Git Product home page Git Product logo

local-highlight.nvim's Introduction

local-highlight.nvim

Using regexes and extmarks to highlight uses of word under the cursor. Keeps updates local to currently visible lines, thus enabling blazingly fast performance.

In Action

recording

Performance

This plugin replaces nvim-treesitter/nvim-treesitter-refactor highlight-definitions which performs poorly on large files.

install

Using Lazy:

  {
      'tzachar/local-highlight.nvim',
      config = function()
        require('local-highlight').setup()
      end
  },

Make sure to specify file types to attach to, or use the attach interface documented below.

Why Another Highlight Plugin?

Multiple plugins to highlight the word under the cursor exist. However, none of them solved all of the following issues for me:

  1. Performance (especially on large files)
  2. Highlight mechanics: by using extmarks, the current format of each highlighted word remains the same (e.g., italics, treesitter highlights)

Setup

You can setup local-highlight as follows:

require('local-highlight').setup({
    file_types = {'python', 'cpp'}, -- If this is given only attach to this
    -- OR attach to every filetype except:
    disable_file_types = {'tex'},
    hlgroup = 'Search',
    cw_hlgroup = nil,
    -- Whether to display highlights in INSERT mode or not
    insert_mode = false,
    min_match_len = 1,
    max_match_len = math.huge,
    highlight_single_match = true,
})

hlgroup

Specify the highlighting group to use.

By default, local-highlight will use the LocalHighlight highlight group, which it defines upon startup. If the group is already defined elsewhere in your config then it will not be overwritten. You can also use any other group you desire, e.g., see above where Search is used.

cw_hlgroup

Specify the highlighting group to use for the word under the cursor. Defaults to nil, which means "Do not apply any highlighting".

file_types and disable_file_types

The plugin works out of the box if you want to use FileTypes to attach to buffers.

To control this behavior, you have the option of setting the following options: file_types: nil by default, meaning attach to all file types. If set to a table, should contain file types relevant to the FileType autocommand, and will instruct the plugin to attach only to the specified fule types. disable_file_types: nil by default, meaning no exceptions when attaching to buffers. If set to a table, each fie type specified in the table will be skipped when attaching to buffers.

If you set file_types to an empty table, {}, local-highlight will not attach to any buffer on its own, and will leave all attach logic to the user.

insert_mode

If set to true, will also work during insert mode.

min_match_len and max_match_len

Set lower and upper limits on the length of the word being matched.

highlight_single_match

Set to false to stop highlighting words that only appear once.

API

If you want to directly attach the plugin to your buffers, you can use any autocommand to attach an event to your liking. For example, to attach to any buffer:

vim.api.nvim_create_autocmd('BufRead', {
  pattern = {'*.*'},
  callback = function(data)
    require('local-highlight').attach(data.buf)
  end
})

The plugin will take care not to reattach and to delete the autocommands when the buffer is closed.

Callbacks

Match Count

You can request the current count of matches. This can be used, e.g., in a status line plugin:

require('local-highlight').match_count(bufnr)

where bufnr is the buffer number the count is requested for or 0 for the current buffer.

User Commands

LocalHighlightToggle

Toggle local highlighting for the current buffer.

LocalHighlightOff

Turn local highlighting off for the current buffer.

LocalHighlightOn

Turn local highlighting on for the current buffer.

LocalHighlightStats

Echo timing information: total number of invocations and the average running time in milliseconds.

How the Plugin Works

local-highlight will attach to a buffer and register an autocommand for the CursorHold event. Once the event fires, local-highlight will grab the word under the cursor and will highlight all of the usages of the same word in the visible lines of the buffer.

One implication of using CursorHold is that interactivity depends on updatetime, which is 4000 by default. A good advice is to set it to something more reasonable, like 500, to get good interactivity.

local-highlight.nvim's People

Contributors

blakejc94 avatar casprwang avatar github-actions[bot] avatar indianboy42 avatar momepp avatar olimorris avatar rdkang avatar tombh avatar tzachar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

local-highlight.nvim's Issues

Words in string should be excluded

Currently the highlight included the same symbol in strings, which doesn't make sense to me. For example, the "vim" in the string "shiracamus/vim-syntax-x86-objdump-d" is not a lua symbol and should not have been highlighted. I believe treesitter is capable of avoiding this.

image

can't make the plugin work

Love the idea!

I have placed the following in my _vimrc:

        'tzachar/local-highlight.nvim',
        config = function()
          require('local-highlight').setup({
              file_types = {'python'},
              hlgroup = 'TSDefinitionUsage',
          })
        end
    },

