GithubHelp home page GithubHelp logo

jose-elias-alvarez / null-ls.nvim Goto Github PK

View Code? Open in Web Editor NEW
3.6K 17.0 798.0 2.48 MB

Use Neovim as a language server to inject LSP diagnostics, code actions, and more via Lua.

License: Other

Makefile 0.07% Lua 99.87% JavaScript 0.01% Shell 0.05%
neovim neovim-plugin lsp neovim-lsp

null-ls.nvim's Introduction

ARCHIVED

null-ls is now archived and will no longer receive updates. Please see this issue for details.

null-ls.nvim

Use Neovim as a language server to inject LSP diagnostics, code actions, and more via Lua.

Motivation

Neovim's LSP ecosystem is growing, and plugins like telescope.nvim and trouble.nvim make it a joy to work with LSP features like code actions and diagnostics.

Unlike the VS Code and coc.nvim ecosystems, Neovim doesn't provide a way for non-LSP sources to hook into its LSP client. null-ls is an attempt to bridge that gap and simplify the process of creating, sharing, and setting up LSP sources using pure Lua.

null-ls is also an attempt to reduce the boilerplate required to set up general-purpose language servers and improve performance by removing the need for external processes.

Status

null-ls is in beta status. Please see below for steps to follow if something doesn't work the way you expect (or doesn't work at all).

null-ls is developed on and tested against the latest stable version of Neovim. Support for versions built from HEAD is provided on a best-effort basis, and users are encouraged to contribute fixes to any issues exclusive to these versions.

Features

null-ls sources are able to hook into the following LSP features:

  • Code actions

  • Diagnostics (file- and project-level)

  • Formatting (including range formatting)

  • Hover

  • Completion

null-ls includes built-in sources for each of these features to provide out-of-the-box functionality. See BUILTINS for a list of available built-in sources and BUILTIN_CONFIG for instructions on how to set up and configure these sources.

null-ls also provides helpers to streamline the process of spawning and transforming the output of command-line processes into an LSP-friendly format. If you want to create your own source, either for personal use or for a plugin, see HELPERS for details.

Setup

Install null-ls using your favorite package manager. The plugin depends on plenary.nvim, which you are (probably) already using.

To get started, you must set up null-ls and register at least one source. See BUILTINS for a list of available built-in sources and CONFIG for information about setting up and configuring null-ls.

local null_ls = require("null-ls")

null_ls.setup({
    sources = {
        null_ls.builtins.formatting.stylua,
        null_ls.builtins.diagnostics.eslint,
        null_ls.builtins.completion.spell,
    },
})

Documentation

The definitive source for information about null-ls is its documentation, which contains information about how null-ls works, how to set it up, and how to create sources.

Contributing

Contributions to add new features and built-ins for any language are always welcome. See CONTRIBUTING for guidelines.

Examples

Parsing buffer content

The following example demonstrates a diagnostic source that will parse the current buffer's content and show instances of the word really as LSP warnings.

local null_ls = require("null-ls")

local no_really = {
    method = null_ls.methods.DIAGNOSTICS,
    filetypes = { "markdown", "text" },
    generator = {
        fn = function(params)
            local diagnostics = {}
            -- sources have access to a params object
            -- containing info about the current file and editor state
            for i, line in ipairs(params.content) do
                local col, end_col = line:find("really")
                if col and end_col then
                    -- null-ls fills in undefined positions
                    -- and converts source diagnostics into the required format
                    table.insert(diagnostics, {
                        row = i,
                        col = col,
                        end_col = end_col + 1,
                        source = "no-really",
                        message = "Don't use 'really!'",
                        severity = vim.diagnostic.severity.WARN,
                    })
                end
            end
            return diagnostics
        end,
    },
}

null_ls.register(no_really)

Parsing CLI program output

null-ls includes helpers to simplify the process of spawning and capturing the output of CLI programs. This example shows how to pass the content of the current buffer to markdownlint via stdin and convert its output (which it sends to stderr) into LSP diagnostics:

local null_ls = require("null-ls")
local helpers = require("null-ls.helpers")

local markdownlint = {
    method = null_ls.methods.DIAGNOSTICS,
    filetypes = { "markdown" },
    -- null_ls.generator creates an async source
    -- that spawns the command with the given arguments and options
    generator = null_ls.generator({
        command = "markdownlint",
        args = { "--stdin" },
        to_stdin = true,
        from_stderr = true,
        -- choose an output format (raw, json, or line)
        format = "line",
        check_exit_code = function(code, stderr)
            local success = code <= 1

            if not success then
                -- can be noisy for things that run often (e.g. diagnostics), but can
                -- be useful for things that run on demand (e.g. formatting)
                print(stderr)
            end

            return success
        end,
        -- use helpers to parse the output from string matchers,
        -- or parse it manually with a function
        on_output = helpers.diagnostics.from_patterns({
            {
                pattern = [[:(%d+):(%d+) [%w-/]+ (.*)]],
                groups = { "row", "col", "message" },
            },
            {
                pattern = [[:(%d+) [%w-/]+ (.*)]],
                groups = { "row", "message" },
            },
        }),
    }),
}

