为Java配置Neovim
#java #neovim

认为这是专门用于Java编程的整个基础架构是非常错误的。使用此语言进行编程的当前文化以及C#©是IDE的整个环境。

我不会否认,将Intellij与Java一起使用非常好! Porco©m,我坚信可以使用Neovim等简单的文本编辑器来使用此语言。

但是,为什么不使用插件在Intellij中激活Neovim模式?

我已经在代码编辑器和IDE中测试了这些插件,并使用功能强大的GUI和徒劳的选项测试,这是让我失望的是IDE的标准映射。要使用IDE的全部功能,有必要配置与NeoVim一起使用的所有标准映射以及图案映射未涵盖的功能。

当我喜欢Neovim时,我决定将其配置得更好,以满足使用它来编程Java。

你需要什么

  • Nevovi 0.7+
  • jdtls(语言服务器标准日食)

安装插件

开始,首先必须安装包装。我在大多数配置中都使用月亮:

git clone --depth 1 https://github.com/wbthomason/packer.nvim\
 ~/.local/share/nvim/site/pack/packer/start/packer.nvim

安装包装器后,让我们首先安装插件。在我的配置中,我创建一个lua/plugins.lua文件并在我的koud1上执行它:

require("plugins")

plugins.lua文件中,我将实例化包裹,并将所有必要的插件声明以配置LSP到Java。


-- instancia o Packer
local status, packer = pcall(require, "packer")
if (not status) then
  print("Packer is not installed")
  return
end

vim.cmd [[packadd packer.nvim]]

-- aqui eu declaro todos os meus plugins
packer.startup(function(use)
  use 'wbthomason/packer.nvim'  -- necessário
  use 'nvim-treesitter/nvim-treesitter' -- syntax highlighting
  use 'neovim/nvim-lspconfig' -- provê configurações padrão de lsp
  use 'hrsh7th/cmp-nvim-lsp' -- auto complete
  use 'hrsh7th/nvim-cmp' -- auto complete
  use 'hrsh7th/cmp-buffer' -- auto complete
  use 'L3MON4D3/LuaSnip' -- provê snippets 
  use 'onsails/lspkind.nvim' -- provê ícones para o lsp
  use 'mfussenegger/nvim-jdtls' -- plugin com todas as features do jdtls
end)

好!发表此声明后,只需保存文件,重新启动neovim并运行:PackerSync命令。它将安装并编译已声明的插件。

配置Neovim

下一部分是配置这些插件以正确运行。
由于只有在打开.java文件时才有必要JDTL,因此建议是为此使用Neovim Filetype。

此插件是本机的,只需创建一个名为Koud5的文件夹,您的Koud1所在,其中我们将创建Koud7:
file

$ mkdir ftplugin
$ cd ftplugin
$ touch java.lua

打开此文件,我们将启动配置。

我们将配置自动完成源的第一件事。在这种情况下,我们只会召集Neovim的cmp_nvim_lsp默认值。

另一个重要的事情是激活两个通知的动态记录:didChangeWatchedFilesdidChangeConfiguration

local capabilities = require('cmp_nvim_lsp').default_capabilities(vim.lsp.protocol.make_client_capabilities())

capabilities.workspace = {
  configuration = true,
  didChangeWatchedFiles = {
    dynamicRegistration = true
  },
  didChangeConfiguration = {
    dynamicRegistration = true
  }
}

我们将配置的下一件事是“保存格式”和keymaps的功能。所有这些都是在函数on_attach中定义的。

local on_attach = function(client, bufnr)
  -- Aqui define <Ctrl-x> + <Ctrl-o> para ativar o autocomplete, mas ele irá se ativar quando você digita também
  vim.api.nvim_buf_set_option(bufnr, 'omnifunc', "v:lua.vim.lsp.omnifunc")
  vim.api.nvim_create_autocmd("BufWritePre", {
    group = vim.api.nvim_create_augroup('Format', { clear = true }),
    buffer = bufnr,
    callback = function()
      vim.lsp.buf.format()
    end
  })
  local bufopts = { noremap = true, silent = true, buffer = bufnr }
  local opts = { noremap = true, silent = true }
  vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts)
  vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts)
  vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, bufopts)
  vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts)
  vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, bufopts)
  vim.keymap.set('n', '<space>K', vim.lsp.buf.signature_help, bufopts)
  vim.keymap.set('n', 'gt', vim.lsp.buf.type_definition, bufopts)
  vim.keymap.set('n', '<F2>', vim.lsp.buf.rename, bufopts)
  vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, bufopts)
  vim.keymap.set('n', '<space>ca', vim.lsp.buf.code_action, bufopts)
  vim.keymap.set('n', '<space>f', vim.lsp.buf.format, bufopts)
  vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, opts)
  vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, opts)
  vim.keymap.set('n', ']d', vim.diagnostic.goto_next, opts)
