Code Monkey home page Code Monkey logo

lsp-format.nvim's Introduction

LSP-format.nvim

LSP-format.nvim is a wrapper around Neovims native LSP formatting.

It does

  1. Asynchronous or synchronous formatting on save
  2. Sequential formatting with all attached LSP server
  3. Add commands for disabling formatting (globally or per filetype)
  4. Make it easier to send format options to the LSP
  5. Allow you to exclude specific LSP servers from formatting.

It does not

  1. Provide any formatting by itself. You still need to use an LSP server

Requirements

LSP-format requires Neovim 0.7 or newer.

Install

Use your favourite plugin manager to install.

Example with Packer

wbthomason/packer.nvim

-- init.lua
require("packer").startup(function()
    use "lukas-reineke/lsp-format.nvim"
end)

Example with Plug

junegunn/vim-plug

" init.vim
call plug#begin('~/.vim/plugged')
Plug 'lukas-reineke/lsp-format.nvim'
call plug#end()

Setup

To use LSP-format, you have to run the setup function, and pass the on_attach function to each LSP that should use it.

require("lsp-format").setup {}
require("lspconfig").gopls.setup { on_attach = require("lsp-format").on_attach }

or

require("lsp-format").setup {}

local on_attach = function(client, bufnr)
    require("lsp-format").on_attach(client, bufnr)

    -- ... custom code ...
end
require("lspconfig").gopls.setup { on_attach = on_attach }

That's it, saving a buffer will format it now.

Special format options

There are a couple special format options that LSP-format uses.

exclude format option

exclude is a table of LSP servers that should not format the buffer.

Alternatively, you can also just not call on_attach for the clients you don't want to use for formatting.

order format option

order is a table that determines the order formatting is requested from the LSP server.

sync format option

sync turns on synchronous formatting. The editor will block until the formatting is done.

force format option

force will write the format result to the buffer, even if the buffer changed after the format request started.

Notes

Make sure you remove any old format on save code

You don't want to run formatting twice. If you had setup formatting on save before, remove it.
You can check if something is listening on buffer write events with :autocmd BufWritePre and :autocmd BufWritePost

:wq will not format when not using sync

Because default formatting is async, you can't save and quit in the same command. The formatting results will not get back in time and Neovim will close without applying the changes.
In this case you need to use the sync format option.

Add this abbreviation into your dotfiles to do the right thing when doing :wq

vim.cmd [[cabbrev wq execute "Format sync" <bar> wq]]

FAQ

How is it different to autocmd BufWritePre <buffer> lua vim.lsp.buf.format()?

The main difference is that LSP-format.nvim is async by default. It will format on save, without blocking the editor.
When the formatting is done, LSP-format.nvim will only change the buffer if it didn't change since the time formatting was called.
And it adds some convenience with disable commands and format options.
But the end result is the same.

How do I use format options?

You can pass the format options into the setup function, or as arguments to the :Format command.
How the format options look like depends on the LSP server you are using.

The format options can either be string, number, boolean, or a function that resolves to those.

As an example, mattn/efm-langserver uses ${} template syntax with which you can define your own options ${--flag:lua_variable_name}.

require("lsp-format").setup {
    typescript = {
        tab_width = function()
            return vim.opt.shiftwidth:get()
        end,
    },
    yaml = { tab_width = 2 },
}
local prettier = {
    formatCommand = [[prettier --stdin-filepath ${INPUT} ${--tab-width:tab_width}]],
    formatStdin = true,
}
require("lspconfig").efm.setup {
    on_attach = require("lsp-format").on_attach,
    init_options = { documentFormatting = true },
    settings = {
        languages = {
            typescript = { prettier },
            yaml = { prettier },
        },
    },
}

Now Typescript gets formatted with what shiftwidth is set to, and YAML with 2 spaces by default.
And you can run :Format tab_width=8 to overwrite the setting and format with 8 spaces.

lsp-format.nvim's People

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

lsp-format.nvim's Issues

