diff options
| author | Steven Sojka <steelsojka@users.noreply.github.com> | 2020-08-14 06:42:33 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-08-14 06:42:33 -0500 |
| commit | 52420544ff5b8d19837f7e5695e3b37aed9add75 (patch) | |
| tree | 11286f402ffc122c9dd17b71cab52282f09f1eb4 /lua/nvim-treesitter/ts_utils.lua | |
| parent | 1846d92ec62c5ac6403387b64a8ee3f97a59b765 (diff) | |
| parent | 282e33ad9c96a44a092ab8a356bba7626c838b68 (diff) | |
Merge pull request #284 from steelsojka/fix-usages
fix(definitions): optimize and fix definition highlighting
Diffstat (limited to 'lua/nvim-treesitter/ts_utils.lua')
| -rw-r--r-- | lua/nvim-treesitter/ts_utils.lua | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/lua/nvim-treesitter/ts_utils.lua b/lua/nvim-treesitter/ts_utils.lua index bf5b2208..0a5cbc60 100644 --- a/lua/nvim-treesitter/ts_utils.lua +++ b/lua/nvim-treesitter/ts_utils.lua @@ -195,4 +195,34 @@ function M.node_to_lsp_range(node) return rtn end +--- Memoizes a function based on the buffer tick of the provided bufnr. +-- The cache entry is cleared when the buffer is detached to avoid memory leaks. +-- @param fn: the fn to memoize +-- @param bufnr_fn: a function that receives all arguments passed to the function +-- and returns the bufnr from the arguments +-- @returns a memoized function +function M.memoize_by_buf_tick(fn, bufnr_fn) + local bufnr_fn = bufnr_fn or function(a) return a end + local cache = {} + + return function(...) + local bufnr = bufnr_fn(...) + local tick = api.nvim_buf_get_changedtick(bufnr) + + if cache[bufnr] then + if cache[bufnr].last_tick == tick then + return cache[bufnr].result + end + else + cache[bufnr] = {} + api.nvim_buf_attach(bufnr, false, { on_detach = function() cache[bufnr] = nil end }) + end + + cache[bufnr].last_tick = tick + cache[bufnr].result = fn(...) + + return cache[bufnr].result + end +end + return M |