end

下一部分是定义LSP的更通用配置。

local project_name = vim.fn.fnamemodify(vim.fn.getcwd(), ':p:h:t')
local workspace_dir = "/home/eronads/workspaces/" .. project_name


local config = {
  flags = {
    allow_incremental_sync = true
  },
  -- O comando para invocar o lsp. Eu recomendo seguir o caminho abaixo, através do executável em python
  cmd = {
    '/caminho/para/jdtls',

    -- Na pasta do jdtls terá algumas pastas com configurações específicas do OS. Indique este caminho de acordo com seu OS
    '-configuration', '/caminho/para/pasta-do-jtdls/config_SEU-OS',

    -- Para cada projeto, o lsp cria uma pasta com um workspace. Aqui você irá indicar onde irão ficar essas pastas.  
    '-data', workspace_dir
  },

-- A raiz do seu projeto
  root_dir = require("jdtls.setup").find_root({ 'gradlew', '.git', 'mvnw' }),
  on_attach = on_attach,
  capabilities = capabilities,

-- Outras configurações, recomendável repetir
  settings = {
    java = {
      signatureHelp = { enabled = true },
      contentProvider = { preferred = 'fernflower' },
      completion = {


-- Se precisar adicionar uma classe para import estático
        favoriteStaticMembers = {
          "org.hamcrest.MatcherAssert.assertThat",
          "org.hamcrest.Matchers.*",
          "org.hamcrest.CoreMatchers.*",
          "org.junit.jupiter.api.Assertions.*",
          "java.util.Objects.requireNonNull",
          "java.util.Objects.requireNonNullElse",
          "org.mockito.Mockito.*"
        },
        filteredTypes = {
          "com.sun.*",
          "io.micrometer.shaded.*",
          "java.awt.*",
          "jdk.*",
          "sun.*",
        },
      },
      sources = {
        organizeImports = {
          starThreshold = 9999,
          staticStarThreshold = 9999,
        },
      },
      codeGeneration = {

   -- Instrução para geração de métodos populares
        toString = {
          template = "${object.className}{${member.name()}=${member.value}, ${otherMembers}}"
        },
        hashCodeEquals = {
          useJava7Objects = true,
        },
        useBlocks = true,
      },
      configuration = {

-- Indique aqui as versões de java e as pastas onde se encontram
        runtimes = {
          {
            name = "JavaSE-17",
            path = "/caminho/para/pasta/do/java/17.0.7-tem/",
            default = true
          },
        }
      },
    },
  }
}

CMP,LSPKIND和LSP的执行的剩余,它可以执行Padrã£O:

local cmp = require 'cmp';
local lspkind = require 'lspkind'

cmp.setup({
  snippet = {
    expand = function(args)
      require('luasnip').lsp_expand(args.body)
    end
  },
  mapping = cmp.mapping.preset.insert({
    ['C-Space'] = cmp.mapping.complete(),
    ['<CR>'] = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }),
  }),
  sources = cmp.config.sources({
    { name = 'nvim_lsp' },
    { name = 'buffer' },
  }),
  formatting = {
    format = lspkind.cmp_format({
      mode = 'symbol',       -- show only symbol annotations
      maxwidth = 50,         -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters)
      ellipsis_char = '...', -- when popup menu exceed maxwidth, the truncated part would show ellipsis_char instead (must define maxwidth first)

      -- The function below will be called before any actual modifications from lspkind
      -- so that you can provide more controls on popup customization. (See [#30](https://github.com/onsails/lspkind-nvim/pull/30))
      before = function(entry, vim_item)
        return vim_item
      end
    })
  }
})


require('jdtls').start_or_attach(config)

保存文件。从这里,您的Neovim已经为Java配置了。

最后结果

开始服务:

Image description

自动完成操作:

Image description

它已经带有一些有助于类和接口创建的片段:

Image description

诊断:

Image description

代码操作(包括Javeiros的宠儿):

Image description

完整配置

我的完整配置在github中。

除了Java的配置外,它还已经配置为:

  • 打字稿;
  • javascript;
  • vue;
  • react;
  • GO;
  • PHP.

此外,它还有其他一些插件,可为我提供轻巧的基本配置,用于日常编辑。