(I didn't copy the separate setup code from your README as it seems to duplicate the above).

Still nothing happens in my python file. I tried to verify activation by manually typing :LocalHighlightOn but still nothing happens. (BTW, all LocalHighlight* commands do not prompt the current status, might be helpful to add).

Anything that might indicate what the problem is? Or did I get something wrong in the install/use?

Thanks!

[Bug]: Doesn't highlight on first open buffer

The plugin doesn't work on the first buffer I open, I have to switch to another buffer then the plugin will work.

For example:

  1. Open nvim ./general (Doesn't highlight but I can use LocalHighlightToggle to enable)
  2. Switch to any other buffer (Highlight now activated)
return {
    {
        "tzachar/local-highlight.nvim",
        event = "VeryLazy",
        config = function()
            require("local-highlight").setup({
                file_types = nil,
                disable_file_types = nil,
                hlgroup = "Error",
                cw_hlgroup = "Error",
            })
        end,
    },
}

Add option to clear reference on CursorMoved and/or CursorMovedI

Pretty self explanatory. I can start a pull request if you want. So far as a work around, I created a autocmd and call the preexisting clear function so it should be pretty easy to implement. You can set a boolean in the setup function.

vim.api.nvim_create_autocmd({ 'CursorMoved', 'CursorMovedI' }, {
	buffer = event.buf,
	callback = function()
		require('local-highlight').clear_usage_highlights(event.buf)
	end,
})

4 second highlight/de-highlight delay

Any idea why I'm seeing a 4 second highlight delay? I checked the source to see if I could find a config for the delay for debounce, etc, but I didn't see anything. It also takes 4 seconds to de-highlight. I'm 99% sure this delay is synthetic, but I can't find the source. I commented all of my Lazy packages except yours (mason also commented, so no lsps running). Still 4 second delay.

  • WSL on windows (vmmem 100%-CPU bug not in action). Everything else "snappy".
  • Editing my small init.lua file. 277 lines.
  • nvim 0.9.2
  • Tmux if that matters
    {
        'tzachar/local-highlight.nvim',
        config = function()
            require('local-highlight').setup({
                file_types = {'python', 'cpp', 'lua'}, -- If this is given only attach to this
                -- OR attach to every filetype except:
                disable_file_types = {'tex'},
                hlgroup = 'Search',
                cw_hlgroup = nil,
                -- Whether to display highlights in INSERT mode or not
                insert_mode = false
            })
        end
    }

:LocalHighlightStat
Total Usage Count : 2
Average Running Time : 0.210606 msec

tzachar/local-highlight.nvim
neovim/nvim-lspconfig
lukas-reineke/indent-blankline.nvim
nvim-treesitter/nvim-treesitte
hrsh7th/nvim-cm
numToStr/Comment.nvim
nvim-telescope/telescope.nvi

image

image

Thanks!

Highlight not work on line with comment

I'm using the default configuration. When i highlight travelers in the commented line the matches does not get highlighted, only if i uncomment the line.

Actual behavior

1

Expected to work in commented line

2

Minimum number of occurrences to highlight

Hi, thanks for your effort,
Right now there is no way to prevent highlighting in cases when there is only 1 occurrence.
Minimum number of occurrences to highlight would be a nice to have feature.

How to disable the plugin per default?

Hi,
I couldnt find a solution for this yet: How can I start neovim with this plugin loaded but disabled?
If I want to use it, I would like to execute the user command "LocalHighlightToggle" explicitly.

I tried it via
config = function() require('local-highlight').setup({ default = false, })

but it did not work.
I'm not sure if I miss something obvious here.

Highlight single match does not work.

Hi, I wanted to test this freshly merged feature: #22 (thank you @tzachar for merging)

So I updated local-highlight.nvim to the current master branch.

However, I have no changed behavior than before. When same words occur multiple times in the buffer, only the OTHER words are highlighted, not the one which my cursor is at.

This is my local-highlight.nvim config:

return {
  'tzachar/local-highlight.nvim',
  config = function()
    require('local-highlight').setup({
      file_types = {'xyz'},
      highlight_single_match = true
    })

    vim.keymap.set('n', '<leader>ph', vim.cmd.LocalHighlightToggle, { expr = false, silent = true, desc = "Toggle local-highlight.nvim"})
  end,
}

The red rectangle shows the current behaviour.
image

Do you have any suggestions for me?
Regards

Plugin is not attached to the buffer with the default config

Hi, by default config M.config.file_types has been set to {}

by checking for nil value of this line

elseif M.config.file_types == nil then

this condition causes the evaluation to skip creating an autocmd to attach the buffer

i can solve it by changing this line to next(M.config.file_types) == nil

Edit: Created PR #15

[Feature] Some suggestions

First of all, thanks for this plugin.

These are some options it would be great to add because it seems that as of now, there are no other plugins offering these features:

  • Enable word highlight in all buffers (e.g. quickfix), not just certain file types.

  • Customize highlight colour for the current word.

  • Define custom keywords to always highlight, with highlight groups. For example:

{
  keywords = {
    { "TODO",  "Todo" },
    { "ERROR", "Error" },
    { "FIXME", "Error" },
    { "NOTE",  "Comment" },
  },
}

and custom highlight groups, for example:

{
  highlight = {
    Todo    = { gui = "bold,italic", guifg = "Red" },
    Error   = { gui = "bold,italic", guifg = "Orange" },
    Comment = { gui = "bold,italic", guifg = "Grey" },
  },
}

also, it would be great to let the user define the custom keywords as regex patterns if needed.

[Bug] No highlight because `TSDefinitionUsage` is a non-existent highlight

After installing the plugin, I found that here:

'TSDefinitionUsage',

it is defined a highlight which is not existent in my setup, thus the plugin doesn't highlight any word.

I wonder where that highlight comes from, also it would be great to let the user configure the highlight by choosing something different (or by manually defining a new one with background, foreground, style etc.).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.