null_ls.register(markdownlint)

FAQ

Something isn't working! What do I do?

NOTE: If you run into issues when using null-ls, please follow the steps below and do not open an issue on the Neovim repository. null-ls is not an actual LSP server, so we need to determine whether issues are specific to this plugin before sending anything upstream.

  1. Make sure your configuration is in line with the latest version of this document.
  2. Enable debug mode and check the output of your source(s). If the CLI program is not properly configured or is otherwise not running as expected, that's an issue with the program, not null-ls.
  3. Check the documentation for available configuration options that might solve your issue.
  4. If you're having trouble configuring null-ls or want to know how to achieve a specific result, open a discussion.
  5. If you believe the issue is with null-ls itself or you want to request a new feature, open an issue and provide the information requested in the issue template.

My :checkhealth output is wrong! What do I do?

Checking whether a given command is executable is tricky, and null-ls' health check doesn't handle all cases. null-ls' internal command resolution is independent of its health check output, which is for informational purposes.

If you're not sure whether a given command is running as expected, enable debug mode and check your log.

How do I format files?

Use vim.lsp.buf.format(). See :help vim.lsp.buf.format() for usage instructions.

How do I format files on save?

See this wiki page.

How do I stop Neovim from asking me which server I want to use for formatting?

See this wiki page.

How do I view project-level diagnostics?

For a built-in solution, use :lua vim.diagnostic.setqflist(). You can also use a plugin like trouble.nvim.

How do I enable debug mode and get debug output?

  1. Set debug flag to true in your config:

    require("null-ls").setup({
        debug = true,
    })
  2. Use :NullLsLog to open your debug log in the current Neovim instance or :NullLsInfo to get the path to your debug log.

As with LSP logging, debug mode will slow down Neovim. Make sure to disable the option after you've collected the information you're looking for.

Does it work with (other plugin)?

In most cases, yes. null-ls tries to act like an actual LSP server as much as possible, so it should work seamlessly with most LSP-related plugins. If you run into problems, please try to determine which plugin is causing them and open an issue.

This wiki page mentions plugins that require specific configuration options / tweaks to work with null-ls.

How does it work?

Thanks to hard work by @folke, the plugin wraps the mechanism Neovim uses to spawn language servers to start a client entirely in-memory. The client attaches to buffers that match defined sources and receives and responds to requests, document changes, and other events from Neovim.

Will it affect my performance?

More testing is necessary, but since null-ls uses pure Lua and runs entirely in memory without any external processes, in most cases it should run faster than similar solutions. If you notice that performance is worse with null-ls than with an alternative, please open an issue!

I am seeing a formatting timeout error message

This issue occurs when a formatter takes longer than the default timeout value. This is an automatic mechanism and controlled by Neovim. You might want to increase the timeout in your call:

vim.lsp.buf.format({ timeout_ms = 2000 })

Tests

The test suite includes unit and integration tests and depends on plenary.nvim. Run make test in the root of the project to run the suite or FILE=filename_spec.lua make test-file to test an individual file.

To avoid a dependency on any plugin managers, the test suite will set up its plugin runtime under the ./tests directory to always have a plenary version available.

If you run into plenary-related issues while running the tests, make sure you have an up-to-date version of the plugin by clearing that cache with: make clean.

All tests expect to run on the latest release version of Neovim and are not guaranteed to work on versions built from HEAD.

Alternatives

null-ls.nvim's People

Contributors

abzcoding avatar andrewferrier avatar aoswalt avatar aspeddro avatar b0o avatar carrascomj avatar cenk1cenk2 avatar cenobantur avatar danilshvalov avatar eshepelyuk avatar euoia avatar folke avatar furkanzmc avatar iamthefij avatar jose-elias-alvarez avatar kylo252 avatar meck avatar muniftanjim avatar mvllow avatar nawordar avatar numtostr avatar observeroftime avatar oncomouse avatar raviqqe avatar sirbrillig avatar sloff avatar ssbanerje avatar syphar avatar tastyep avatar vuki656 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

null-ls.nvim's Issues

Cannot call setup function with recent changes

I updated my plugins today and noticed that when trying to run the following config:

require("null-ls").config {}
require("lspconfig")["null-ls"].setup {}

I get the following error:

packer.nvim: Error running config for nvim-lspconfig: ...site/pack/packer/start/null-ls.nvim/lua/null-ls/init.lua:31: attempt to call field 'setup' (a nil value)

Is this on my end or am I calling this incorrectly? I have lspconfig to installed and have been using this plugin for a while now along with your ts-utils plugin.

Thanks for any help you can provide.

Expected table got null

Hey, thanks for the cool plugin.

I'm using it in fairly large codebases and seeing some random weird errors from time to time so ill try to post what happens.

This is the one that pops up quite often after pasting some code in.

In this specific case, all I did was paste code from line 66 to 70 (useFieldArray hook). Let me know if I can provide any other info to help debug this.

image

Builtin clang-format formatter not working because of missing filename argument

FAQ

  • I have checked FAQ and it didn't resolve my problem.

Issues

  • I have checked existing issues and there are no issues with the same problem.