Is there a way to format without losing the jump history?

Hi Lukas.

Thanks for the plugin. I've been using it, favoring it over the LSP provided formatting. One thing I noticed that is common for both this and the LSP provided formatting is that the jump history is cleared when the file is formatted.

Is there a way to avoid that?

Setting up without messing up previous settings?

I use rust-tools to dogfeed all the lsp related setup to lspconfig, and I don't need to manually add the following line
lspconfig["rust_analyzer"].setup {}
while setting up rust server.
However, if I want to use lsp-format, then I have to have the following line in my config:
lspconfig["rust_analyzer"].setup { on_attach = require "lsp-format".on_attach }
While adding the above line makes formatting on save work, it messes up with the prior setup done by rust-tools. How can I use the functionality of both rust_tools and lsp-format simultaneously?

extra key press after save

Hi, thanks again for the plug-in. After the latest update, I noticed have to press Enter after saving (and auto formatting).
Is there a way to go back to the previous behavior where auto formatting doesn't ask me for an extra key press?
Screen Shot 2020-11-16 at 11 12 04 PM

These are the settings I used to invoke formatting

" auto format and save
augroup Format
    autocmd!
    autocmd BufWritePost * FormatWrite
augroup END

Enable/disable per buffer

AFAICT, formatting can only be toggled globally. It would be great if I could disable it for only a specific file (e.g. FormatBufDisable).

Infinite loop of formatting

After some update when I have autosave enabled and do :w it infinitely loops, once it gets indented in the one way, eslint shows an error, then it gets indented in the other way, and it is an infinite loop until I exit neovim, this happens when opening neovim, opening some (1 or more) random file with formatting support, doing :w and that's it, this might be something with my configuration or with the plugin, I would greatly appreciate if you can point me into the right direction

[Bug] Formatting occasionally changes other buffers

