Warning
Currently experimental until v1.0.0 release.
Tree-sitter based nvim-cmp completion source for lowerCamelCase variable names based on type.
It's common to name variables after their type in strongly-typed languages such as Java.
For example, a variable name with the type LinkedHashSet
could be linkedHashSet
, hashSet
, or set
:
LinkedHashSet l // suggest linkedHashSet
LinkedHashSet h // suggest hashSet
LinkedHashSet s // suggest set
Other editors such as VS Code also provide these completion suggestions.
If you use lazy.nvim as your plugin manager:
{
'gbroques/cmp-variable-type',
dependencies = {
'hrsh7th/nvim-cmp',
'nvim-treesitter/nvim-treesitter'
},
ft = 'java'
}
require('cmp').setup({
sources = {
{ name = 'variable_type' },
},
})
The type
is returned within the data
element of the completion_item
for each entry
.
If you want to customize the menu appearance to show the type as the source, then you might have the following code:
local cmp = require('cmp')
cmp.setup {
formatting = {
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind)
-- Source
local data = entry.completion_item.data
local variable_type = data ~= nil and data.type or 'Type'
vim_item.menu = ({
-- 👇 Show type (e.g. LinkedHashSet) as source in completion menu.
variable_type = variable_type,
buffer = "[Buffer]",
nvim_lsp = "[LSP]",
luasnip = "[LuaSnip]",
nvim_lua = "[Lua]",
latex_symbols = "[LaTeX]",
})[entry.source.name]
return vim_item
end
},
}
Currently only supports Java. See test/Test.java for testing.
It should complete variables in the following places.
-
For fields declarations in class bodies:
class Example { private final CompletableFuture f ^ suggest future }
-
For parameter names in constructors:
class Example { Example(CompletableFuture f) ^ suggest future }
-
For parameter names in method declarations:
class Example { private String getValue(CompletableFuture f) ^ suggest future }
-
And for local variable names in method bodies:
class Example { private String getValue() { CompletableFuture f } ^ suggest future }
Pull requests are welcome for other languages like C#, Kotlin, and Scala.
-
Doesn't work for Java generic types. For example:
LinkedHashSet<String> l ^ doesn't suggest linkedHashSet
This is because the Java tree-sitter grammar parses incomplete generic type declarations as binary expressions.
Changes to the Java tree-sitter grammar should be made before attempting to work around that.
-
Currently doesn't work for constants. For example:
class Example { private static final Logger L ^ doesn't suggest LOGGER }