Neovim Version

0.5

Steps to reproduce

Open a file with filetype "c", "cpp", "cs" or "java" and try to use builtin clang_format (clang-format) to format the current buffer. Buffer does not get formatted, because the -assume-filename option value does not get set.

Expected behavior

Buffer content gets formatted using clang-format

Actual behavior

Buffer content does not get formatted.

Debug log

error: empty filenames are not allowed
Error: clang-format exited with exit code 1.

Help

Yes

Implementation help

No response

Question/Bug: Too late formatting and long update time

does the null-ls server update only depending on the debounce period or other triggers too?
I have noticed that when I edit and save my file it doesn't format it on the first save, neither the second if its too fast. It takes some time and then formats the file. I am trying to move to null-ls.nvim from efm.

Export from_pattern/from_patterns/from_json from diagnostics module

Issues

  • I have checked existing issues and there are no existing ones with the same request.

Feature description

Thanks for your great work on null-ls. It's a great idea and I'm already using some of the built-in diagnostic helpers.

However, when building my own, I'm a bit surprised that the from_pattern/from_json functions from the null-ls.builtins.diagnostics module are not exported. To me, these functions are both really useful, and kind of essential to match simple regex-style patterns that many linters output. For example, this is typically how you parse responses when using EFM as a language server, for example.

It would be great if these functions were available for custom diagnostic helpers, as well as the built-in ones.

Help

Yes, but I don't know how to start. I would need guidance

Implementation help

Recommendation / opinion on where / how to expose it.

Formatting removes todo-comments' highlights

Hi @jose-elias-alvarez, I am using todo-highlights and have noticed that once buffer is formatted by null-ls comments highlighted by that plugin lose their highlighting. I have reported it to @folke who suggested checking if it is the case with efm as well, which it wasn't after quick test. Please see @folke's suggested direction here folke/todo-comments.nvim#46 (comment). Do you know if that's something that could easily be fixed? I am not sure whether LSP (efm) and null-ls use different methods to modify buffers.

Thanks!

packer.nvim: Error running config for nvim-lspconfig: [string "..."]:0: attempt to index field 'null-ls' (a nil value)

This config causes this error:

require("packer").startup(function(use)
	use({
		"wbthomason/packer.nvim",
	})
	use({
		"neovim/nvim-lspconfig",
		config = function()
			require('lspconfig')['null-ls'].setup({})
		end,
	})
	use({
		"hrsh7th/nvim-compe",
		config = function()
		end,
	})
	use({
		"jose-elias-alvarez/null-ls.nvim",
		requires = "nvim-lua/plenary.nvim",
		config = function()
			require("null-ls").config({})
		end,
	})
end)

This config is fine:

require("packer").startup(function(use)
	use({
		"wbthomason/packer.nvim",
	})
	use({
		"neovim/nvim-lspconfig",
		config = function()
			require('lspconfig')['null-ls'].setup({})
		end,
	})
	-- use({
	-- 	"hrsh7th/nvim-compe",
	-- 	config = function()
	-- 	end,
	-- })
	use({
		"jose-elias-alvarez/null-ls.nvim",
		requires = "nvim-lua/plenary.nvim",
		config = function()
			require("null-ls").config({})
		end,
	})
end)

This config is also fine:

require("packer").startup(function(use)
	use({
		"wbthomason/packer.nvim",
	})
	use({
		"neovim/nvim-lspconfig",
		config = function()
		end,
	})
	use({
		"hrsh7th/nvim-compe",
		config = function()
		end,
	})
	use({
		"jose-elias-alvarez/null-ls.nvim",
		requires = "nvim-lua/plenary.nvim",
		config = function()
			require("null-ls").config({})
			require('lspconfig')['null-ls'].setup({})
		end,
	})
end)

Fix `lsp.buf_request_all`

From what I understand, this issue is fundamentally due to null-ls returning a nil response when Neovim expects an empty table.

@NSteinhoff Could you give me instructions to replicate this so we can make sure it's fixed? I'm having a bit of trouble replicating this based on the scenario you described, because null-ls returns an empty table and everything works as expected.

[Bug] Changelist broken

  • nvim --version: NVIM v0.5.0-dev+1384-gf2906a466
  • Operating system/version: Manjaro

Describe the bug

When I run format, the changelist is all on the first line.

To Reproduce

set encoding=utf-8

filetype plugin indent on
if has('vim_starting')
  let s:pluin_manager_dir='~/.config/nvim/.plugged/vim-plug'
  execute 'set runtimepath+=' . s:pluin_manager_dir
endif
call plug#begin('~/.config/nvim/.plugged')
Plug 'nvim-lua/plenary.nvim'
Plug 'jose-elias-alvarez/null-ls.nvim'
call plug#end()

set number
set nobackup
set nowritebackup
set noswapfile
set updatecount=0
set backspace=indent,eol,start
language messages en_US.utf8

lua << EOF

local null_ls = require'null-ls'

null_ls.setup {
  on_attach = function(client)
    vim.cmd([[autocmd BufWritePost <buffer> lua vim.lsp.buf.formatting()]])
  end,
  sources = {
    null_ls.builtins.formatting.stylua,
  }
}