Occasionally (unfortunately I haven't yet determined the pattern, but it might be related to when a buffer has been formatted and is still in a modified state), the formatting in a specific buffer seems not to run, but actually another open buffer is instead changed and lines from my current buffer are inserted into the other open buffer.

I appreciate this isn't a lot to go off of and tbh I've held off reporting till I noticed a pattern, but I'm stumped and don't really know why this occurs. My lsp format is pretty minimal, I've been using it as default with just the attach method in my general lsp on_attach and noticed this issue still.

I'm happy to try various things if anything comes to mind, I didn't/don't think I'm doing anything particularly unusual and I am wondering if there is a bug in nvim core that because formatting is done asynchronously in this plugin it's being exacerbated

temporary file directory

Is it possible to specify a directory for the temporary file? Currently it saves it on the same directory of the file that gets formatted then delete it. This causes issue with an SPA framework that uses filesystem routing (Sapper in my case) and watching for file change. So when the temporary files created, it throws an error because it's not a valid file extension for Sapper and it refresh the page several times (when the tmp files got created and deleted).

I'd like to be able to set the directory for the tmp files, e.g ~/.config/nvim/tmp/ so it doesn't cause this issue. Maybe let user specify it in the setup? Thanks!

Format from stdout

I use clang-format and lua-format. Both programs print formatted text to stdout. Is it possible to support this behavior?

messes up files when writing into multiple files at once with multiple formating lsp providers

how to reproduce:

  • install sumneko lua-language-server
  • install stylua
  • install null-ls and enable stylua formatter
  • open about 50 lua files with, e.g. vim lua/**/*.lua
  • run bufdo w

vim will start writing into all those files and lsp-format will endup with file contents mixed between the files. e.g.
file foo will have content of file bar, which, in turn will have content of file baz etc.

`Format sync` is returning async

After a lot of trail and error I determined that the suggested command is returning async
vim.cmd [[cabbrev wq execute "Format sync" <bar> wq]]

When this command is used it causes issues in a couple places

  1. When you search for wq find it breaks because it auto expands
  2. When you use wq on the last buffer nvim quits before the returned command

To determine the async problem I built a quick and dirty mills time r

function epoch_ms()
	local s, ns = vim.loop.gettimeofday()
	return s * 1000 + math.floor(ns / 1000)
end

Then ran a bunch of commands to understand what happened

:execute "lua print(epoch_ms())" | Format sync | execute "lua print(epoch_ms())"
1712103251379
1712103251383
:execute "lua print(epoch_ms())" | Format | execute "lua print(epoch_ms())"
1712103301293
1712103301295
:execute "lua print(epoch_ms())" | execute "lua print(vim.lsp.buf.format())" | execute "lua print(epoch_ms())"
1712103328159
1712103328221

Currently I have defined the following which does work but it feels very much like I am bypassing lsp-format and just using the built-ins.

vim.api.nvim_create_autocmd("BufWritePre", {
callback = function()
	require("lsp-format").format({ sync = true })
	-- vim.lsp.buf.format(). -- bypasses lsp-format
end
})

Any help would be wonderful as I do like using ZZ and wq to format before exit

clang-format not working

i have these:

require "format".setup {
	cpp = {{
			-- cmd = {"clang-format --style='{BasedOnStyle: chromium, IndentWidth: 4}'"}
			cmd = {"clang-format"}
	}},
	c = {{
			cmd = {"clang-format --style='{BasedOnStyle: chromium, IndentWidth: 4}'"}
	}},
}

calling clang-format like this in terminal works like a charm.

but calling from plugin with this config doesnt work.

help.

i've tested for python with black works like a charm and its really fast.

but it doesnt work for cpp/c ... :(

Example config leads to lua error

Just setting up with the base example from the help file leads to lua error

Example init.vim

lua require "format".setup {
    lua = {
        {cmd = {"luafmt -w replace"}}
    }
}

Error

Error detected while processing /home/creztoe/.config/nvim/init.vim:
line  164:
E5104: Error while creating lua chunk: [string "<VimL compiled string>"]:1: unexpected symbol near '<eof>'
line  165:
E5104: Error while creating lua chunk: [string "<VimL compiled string>"]:1: unexpected symbol near '='
line  166:
E492: Not an editor command:         {cmd = {"luafmt -w replace"}}
line  167:
E492: Not an editor command:     }
line  168:
E492: Not an editor command: }

Treesitter integration

Instead of manually specifying start_pattern and end_pattern, have you thought about using Treesitter to detect embedded languages? That's already an inherent feature of Treesitter (and is used for highlighting said embedded languages). I know nvim-treesitter is still in it's early stages, but it's rock solid for most common languages.

This vs formatter.nvim

Hey, just curious what your view is on plans to develop this vs steering people to formatter.nvim?
The readme states that this started out as a PR to formatter.nvim, but I also see that you have commits in formatter.nvim that are newer than the most recent commits here.

Thanks!

how to format code with prettier, stylua

I want to ask how to use prettier to format code, I see that efm lsp is used in the documentation, but I don't use this, I just installed simple tsserver, vuels, cssls lsp, I don't see the specific usage in the documentation , can you provide a demo?

lsp info:
WechatIMG2092

tsserver setup:
WechatIMG2094

on_attach:
WechatIMG2102

this is my code, but it's not work, am i missing something? and if I also want to format the lua file using stylua, What should we do?

functions in cmd table are not running

This is the config I'm testing & I have g:format_debug=v:true

This works fine

require "format".setup {
  typescript = {
    {cmd = {"prettier -w"}}
  }
}

This doesn't run

require "format".setup {
  typescript = {
    cmd = {
      function(file)
        return string.format("prettier --print-width %s -w %s", vim.bo.textwidth, file)
      end
    }
  }
}

[Question] Unable to format python with black formatter

Summary

I'm unable to format python files with black formatter using efm language server.

Configuration

lsp-config.lua

local lsp_format_status_ok, lsp_format = pcall(require, "lsp-format")
if not lsp_format_status_ok then
    return
end