EOF

Steps to reproduce the behavior:

  1. nvim -u minivimrc -i NONE
  2. :e sample.lua
  3. edit buffer
  4. :write (Format)

After running format, all the lines in the changelist will be on the first line.

Expected behavior

I want the changelist to stay intact.

Screenshots

simplescreenrecorder-2021-06-15_21.09.05.mp4

Thank you!

[Bug]: Filetypes table of user config thrown away by `validate_config` function.

So I've got the following configured in my lsp setup for null-ls:

    null_ls.setup({
        ...
        filetypes = {
            "python",
            "lua",
        },
        ...
    })

I've left out some unrelated configuration and replaced it with ...

The filetypes table is however thrown away by the validate_config
called by the setup function in lua/null-ls/config.lua. Which means
null-ls is activated for every single filetype. Currently I'm using the
following workaround:

M.setup = function(user_config)
    if config._setup then
        return
    end

    -- USER: FIXME: function validate_config throws away the filetypes key in
    -- user config so store it here and set it again later for now
    local filetypes_workaround = user_config.filetypes

    local validated = validate_config(user_config)
    config = vim.tbl_extend("force", config, validated)
    
    -- USER: FIXME: see line 172
    config.filetypes = filetypes_workaround

    if config.sources then
        register(config.sources)
    end
    config._setup = true
end

But I suppose this should be fixed in the validate_config function. On
another note, I think the user should also be able to configure which
capabilities null-ls should have for a file type. Even though I'm only
using null-ls for formatting it seems to register itself with code
actions and diagnostics capabilities too. Although automatically setting
the right capabilities I think the user should be able to configure it
manually first and foremost so that you for instance can disable
something temporarily when working with certain files or if a particular
tool is not working correctly.

Code actions too slow

I don't know why but code actions are too slow. I have keybinding set to ga to bring up the available code actions, It takes around 2-3 seconds to bring up the list of code actions available. How do I reduce this?

[Bug]: `Error detected while processing CursorHold Autocommands for "*":`

This is the error which popped-up using null-ls 0bb8b38 and NVIM v0.5.0-dev+1425-g7da86f55a

Error detected while processing CursorHold Autocommands for "*":
E5108: Error executing lua vim/shared.lua:314: src: expected table, got number
stack traceback:
        vim/shared.lua:314: in function 'list_extend'
        .../pack/packer/start/null-ls.nvim/lua/null-ls/handlers.lua:46: in function 'handler'
        /usr/local/share/nvim/runtime/lua/vim/lsp.lua:1276: in function 'buf_request'
        ...ack/packer/start/lspsaga.nvim/lua/lspsaga/codeaction.lua:192: in function 'code_action'
        ...ack/packer/start/lspsaga.nvim/lua/lspsaga/codeaction.lua:276: in function 'code_action_prompt'
        [string ":lua"]:1: in main chunk
Press ENTER or type command to continue

As you can see it happens for a buffer where null-ls isn't an active client:
image

Steps to reproduce:

  1. Restrict null-ls to some filetypes
  2. Open a buffer of one of the aforementioned filetypes such that null-ls is an active client
  3. Open another buffer for which you have other registered lsp's but not null-ls
  4. Hover

Edit: nice to see github finally implemented markdown for issue titles :)

Feature Request: conditional formatting

Would it be possible to select a formatter based on some conditions?

For example with eslint and prettier, a user could write a condition to check if there is .eslintrc present in the project, if yes, use eslint, if not use prettier.

Awesome work on the plugin btw, its a breeze to set up compared to efm.

When opening a second buffer: Error executing vim.schedule lua callback: [...]/null-ls/init.lua:31: attempt to call field 'setup' (a nil value)

null-ls-bug-second-buffer

See the GIF above:

  • When opening a first buffer, null-ls doesn't throw any errors and my LSP features work great.
  • When opening a second buffer (regardless of through a split window, or just a second buffer), null-ls throws this error:
Error executing vim.schedule lua callback: [...]/null-ls/init.lua:31: attempt to call field 'setup' (a nil value)

My config:

local lsp_status = require('lsp-status')
lsp_status.register_progress()
local nvim_lsp = require('lspconfig')
local on_attach = function(client, bufnr)
  require("null-ls").setup {}
  require("nvim-lsp-ts-utils").setup { eslint_enable_diagnostics = true, eslint_bin = "eslint_d" }
  local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
  local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end

  lsp_status.on_attach(client, bufnr)

  -- Mappings.
  local opts = { noremap=true, silent=true }

  buf_set_keymap('n', '<leader>o', ':TSLspOrganize<CR>', opts)
  -- More keybindings (redacted)
  buf_set_keymap('n', '<leader>j', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
end

nvim_lsp.tsserver.setup { on_attach = on_attach, capabilities = lsp_status.capabilities }

Thanks for your plugins @jose-elias-alvarez!

Add luacheck

Issues

  • I have checked existing issues and there are no existing ones with the same request.

Feature description

Add luacheck as a linter

Help

No

Implementation help

If I find some time I will add this, but if someone wants to beat me to it, I would appreciate it.

Unable to get misspell to work

I have added misspell to my configured source, installed it with go but can't get it to pick up any misspellings from comments or strings in lua files. Should it work that way?

Formatting sync will timeout when formatter errors

FAQ

  • I have checked FAQ and it didn't resolve my problem.

Issues

  • I have checked existing issues and there are no issues already open with the same problem.

Neovim Version

NVIM v0.6.0-dev+61-g6f48c018b

Steps to reproduce

I would guess there are more ways to reproduce this, but this is mine.

  • Setup vim to format on save sync: autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()
  • Config a formatter, in my case deno fmt or prettier that will give exit code >0 and stderr on syntax errors:
  local deno_fmt = {
    method = null_ls.methods.FORMATTING,
    filetypes = {"typescript", "typescriptreact" },
    generator = null_ls.formatter({
      command = "deno",
      args = { "fmt", "-"},
      to_stdin = true
      -- command = "prettier",
      -- args = { "--stdin-filepath", "$FILENAME" },
      -- to_stdin = true,
    }),
  }
  null_ls.config {
    debounce = 150,
    save_after_format = false,
    sources = { deno_fmt }
  }

(I'm using TypeScript code, but I guess use anything else)

  • Change code to have a syntax error
  • Save the file
  • Notice it takes a long time (vim freezes for a bit)
  • :messages: you'll see it timed out vim.lsp.buf.formatting_sync: timeout

Expected behavior

I would expect no timeout / delay

Actual behavior

Delay / timeout :)

Help

Yes, but I don't know how to start. I would need guidance

Implementation help

No response

[Request] Exclude Running Null-LS by Filetypes and Buftypes

I found some compability issues of null-ls with nvim-tree. I got double entries if I use builtins that use filetypes of "*" (like misspell or gitsigns). I assume that's because null-ls will run on that buffer and nvim-tree go haywire.

Screenshot:

nvim-tree

This perhaps could be caused by other plugins or configurations, but debugging that deep will take a huge time. Hopefully simple exclusion will solve the problem.

Ideally an exclude per sources, but perhaps adding global_exclude parameter when calling require('null-ls').config should be suffice for this.

Diagnostics source is not set correctly

FAQ

  • I have checked FAQ and it didn't resolve my problem.

Issues

  • I have checked existing issues and there are no issues with the same problem.

Neovim Version

NVIM v0.6.0-dev

Steps to reproduce

Use builtin diagnostics

    require("null-ls").config({ sources = {builtins.diagnostics.hadolint} })

Expected behavior

The diagnostics source is displayed as hadolint (defaults to generator command).

Actual behavior

The diagnostics source is displayed as null-ls.

Debug log

see explanation below

Help

Yes

Implementation help

The problem is that index in https://github.com/jose-elias-alvarez/null-ls.nvim/blob/main/lua/null-ls/diagnostics.lua#L22 refers to generators that are added to params (after matching filetype), however when the function is calledindex refers to all generators (not matched by filetype) https://github.com/jose-elias-alvarez/null-ls.nvim/blob/main/lua/null-ls/generators.lua#L37. This then leads to generators being nil, and the code defaults to null-ls rather than taking the command configured in the generator.

Possible fixes would be to

  1. pass the relevant generator directly to postprocess instead of relying on an index, or
  2. pass the correct index for the table of filetype matched generators, or
  3. select from all generators in https://github.com/jose-elias-alvarez/null-ls.nvim/blob/main/lua/null-ls/diagnostics.lua#L22.

I would prefer option 1. because I find the index passing a bit convoluted and I don't see any reason for it. But I also haven't looked at much of the rest of the code, so maybe there's a reason.

Per filetype settings for prettier

Using the builtin prettier formatter is there a way to change settings per filetype? E.g. set --tab-width 4 for markdown and 2 for everything else?

Undoing changes sometimes duplicates lines after formatting, effectively breaking undo history.

FAQ

  • I have checked FAQ and it didn't resolve my problem.

Issues

  • I have checked existing issues and there are no issues with the same problem.

Neovim Version

NVIM v0.6.0-dev

Steps to reproduce

I unfortunately have not yet been able to consistently reproduce this bug, but it happens fairly often.

It seems to happen when I'm formatting code with lots of braces/parenthesis, writing the file (this may not matter), and then undoing.

Often, a single additional line is added on undo, right below the area that was formatted.

I have seen this issue with both eslint_d and prettier, so it does not seem related to any formatter in particular.

Expected behavior

Undoing after formatting does not add an extra line.

Actual behavior

Undoing after formatting sometimes adds an additional line and "corrupts" undo history.

This additional line often contains text e.g. )};, which tends to break code. I believe it is a copy of the last line that was formatted in the file.

Debug log

none

Help

No

Implementation help

No response

Linter name in diagnostics

It would be cool to have the option to prefix diagnostics with the linter name. That way diagnostics from multiple linting sources can be distinguished from each other. Efm added a similar feature recently: mattn/efm-langserver#148

[DOCS] Unclear setup instructions in BUILTINS.md

Hey, in the docs for builtins, for every source the doc states that config is set up like so

  • Filetypes: { "asm" }
  • Command: asmfmt
  • Arguments: {}

While configuring mine I assumed the param names would be filetypes, command, and arguments. While this is true for filetypes, and command, arguments actually take args param instead of arguments. Lost a few hours trying to figure it out a few days ago.

More to the point, I doesn't state anywhere in BUILTINS.md that you should use args and not arguments.

I also found that in #35, there was the same problem. I assume I'm not the only person that is going to make that mistake.

What do you think about the examples being written in the following format:

{
    command = 'prettier',
    filetypes = { 'css', 'html' },
    args = { '--no-semi', '--tab-width=4' }
}

That way people can just copy-paste and not have to figure out parameter names.

What do you think?

I'd be happy to open a PR.

done() callback error

I'm seeing this error when opening a file with no diagnostic results (after vint merge #44)Error executing vim.schedule lua callback: .../start/null-ls.nvim/lua/null-ls/builtins/diagnostics.lua:446: attempt to call local 'done' (a nil value) line 446

Any idea what could be causing this? I copied this from one of the other builtins for the PR.

Cannot find module eslint

I have eslint configured as a local dependency of a project but null-ls gives this error when trying to use code actions. error in generator output: Error: Failed to load plugin '@typescript-eslint' declared in '.eslintrc.js#overrides[0]': Cannot find module 'eslint'

Here is my .eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
    es6: true,
  },
  parserOptions: { ecmaVersion: 8 }, // to enable features such as async/await
  ignorePatterns: ['node_modules/*', '.next/*', '.out/*', '!.prettierrc.js'], // We don't want to lint generated files nor node_modules, but we want to lint .prettierrc.js (ignored by default by eslint)
  extends: ['eslint:recommended'],
  overrides: [
    // This configuration will apply only to TypeScript files
    {
      files: ['**/*.ts', '**/*.tsx'],
      parser: '@typescript-eslint/parser',
      settings: { react: { version: 'detect' } },
      env: {
        browser: true,
        node: true,
        es6: true,
      },
      extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended', // TypeScript rules
        'plugin:react/recommended', // React rules
        'plugin:react-hooks/recommended', // React hooks rules
        'plugin:jsx-a11y/recommended', // Accessibility rules
        'plugin:prettier/recommended', // Prettier plugin
      ],
      rules: {
        // We will use TypeScript's types for component props instead
        'react/prop-types': 'off',

        // No need to import React when using Next.js
        'react/react-in-jsx-scope': 'off',

        // This rule is not compatible with Next.js's <Link /> components
        'jsx-a11y/anchor-is-valid': 'off',

        // Why would you want unused vars?
        '@typescript-eslint/no-unused-vars': ['error'],

        // I suggest this setting for requiring return types on functions only where useful
        '@typescript-eslint/explicit-function-return-type': [
          'warn',
          {
            allowExpressions: true,
            allowConciseArrowFunctionExpressionsStartingWithVoid: true,
          },
        ],
        'prettier/prettier': ['error', {}, { usePrettierrc: true }], // Includes .prettierrc.js rules
      },
    },
  ],
}

Dynamic setup per filetype

I'm not sure if this is possible but I figured I would ask.

What I am looking for is for null-ls to only configure what it needs for the filetype that it's looking at. Or append configuration as it sees filetypes.

For example:

  • filetype js: eslint and prettier are configured
  • filetype py: flake8 and black are configured
  • etc..

What I'm trying to avoid is instantiating null-ls with all of my configuration up front. I would like to wait until it's absolutely necessary to pass that config.

There may be an inherent limitations with how lsp-config or the language servers work in general. If that's the case it's not that big of a deal, but if something can be done to support this I would appreciate it.

Stylua ignores the given argument list.

Hi, I have the following configuration:

local null_ls = require("null-ls")
null_ls.setup({
on_attach = function()
		vim.cmd([[
      augroup lsp_format_on_save
        autocmd! * <buffer>
        autocmd BufWritePost <buffer> lua vim.lsp.buf.formatting()
      augroup END
    ]])
	end,
	save_after_formatting = true,
	sources = {
		null_ls.builtins.formatting.prettier.with({
			filetypes = { "html", "css", "json", "markdown", "yaml" },
		}),
		null_ls.builtins.formatting.stylua.with({
			filetypes = { "lua" },
			command = "stylua",
			arguments = { "--indent-width", "2", "--indent-type",  "Spaces", "-" },
		}),
	},
})

It is working, but stylua ignores the arguments list. If you look in the code pasted above, it has tabs instead of spaces.

Enable excluding filetypes

I enabled the gitsigns code actions, which works great for all my code files. However, on some filetypes, such as Neogit, I get an error when the generator tries to get a code action for a non-existent file.

Is it possible for filetypes to be enabled for "*" except for a few?

null-ls server not starting

Since the most recent updates, I've been this issue. Am I doing something wrong?