lsp_format.setup()
local capabilities = cmp_nvim_lsp.update_capabilities(vim.lsp.protocol.make_client_capabilities())

lspconfig.efm.setup {
    on_attach = on_attach,
    init_options = { documentFormatting = true },
    capabilities = capabilities,
    filetypes = { "python" },
    settings = {
        languages = {
            python = {
                formatCommand = "black --quiet -",
                formatStdin = true,
            }
        }
    }
}
$ which black
/home/rahul/.pyenv/shims/black
$ which efm-langserver
/home/rahul/go/bin/efm-langserver

language servers connected to python:

 Client: pyright (id: 1, pid: 26009, bufnr: [1])
 	filetypes:       python
 	autostart:       true
 	root directory:  Running in single file mode.
 	cmd:             pyright-langserver --stdio
 
 Client: efm (id: 2, pid: 26010, bufnr: [1])
 	filetypes:       python
 	autostart:       true
 	root directory:  Running in single file mode.
 	cmd:             efm-langserver
 

My suspicion is that somehow pyright takes priority and since it does not have formatting capabilities that could be a problem? Any advice would be helpful, thanks!

Buffers content duplicated on wq

With null-ls (stylua enabled only) and lsp-format attached to buffer through on_attach() with sumneko's lua LSP buffer's content will get duplicated on :wq.
Seems like it's only happening when there are changes made to buffer. I think previously there was no formatting on :wq at all? If buffer has no changes made to it since opening of neovim content of file is not changed, but as soon as buffer is changed :wq results in duplication.

Custom format commands no longer working.

Hello.