require("packer").startup(function(use)
  use { "wbthomason/packer.nvim" }

  use {
    "jose-elias-alvarez/null-ls.nvim",
    requires = {
      { "nvim-lua/plenary.nvim" },
      { "neovim/nvim-lspconfig" }
    },
    config = function()
      require("null-ls").config {
        sources = {
          require("null-ls").builtins.formatting.stylua,
        }
      }
      require("lspconfig")["null-ls"].setup {
        on_attach = function()
          vim.cmd([[autocmd BufWritePost <buffer> lua vim.lsp.buf.formatting()]])
        end
      }
    end
  }
end)

Plugin manager support

This issue was, if my understanding is correct, caused by a difference in how packer.nvim and vim-plug modify Neovim's rtp. The solution in #3 fixed vim-plug, and the same solution should (again, if my understanding is correct) make it so that if the user's Neovim config is aware of null-ls, the server should be, too. However, I want to test other plugin managers and verify that they work, since it's a serious issue that's hard to debug.

At a minimum, I want to verify:

If any users of these package managers happen to see this issue (a massive long shot!), I'd appreciate confirmation that null-ls works as expected. Otherwise, I'll find some time to set them up myself and test it out.

Formating and code action not working as expected (elixir)

FAQ

  • I have checked FAQ and it didn't resolve my problem.

Issues

  • I have checked existing issues and there are no issues with the same problem.

Neovim Version

v0.5.0

Steps to reproduce

  • set lsp-config
  • set null-ls with require("null-ls").builtins.formatting.mix
  • set lightbulb and telescope
  • write some incorrect code
  • display code actions (no action to format)
  • run vim.lsp.buf.formatting()
  • prompt : (1) elixir, (2) null-ls
  • if i select 2 nothing happens
  • if I select 1 formating happens

Expected behavior

Display code actions for formatting and make null-ls formatting works

Actual behavior

  • if i select 2 nothing happens
  • if I select 1 formating happens

Debug log

Cannot see anything relevant

Help

No

Implementation help

No response

[Error] Vim(bufdo):E37: No write since last change (add ! to override)

Thank you for creating a very interesting plugin!
It did not work properly, so I will report it.

  • nvim --version: NVIM v0.5.0-dev+1384-gf2906a466
  • Operating system/version: Manjaro

Describe the bug

When I run vim.lsp.buf.formatting() without set hidden, I get the following error.

Error executing vim.schedule lua callback: ...im/.plugged/plenary.nvim/lua/plenary/async_lib/async.lua:14: The coroutine failed with this message: ...ig/nvim/.plugged/null-ls.nvim/lua/null-ls/formatting.lua:63: Vim(bufdo):E37: No write since last change (add ! to override)

To Reproduce using nvim -u mini.vim -i NONE

set encoding=utf-8

filetype plugin indent on
if has('vim_starting')
  let s:pluin_manager_dir='~/.config/nvim/.plugged/vim-plug'
  execute 'set runtimepath+=' . s:pluin_manager_dir
endif
call plug#begin('~/.config/nvim/.plugged')
Plug 'neovim/nvim-lspconfig'
Plug 'nvim-lua/plenary.nvim'
Plug 'jose-elias-alvarez/null-ls.nvim'
call plug#end()

set nobackup
set nowritebackup
set noswapfile
set updatecount=0
set backspace=indent,eol,start
language messages en_US.utf8

lua << EOF

local servers = require'xlsp.servers'
require'lspconfig'.sumneko_lua.setup{
  cmd = servers.get_cmd('sumneko_lua'),
}

require'null-ls'.setup {
  sources = {
    null_ls.builtins.formatting.stylua,
  }
}

EOF

Steps to reproduce the behavior:

  1. nvim -u minvimrc -i NONE
  2. :e sample.lua
  3. edit
  4. :w (hook BufWritePost)
  5. error

Expected behavior

format is executed and the file is saved without error.


Thank you!

Cscope as a LSP using null-ls.nvim

Issues

  • I have checked existing issues and there are no existing ones with the same request.

Feature description

If I understood correctly, through null-ls.nvim it would be possible to define a new LSP server starting from command line output or writing it in LUA source code.

My question is, there is a tool called cscope which is used to find references, definitions, call hierarchies and so on in C/C++ code.

Would it be theoretically possible to read the cscope database or parse its command line output, defining a new cscope-based LSP with null-ls.nvim? If yes, how could be achieved, and is there someone currently working on it?

Help

No

Implementation help

No response

Is format working with windows 10

FAQ

  • I have checked FAQ and it didn't resolve my problem.

Issues

  • I have checked existing issues and there are no issues with the same problem.

Neovim Version

NVIM v0.5.0 Build type: RelWithDebInfo LuaJIT 2.1.0-beta3

Steps to reproduce

out.mp4

Expected behavior

:w or using <cmd>lua vim.lsp.buf.formatting()<cr> will format the file. I have prettier installed global. Can use prettier -w file.js to manually format. Old neoformat is working ok. The same with stylua and yapf too

Actual behavior

It not formatting

Debug log

:message
message

:LspInfo
lspinfo

Help

No

Implementation help

No response

Adding $FILEEXT var

Issues

  • I have checked existing issues and there are no existing ones with the same request.

Feature description

Adding $FILEEXT var which will be interpolated into file extensions (eg json when filename is foo.json)
This will help with formatters which require type hint like deno fmt --ext

Help

No

Implementation help

No response

rustfmt builtin

I've been switching to null-ls these days, and a rustfmt builtin would be great. I'd just open a pull request but I'm quite busy. Great plugin btw.

[Bug] Cursor position in another window is not restored

  • nvim --version: NVIM v0.5.0-dev+1384-gf2906a466
  • Operating system/version: Manjaro

Describe the bug

When a buffer is displayed in multiple windows and formatting is executed, there is a issue that the cursor position of the buffer in the window other than the current buffer becomes the first position.

To Reproduce

set encoding=utf-8

filetype plugin indent on
if has('vim_starting')
  let s:pluin_manager_dir='~/.config/nvim/.plugged/vim-plug'
  execute 'set runtimepath+=' . s:pluin_manager_dir
endif
call plug#begin('~/.config/nvim/.plugged')
Plug 'neovim/nvim-lspconfig'
Plug 'nvim-lua/plenary.nvim'
Plug 'jose-elias-alvarez/null-ls.nvim'
call plug#end()

set number
set nobackup
set nowritebackup
set noswapfile
set updatecount=0
set backspace=indent,eol,start
language messages en_US.utf8

lua << EOF

local null_ls = require'null-ls'

null_ls.setup {
  on_attach = function(client)
    vim.cmd([[autocmd BufWritePost <buffer> lua vim.lsp.buf.formatting()]])
  end,
  sources = {
    null_ls.builtins.formatting.stylua,
  }
}

EOF

Steps to reproduce the behavior:

sample.lua
function func1(a, b)
  local x = a + b
  local y = [[








































  ]]

  return x
end

function func2(a, b)
  local x = a + b

  return x
end
  1. nvim -u minivimrc -i NONE
  2. :e sample.lua
  3. :normal! G3o (Edit buffer)
  4. :vsplit | normal! Gzz (Split and move the cursor)
  5. :wincmd w
  6. :write (Format)

The cursor position of the window opened with 3 is the first line.
This issue also affects windows in other tabs.

Expected behavior

Cursor positions in all window buffers will be displayed at their original positions.

Screenshots

simplescreenrecorder-2021-06-15_20.23.10.mp4

Thank you!

null-ls attaches to every buffer

First of all, thank you for this amazing plugin!

Right now it seems that null-ls attaches to every buffer including for example Nix buffers.

I would expect it to only attach to the buffers with a filetype from one of the sources.

I run setup with {} and only use it with your ts plugin.

Is this behavior expected?

Formatting and moving buffers will replace them

  • nvim --version: NVIM v0.5.0-dev+1384-gf2906a466
  • Operating system/version: Manjaro

Describe the bug

If I move to another buffer while it is being formatted, there is a problem with the buffer being replaced.

To Reproduce

set encoding=utf-8

filetype plugin indent on
if has('vim_starting')
  let s:pluin_manager_dir='~/.config/nvim/.plugged/vim-plug'
  execute 'set runtimepath+=' . s:pluin_manager_dir
endif
call plug#begin('~/.config/nvim/.plugged')
Plug 'neovim/nvim-lspconfig'
Plug 'nvim-lua/plenary.nvim'
Plug 'jose-elias-alvarez/null-ls.nvim'
call plug#end()

set nobackup
set nowritebackup
set noswapfile
set updatecount=0
set backspace=indent,eol,start
language messages en_US.utf8

lua << EOF

local null_ls = require'null-ls'

null_ls.setup {
  on_attach = function(client)
    vim.cmd([[autocmd BufWritePost <buffer> lua vim.lsp.buf.formatting()]])
  end,
  sources = {
    null_ls.builtins.formatting.stylua,
  }
}

EOF

Steps to reproduce the behavior:

  1. nvim -u minvimrc -i NONE
  2. :e sample.lua
  3. :new | wincmd w (Create a buffer and move on to the previous buffer)
  4. edit lua file
  5. :w | wincmd w (hook BufWritePost)
  6. The buffer created in 5 will be deleted and replaced with the buffer opened in 2.

Expected behavior

I hope the buffer will not be replaced.

Screenshots

null-ls-issues.mp4

Thank you!

Improve capability handling

Neovim currently doesn't have support for dynamic capability registration, though there is an open PR. Supporting it will let the null-ls server start up with no capabilities, then register its actual capabilities based on a user's registered sources.

In the meantime, I want to improve the way null-ls handles requests to avoid cases like this one, where null-ls is listed as a formatting source even though it can't provide formatting for a filetype (diagnostics and code actions are fine, since an empty response doesn't do anything negative). My tentative idea is to override client.supports_method, which I think should let us catch this earlier, but I need to look into this a bit more when I have time.

[Feature request] Add support for golangci-lint

Allow using golangci-lint as either formatter or linter.
This might turn out complicated, as golangci-lint is sometimes slow. This could be alleviated increasing concurrent threads via command line options.
It is also quite extensible, and it would need to be able to source a config file that is project specific.
I can also help, if this feature is deemed desirable.

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.