Ok, so what I used to do was disable formatting in nvim-lsp and use this plugin to take care of that.
So instead now I use the on_attach config in the lsp as indicated in the doc, but this no longer seems to work (notably php-cs-fixer is not running, didn't really check on the rest but I suspect the above config no longer does anything).
So my question is how do I get this working again.

This is my configuration:
```lua
require("lsp-format").setup {
  javascript = {
    {cmd = {"prettier -w", "./node_modules/.bin/eslint --fix"}}
  },
  typescript = {
    {cmd = {"prettier --parser typescript -w"}}
  },
  vue = {
    {cmd = {"prettier --parser vue -w"}}
  },
  scss = {
    {cmd = {"prettier --parser scss -w"}}
  },
  css = {
    {cmd = {"prettier --parser css -w"}}
  },
  yaml = {
    {cmd = {"prettier --parser yaml -w"}}
  },
  html = {
    {cmd = {"prettier --parser html -w"}}
  },
  haskell = {
    {cmd = {"hindent"}}
  },
  python = {
    {cmd = {"autopep8 --ignore E501"}}
  },
  php = {
    {cmd = {"php-cs-fixer fix"}}
  },
  go = {
    {cmd = {"goimports -w"}}
  },
  rust = {
    {cmd = {"rustfmt"}}
  }
}

local onAttach = (function(client)
  -- add custom formatting
  require('lsp-format').on_attach(client)

  -- add nvim-cmp (autocomplete) to lsp capabilities
  client.capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities())
  -- show doc with 'K'
  vim.api.nvim_set_keymap('n', 'K', ':lua vim.lsp.buf.hover()<CR>', {noremap = true, silent = true})
  -- jump to definition
  vim.api.nvim_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', {noremap = true, silent = true})
  vim.api.nvim_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", {noremap = true, silent = true})
  vim.api.nvim_set_keymap("n", "tt", "<cmd>lua vim.diagnostic.open_float()<CR>", {noremap = true, silent = true})
end)
etc...

PS: Sorry if there's just something I missed in the docs but it seems unclear to me.

Format-on-save doesn't work, but calling `:lua vim.lsp.buf.format()` does

Hello! ๐Ÿ‘‹

This is probably a silly question, but I just can't seem to format-on-save. I'm using Neovim 0.8.2 on Ubuntu 22.04 (WSL). I couldn't find a similar issue, so I'm submitting this one.

My config looks something like this:

require("lsp-format").setup {}

--  This function gets run when an LSP connects to a particular buffer.
local on_attach = function(client, bufnr)
  -- ...keymaps...

  -- Enable format-on-save
  require("lsp-format").on_attach(client)
end

local servers = {
  pyright = {},
  tsserver = {},
}

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

-- Setup mason so it can manage external tooling
require('mason').setup()

-- Ensure the servers above are installed
local mason_lspconfig = require 'mason-lspconfig'

mason_lspconfig.setup {
  ensure_installed = vim.tbl_keys(servers),
}

mason_lspconfig.setup_handlers {
  function(server_name)
    require('lspconfig')[server_name].setup {
      capabilities = capabilities,
      on_attach = on_attach,
      settings = servers[server_name],
    }
  end,
}

I'm using null-ls to provide the formatting to the LSP, and apparently it works, since I can manually format using vim.lsp.buf.format().

I checked :autocmd BufWritePre and :autocmd BufWritePost. The first is empty, the second has some autocmds, but none related to formatting.

Is there anything else I'm missing here?

Thank you for your help, and for the plugin ๐Ÿ™

If two files are edited and saved at the same time (:wa), the contents of one file will be overwritten by the contents of the other

If two files are edited and saved at the same time (:wa), the contents of one file will be overwritten by the contents of the other

2023-05-20.8.46.48.mov

Here is my config for lsp-format

local spec = {
  "lukas-reineke/lsp-format.nvim",
  opts = { sync = true },
  enabled = true,
  init = function()
    local on_attach = require("core.plugin").on_attach
    on_attach(function(client, _)
      local enableFormat = client.server_capabilities.documentFormattingProvider
      if enableFormat then
        require("lsp-format").on_attach(client)
        -- vim.cmd([[
        --       cabbrev wq execute "Format sync" <bar> wq
        --       cabbrev wqa bufdo execute "Format sync" <bar> wa <bar> q
        --     ]])
      end
    end)
  end,
}
return spec

Completely stopped working on latest master (v2.3.2)

Hi,

I'm not even sure how to debug this properly or where to start.

I pulled the latest version and now I can't format anymore, on any LSP.

Symptoms:

  • Running :Format does nothing.
  • Running :lua vim.lsp.buf.formatting() works.
  • Running :lua vim.lsp.buf.formatting_sync_seq() works.
  • Saving a file does not autoformat it.
  • No messages or errors show up when starting, or when running any of the commands.

Here's my config:

-- packer
  use "lukas-reineke/lsp-format.nvim"
local lspformat = require("lsp-format")

-- โ€ฆ

  lspformat.setup()
  -- lspformat.setup {
  --   typescript = {
  --     exclude = { "tsserver" },
  --   },
  --   lua = {
  --     exclude = { "sumneko_lua" },
  --   },
  --   ruby = {
  --     -- Use standardrb via null-ls instead.
  --     exclude = { "solargraph" },
  --   },
  -- }
  -- lspformat.disable { args = "markdown" }
  -- lspformat.disable { args = "vimwiki" }
  -- lspformat.disable { args = "eruby" } -- completely breaks in most formatters

-- LSP servers configured like this:
-- { on_attach = on_attach }

local function on_attach(...)
  lspformat.on_attach(...)
  on_attach_without_formatting(...)
end

I use null-ls for most formatting stuff.

Running nvim nightly NVIM v0.8.0-dev+27-g5c4ec25478

No way to tell if auto-formatting is enabled

As far as I can tell, there's no exposed API for determining if the current buffer will autosave.

It would be useful for me to have a modeline indicator so I can know before saving. Happy to submit a PR if it's easier for you, I figured you'd probably know the most sensible way to expose this though.

Thanks for a great package!

Support for lsp.buf.formatting_seq_sync() behavior?

Hey there, great plugin!

I was wondering if there was a way, or if a way may be planned in the future, to support formatting on save when using multiple formatting-enabled LSPs.

For example, I'm currently using the eslint LSP server in conjunction with null-ls for prettier formatting. Right now my format-on-save is calling vim.lsp.buf.formatting_seq_sync() to ensure that both servers have a chance to format according to their configs.

Would there be a way to do that with this plugin? Or is it built with only one attached LSP server at a time in mind?

"Either add eslint to your null-ls config or add an eslint plugin to run prettier and stop running 2 servers at once, you dummy" is also a valid response. ๐Ÿ˜›

Thanks!

Breaking changes in version 2

I have not maintained the old version of format.nvim for some time.
Now I decided to repurpose this repository for a modern way to format with LSP instead.

If you don't want to use LSP to format, you can either use mhartington/formatter.nvim, or pin the version of this repo to tag v1.
That is the old version, and it should still continue to work, but I won't be fixing any bugs going forward.

Plugin does nothing

Saving does nothing. :Format does nothing.

:lua vim.lsp.buf.format({ async = true}) formats stuff like it's supposed to.

I'm using lazy.nvim in NvChad with this setup just like the readme says...

{
    "lukas-reineke/lsp-format.nvim",
    lazy = false,

    config = function()
        -- lsp format on save
        require("lsp-format").setup {}
        require("lspconfig").gopls.setup { on_attach = require("lsp-format").on_attach }
    end
},

I don't know what else to say. It no workie.

tempfile fails to open

Same here. I got the error message: Format error: ...o/.config/nvim/plugged/format.nvim/lua/format/format.lua:35: attempt to index local 'tempfile' (a nil value)

Originally posted by @pulcinello in #3 (comment)

Enabling eslint

Thank you very much for creating this plugin :)

I was configuring it today and I ran into some problems enabling eslint (and disabling tsserver) for formatting, but finally found a solution and wanted to share it as other people might run into the same problem.
I had to add

  if client.name == 'tsserver' then
    -- Disable formatting for typescript 
    client.server_capabilities.documentFormattingProvider = false -- for lsp-format
  elseif client.name == 'eslint' then
    -- Enable formatting for eslint
    client.server_capabilities.documentFormattingProvider = true -- for lsp-format
  end

in my on_attach function, then eslint was enabled, tsserver had to be disabled because otherwise eslint ran first and it corrected its issues then tsserver formatted the file while ignoring my eslint rules.
Such problems were documented already but this plugin required a bit of a different solution as the solution normally was to set document_formatting instead of documentFormattingProvider.

This seems a bit hacky, so if there is a better solution please tell me!

[Feature Request] configure like neoformat

Hi there, great plugin! Ive been using neoformat for a while now and it works well ootb . I just have to install neoformat and :Neoformat for formatting stuff. It needs no config , it'd be nice if format.nvim implements something similar too so for example , just installing format.nvim and external dependencies could be very nicee and no user config unless the user wants to add his own stuff.

check : https://github.com/sbdchd/neoformat/tree/master/autoload/neoformat/formatters

example : https://github.com/sbdchd/neoformat/blob/master/autoload/neoformat/formatters/c.vim

Can you add autocommand event?

I want to popup a notification that the file was formatted using client_name, can you either fire a custom autocommand event? or provide an option for a callback using the setup function for after the file is formatted?
Thanks

Does lsp-format supports `shfmt` & `stylua` ?

Hello there, everyone!

This is a fantastic plug-in, btw. Thanks for writing that.

I was just wondering how one would wire in formatters like shfmt and stylua.

I use Mason to install those and these are the only ones missing from my setup at this moment.

`vim.lsp.buf.format()` formats, but `:Format` does not

I am currently developing several features for trpc, but the problem here is, that the formatting is not working for me properly. My dotfiles are at iduuck/dots.

Saw #70, but didn't help me, since the formatter is working on other projects properly (also not using null-ls here).

I will try to get a minimal repro done, but I am not sure, when...


:LspLog is the following:

[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[eslint]"	"client.request"	2	"textDocument/codeAction"	{  context = {    diagnostics = {}  },  range = {    ["end"] = <1>{      character = 0,      line = 20    },    start = <table 1>  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 61,  jsonrpc = "2.0",  method = "textDocument/codeAction",  params = {    context = {      diagnostics = {}    },    range = {      ["end"] = <1>{        character = 0,        line = 20      },      start = <table 1>    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[tsserver]"	"client.request"	4	"textDocument/codeAction"	{  context = {    diagnostics = {}  },  range = {    ["end"] = <1>{      character = 0,      line = 20    },    start = <table 1>  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 44,  jsonrpc = "2.0",  method = "textDocument/codeAction",  params = {    context = {      diagnostics = {}    },    range = {      ["end"] = <1>{        character = 0,        line = 20      },      start = <table 1>    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[tailwindcss]"	"client.request"	5	"textDocument/codeAction"	{  context = {    diagnostics = {}  },  range = {    ["end"] = <1>{      character = 0,      line = 20    },    start = <table 1>  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 43,  jsonrpc = "2.0",  method = "textDocument/codeAction",  params = {    context = {      diagnostics = {}    },    range = {      ["end"] = <1>{        character = 0,        line = 20      },      start = <table 1>    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 61,  jsonrpc = "2.0",  result = {}}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 43,  jsonrpc = "2.0"}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 44,  jsonrpc = "2.0",  result = {}}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  jsonrpc = "2.0",  method = "textDocument/didSave",  params = {    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  jsonrpc = "2.0",  method = "textDocument/didSave",  params = {    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  jsonrpc = "2.0",  method = "textDocument/didSave",  params = {    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[eslint]"	"client.request"	2	"textDocument/formatting"	{  options = {    insertSpaces = true,    tabSize = 2  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 62,  jsonrpc = "2.0",  method = "textDocument/formatting",  params = {    options = {      insertSpaces = true,      tabSize = 2    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 62,  jsonrpc = "2.0",  result = {}}
[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[eslint]"	"client.request"	2	"textDocument/codeAction"	{  context = {    diagnostics = {}  },  range = {    ["end"] = <1>{      character = 0,      line = 20    },    start = <table 1>  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 63,  jsonrpc = "2.0",  method = "textDocument/codeAction",  params = {    context = {      diagnostics = {}    },    range = {      ["end"] = <1>{        character = 0,        line = 20      },      start = <table 1>    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[tsserver]"	"client.request"	4	"textDocument/codeAction"	{  context = {    diagnostics = {}  },  range = {    ["end"] = <1>{      character = 0,      line = 20    },    start = <table 1>  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 45,  jsonrpc = "2.0",  method = "textDocument/codeAction",  params = {    context = {      diagnostics = {}    },    range = {      ["end"] = <1>{        character = 0,        line = 20      },      start = <table 1>    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../lua/vim/lsp.lua:1381	"LSP[tailwindcss]"	"client.request"	5	"textDocument/codeAction"	{  context = {    diagnostics = {}  },  range = {    ["end"] = <1>{      character = 0,      line = 20    },    start = <table 1>  },  textDocument = {    uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"  }}	<function 1>	17
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:285	"rpc.send"	{  id = 44,  jsonrpc = "2.0",  method = "textDocument/codeAction",  params = {    context = {      diagnostics = {}    },    range = {      ["end"] = <1>{        character = 0,        line = 20      },      start = <table 1>    },    textDocument = {      uri = "file:///Users/nick/dev/trpc/packages/client/src/createTRPCClient.ts"    }  }}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 63,  jsonrpc = "2.0",  result = {}}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 44,  jsonrpc = "2.0"}
[DEBUG][2023-03-21 11:55:03] .../vim/lsp/rpc.lua:388	"rpc.receive"	{  id = 45,  jsonrpc = "2.0",  result = {}}

:Format differs from clang-format

I have the following example code file named source.cc.

#include "source.h"

#include "other_files.h"
#include "another_file.h"

#include <libb.h>
#include <liba.h>

void fun() {}

If I open it in neovim and call :Format, then the result looks like this: (note that "source.h" not not at the top anymore)

#include "another_file.h"
#include "other_files.h"
#include "source.h"

#include <liba.h>
#include <libb.h>

void fun()
{}

But if I run clang-format source.cc in the terminal, I get this, result, which is what I would expect:

#include "source.h"

#include "another_file.h"
#include "other_files.h"

#include <liba.h>
#include <libb.h>

void fun()
{}

The .clang-format file looks like this:

---
Language:        Cpp
# BasedOnStyle:  WebKit
AccessModifierOffset: -4
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Left
AlignOperands:   true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
  AfterClass:      true
  AfterControlStatement: false
  AfterEnum:       true
  AfterFunction:   true
  AfterNamespace:  true
  AfterObjCDeclaration: false
  AfterStruct:     true
  AfterUnion:      true
  AfterExternBlock: true
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false
  SplitEmptyFunction: false
  SplitEmptyRecord: false
  SplitEmptyNamespace: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: true
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
BreakConstructorInitializers: BeforeComma
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit:     80
CommentPragmas:  '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat:   false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:   
  - foreach
  - Q_FOREACH
  - BOOST_FOREACH
IncludeBlocks:   Regroup
IncludeCategories: 
  - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
    Priority:        2
  - Regex:           '^(<|"(gtest|gmock|isl|json)/)'
    Priority:        3
  - Regex:           '.*'
    Priority:        1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth:     4
IndentWrappedFunctionNames: true
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
ReflowComments:  true
SortIncludes:    true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles:  false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard:        Cpp11
TabWidth:        4
UseTab:          ForContinuationAndIndentation
...

The lua setup looks like this:

local formatter = require('formatter')
formatter.setup({
	logging = true,
	filetype = {
		cpp = {
			function()
				return {
					exe = "clang-format",
					args = {},
					stdin = true,
					cwd = vim.fn.expand("%:p:h")
					}
			end
			}
		}
	})

I've compared the clang-format calls with strace and it looked the same to me in the sense that the .clang-format file is found. Is it possible that :Formatitself removes some empty lines before it passes the buffer contents to clang-format?

[Feature Request] Dont add the format to undo

Hey, I use autosave and it works great with this plugin, but the format adds to the undo history, when I want to undo a change I need to do it twice, once for the format and once for the actual change

Will format.nvim auto change filename?

I am using format.nvim and latexindent to beautify my tex code, but it is strange that there are many bak file created.

Latexindent log displayed that maybe format.nvim change filename when saving code like this :

image

Don't format if file path matches glob

Hello,

Is it possible to make it so that it doesn't format certain files. For example anything that matches "/site-packages/" so that I don't end up running the formatter when I've gone into a file inside my python virtualenv?

Thanks

python not formatting

I can't this plugin to work with the following settings. Did I goof the setup?

lua <<EOF
require 'format'.setup{
    python = {
        {cmd = {"black", "isort"}}
   }
}
require'colorizer'.setup()
local nvim_lsp = require("nvim_lsp")
local nvim_completion = require("completion")
local nvim_diagnostic = require("diagnostic")

local custom_attach = function()
nvim_completion.on_attach()
nvim_diagnostic.on_attach()
print("LSP Attached.")
end


nvim_lsp.jedi_language_server.setup{ on_attach = custom_attach }
nvim_lsp.jsonls.setup{ on_attach = custom_attach }
nvim_lsp.vimls.setup{ on_attach = custom_attach }
    

EOF

Format on auto save

Thanks for your work on this plugin,
I was wondering if it is possible to format on auto save, I have this autocmd and your plugin does not format after this.

vim.api.nvim_create_autocmd("BufLeave", {
	group = vim.api.nvim_create_augroup("AutoSave", { clear = true }),
	callback = function(event)
		vim.api.nvim_command("update")
	end,
})

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.