<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rishav Raj on Medium]]></title>
        <description><![CDATA[Stories by Rishav Raj on Medium]]></description>
        <link>https://medium.com/@rishavinmngo?source=rss-5c0ca5976f08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dcW1QcO7d8LsUFI_5PE-nQ.png</url>
            <title>Stories by Rishav Raj on Medium</title>
            <link>https://medium.com/@rishavinmngo?source=rss-5c0ca5976f08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:05:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishavinmngo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to setup lsp in neovim]]></title>
            <link>https://medium.com/@rishavinmngo/how-to-setup-lsp-in-neovim-1c3e5073bbd1?source=rss-5c0ca5976f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c3e5073bbd1</guid>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[lsp]]></category>
            <category><![CDATA[neovim]]></category>
            <dc:creator><![CDATA[Rishav Raj]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 13:55:09 GMT</pubDate>
            <atom:updated>2024-12-31T02:24:29.295Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial we will learn how to setup lsp for <strong>auto-completion</strong> and understand role of each package.</p><p>We will also setup <strong>auto-formating</strong>.</p><p>Neovim support lsp, meaning it acts as a client for lsp.</p><p>Neovim has inbuilt lsp support. However neovim does’t have any opinion on how to use it. Instead, it leaves this decision up to the users.</p><h3>Understanding what is all of this</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*AdmmGsIBY0vHaZwY.png" /></figure><p>When you open a file in neovim, an lsp client will attach to the buffer.</p><p>The client which gets attached dependents on the filetype and configration in lsp.</p><p>Then, the client will initiate communication with the Language Server, which is installed on your local machine.</p><p>The lsp responds with code completiation, error diagnostics and many more features.</p><h3>Lets start neovim and attach a lsp client to buffer</h3><p>We will try to start a lsp client and attach the client to a buffer.</p><p><strong>init.lua</strong></p><pre>vim.lsp.start_client({<br>  name = &#39;my-server-name&#39;,<br>  cmd = {&#39;lua-language-server&#39;},<br>  root_dir = vim.fs.dirname(vim.fs.find({&#39;pyproject.toml&#39;, &#39;setup.py&#39;}, { upward = true })[1]),<br>})</pre><p>Parameters:</p><ul><li>name is server name given by user, must be unique</li><li>cmd to start the language server on your machine</li><li>root_dir check for pattern</li><li>upward = true is to start searching from upward to downward</li></ul><p>I intentionally included both pyproject.toml and setup.py in this Lua project to demonstrate that the presence of these files alone doesn&#39;t matter. It is just there to help lsp recognize which lsp to start.</p><p>Place <strong>setup.py</strong>(or any type of file which is mentioned in root_dir) beside init.lua, then lsp client will recognize the pattern and attached to the buffer (init.lua in this case).</p><p>Running :lua =vim.lsp.get_active_clients() will give you a lua table.</p><p>If the table is empty the lsp does’t attach and running :lua =vim.lsp.get_active_clients() will gives empty table {}.</p><p>If everything goes well you can see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*phdxcIWvGVMStOKa.png" /></figure><p>The lsp attached and communicating to the language server.</p><p>You can see warnings pop up in init.lua.</p><p>Or you can open any lua file , just place setup.py or pyproject.toml and lsp will get attached to the buffer.</p><p>You can also get code completions just type &lt;C-x&gt;&lt;C-o&gt;, For some reason this does&#39;t work for me so i use &lt;C-o&gt;&lt;C-n&gt;&lt;C-p&gt; (next and prev completions item).</p><p>Type vim. place the cursor after the . and in the insert mode press &lt;C-o&gt;&lt;C-n&gt;&lt;C-p&gt;.</p><p>If everything is alright, you will see a pop-up open.</p><p>Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/0*wtne0BIJTM8GJodg.png" /></figure><p>Doing all of this for each file requires a lot of effort, which is why we have many plugins available to automate these tasks.</p><p>I will provide an introduction to each plugin and its respective role in the LSP setup.</p><p>This will give you a comprehensive understanding of the functions and purpose of each plugin in the LSP setup.</p><h3>neovim/nvim-lspconfig</h3><p>This is a official plugins from neovim which contains configration for servers and many more functions to help you setup lsp client and start a particular language server.</p><p>Delete all of the previous code .</p><p>Install lspconfig, I used lazy.vim here you can use your fav package manager</p><p><strong>init.lua</strong></p><pre>local lazypath = vim.fn.stdpath(&quot;data&quot;) .. &quot;/lazy/lazy.nvim&quot;<br>if not vim.loop.fs_stat(lazypath) then<br>  vim.fn.system({<br>    &quot;git&quot;,<br>    &quot;clone&quot;,<br>    &quot;--filter=blob:none&quot;,<br>    &quot;https://github.com/folke/lazy.nvim.git&quot;,<br>    &quot;--branch=stable&quot;, -- latest stable release<br>    lazypath,<br>  })<br>end<br>vim.opt.rtp:prepend(lazypath)</pre><pre>require(&quot;lazy&quot;).setup({<br>-- All of the packages goes here<br>    &quot;neovim/nvim-lspconfig&quot;<br>}<br>})</pre><p>Now import the lspconfig</p><p><strong>init.lua</strong></p><pre>{...}</pre><pre>-- Setup language servers.<br>local lspconfig = require(&#39;lspconfig&#39;)</pre><p>Now lspconfig directly give the configration of all the available lsps with default settings. see <a href="https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md">configrations available</a> for your programming language.</p><p><strong>init.lua</strong></p><pre>local lspconfig = require(&#39;lspconfig&#39;)</pre><pre>-- Python<br>lspconfig.pyright.setup {}</pre><pre>-- Typescript , Javascript<br>lspconfig.tsserver.setup {}</pre><pre>-- Lua<br>lspconfig.lua_ls.setup {}</pre><p>Now you can supply custom options to the each lsp setup. see <a href="https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md">configrations</a> for your programming language.</p><p><strong>init.lua</strong></p><pre>lspconfig.rust_analyzer.setup {<br>  -- Server-specific settings. See `:help lspconfig-setup`<br>  settings = {<br>    [&#39;rust-analyzer&#39;] = {},<br>  },<br>}</pre><p>Now we want to setup some keymaps when a lsp client attach to buffer.</p><p>Here a autocmd is created</p><pre>-- Use LspAttach autocommand to only map the following keys<br>-- after the language server attaches to the current buffer<br>vim.api.nvim_create_autocmd(&#39;LspAttach&#39;, {<br>  group = vim.api.nvim_create_augroup(&#39;UserLspConfig&#39;, {}),<br>  callback = function(ev)<br>    -- Enable completion triggered by &lt;c-x&gt;&lt;c-o&gt;<br>    vim.bo[ev.buf].omnifunc = &#39;v:lua.vim.lsp.omnifunc&#39;</pre><pre>    -- Buffer local mappings.<br>    -- See `:help vim.lsp.*` for documentation on any of the below functions<br>    local opts = { buffer = ev.buf }<br>    vim.keymap.set(&#39;n&#39;, &#39;gD&#39;, vim.lsp.buf.declaration, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;gd&#39;, vim.lsp.buf.definition, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;K&#39;, vim.lsp.buf.hover, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;gi&#39;, vim.lsp.buf.implementation, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;C-k&gt;&#39;, vim.lsp.buf.signature_help, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;space&gt;wa&#39;, vim.lsp.buf.add_workspace_folder, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;space&gt;wr&#39;, vim.lsp.buf.remove_workspace_folder, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;space&gt;wl&#39;, function()<br>      print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<br>    end, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;space&gt;D&#39;, vim.lsp.buf.type_definition, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;space&gt;rn&#39;, vim.lsp.buf.rename, opts)<br>    vim.keymap.set({ &#39;n&#39;, &#39;v&#39; }, &#39;&lt;space&gt;ca&#39;, vim.lsp.buf.code_action, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;gr&#39;, vim.lsp.buf.references, opts)<br>    vim.keymap.set(&#39;n&#39;, &#39;&lt;space&gt;f&#39;, function()<br>      vim.lsp.buf.format { async = true }<br>    end, opts)<br>  end,<br>})</pre><p>Here some useful keymaps is defined like gd for going to defination.</p><p>Again if we press &lt;C-o&gt;&lt;C-n&gt;&lt;C-p&gt; we will get completion popup like previously.</p><p>We want to automatic triggering of a completion popup, similar to that of IDEs.</p><p>So we have to use another package called <a href="https://github.com/hrsh7th/nvim-cmp">nvim_cmp</a></p><p>Delete the autocmd</p><h3>hrsh7th/nvim-cmp</h3><p>Install nvim_cmp and few <strong>sources</strong>.</p><pre>require(&quot;lazy&quot;).setup({</pre><pre>   &#39;hrsh7th/nvim-cmp&#39;, -- Autocompletion plugin,<br>   &#39;hrsh7th/cmp-nvim-lsp&#39;, -- LSP source for nvim-cmp,<br>   &#39;saadparwaiz1/cmp_luasnip&#39;, -- Snippets source for nvim-cmp<br>   &#39;L3MON4D3/LuaSnip&#39;, -- Snippets plugin</pre><pre>    &quot;neovim/nvim-lspconfig&quot;,<br>}<br>})</pre><p>What is mean by <strong>sources</strong> here</p><ul><li>Nvim_cmp gets the completions from many sources like</li><li>cmp-nvim-lsp gets data from language server</li><li>luasnip gets data from snippets and expand snippets for nvim_cmp</li><li>buffers gets data from buffer in neovim</li></ul><p>Here we extend the capabilities of lsp with capabilities of cmp to leverage features of cmp.</p><p>And created a lua table which contains all the lsp server which i want to setup.</p><pre>local capabilities = require(&quot;cmp_nvim_lsp&quot;).default_capabilities()<br>local luasnip = require &#39;luasnip&#39;</pre><pre>local servers = {<br>    &quot;lua_ls&quot;<br>    &quot;tsserver&quot;<br>}</pre><pre>for _, lsp in ipairs(servers) do<br>  lspconfig[lsp].setup {<br>    -- on_attach = my_custom_on_attach,<br>    capabilities = capabilities,<br>  }<br>end</pre><h3>Setting up Nvim-cmp</h3><p>Import the Nvim-cmp</p><pre>local cmp = require &#39;cmp&#39;</pre><pre>cmp.setup {</pre><pre>}</pre><h4>Snippet</h4><p>Nvim-cmp doesn’t “know” how to expand a snippet, that’s why we need luasnip.</p><p>This callback function gets data from snippet and here cmp need to expand it.</p><p>So we use luasnip to expand the snippet.</p><pre>cmp.setup {<br>    snippet = {<br>        expand = function(args)<br>          luasnip.lsp_expand(args.body)<br>        end,<br>      },<br>}</pre><h4>Sources</h4><p>Nvim-cmp needs sources to show suggestions to us</p><p>Sources include the response from language server , buffer and many more.</p><pre>cmp.setup {<br>    snippet = {<br>        expand = function(args)<br>          luasnip.lsp_expand(args.body)<br>        end,<br>      },<br>      sources = {<br>        { name = &#39;nvim_lsp&#39; },<br>        {name = &quot;buffer&quot;},<br>      },<br>}</pre><h4>Define keymaps for Nvim-cmp</h4><pre>cmp.setup {<br>    snippet = {<br>        expand = function(args)<br>          luasnip.lsp_expand(args.body)<br>        end,<br>      },<br>      sources = {<br>        { name = &#39;nvim_lsp&#39; },<br>        {name = &quot;buffer&quot;},<br>      },</pre><pre>      mapping = cmp.mapping.preset.insert({<br>        [&#39;&lt;C-u&gt;&#39;] = cmp.mapping.scroll_docs(-4), -- Up<br>        [&#39;&lt;C-d&gt;&#39;] = cmp.mapping.scroll_docs(4), -- Down<br>        [&#39;&lt;C-j&gt;&#39;] = cmp.mapping.select_next_item(),<br>        [&#39;&lt;C-k&gt;&#39;] = cmp.mapping.select_prev_item(),<br>        [&#39;&lt;C-Space&gt;&#39;] = cmp.mapping.complete(),<br>        [&#39;&lt;CR&gt;&#39;] = cmp.mapping.confirm {<br>          behavior = cmp.ConfirmBehavior.Replace,<br>          select = true,<br>        },<br>      }),<br>}</pre><p>Finally we got auto-completion while we typing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*aBSjfT-Y2C1lXTFg.png" /></figure><p>You can see donald which is not a keyword just present in buffer which then suggestion by cmp.</p><h3>Format on save</h3><p>Now we have auto-completion. We should setup a way to format our code.</p><p>One way to format a buffer using lsp is to call vim.lsp.buf.format()</p><p>Calling like this :lua vim.lsp.buf.format() should format the buffer.</p><p>For this we have to define a autocmd which will run vim.lsp.buf.format() before buffer is saved.</p><p><strong>async</strong> options tells how to format, if <strong>true</strong> the format is <strong>non-blocking</strong>(when vim is ideal then the formatting of buffer will happen).</p><p>I make async = false because i want to format the buffer before the buffer is saved no matter what.</p><pre>vim.api.nvim_create_autocmd(&#39;BufWritePre&#39;, {<br>      callback = function()<br>        vim.lsp.buf.format {<br>          async = false,<br>        }<br>      end,<br>    })</pre><p>This will run when any buffer is save, which we don’t want because if lsp_client is not attached to the buffer then it will throw error.</p><p>So we have to define the above autocommand only when a lsp is attached to buffer.</p><p>We have to create another autocommand which will run only when a lsp attached.</p><pre>vim.api.nvim_create_autocmd(&#39;LspAttach&#39;, {<br>  group = vim.api.nvim_create_augroup(&#39;lsp-attach-format&#39;, { clear = true }),<br>  -- This is where we attach the autoformatting for reasonable clients<br>  callback = function(args)<br>    local client_id = args.data.client_id<br>    local client = vim.lsp.get_client_by_id(client_id)<br>    local bufnr = args.buf</pre><pre>    if not client.server_capabilities.documentFormattingProvider then<br>      return<br>    end<br></pre><pre>    vim.api.nvim_create_autocmd(&#39;BufWritePre&#39;, {<br>      group = get_augroup(client),<br>      buffer = bufnr,<br>      callback = function()<br>        if not format_is_enabled then<br>          return<br>        end<br>        vim.lsp.buf.format {<br>          async = false,<br>          filter = function(c)<br>            return c.id == client.id<br>          end,<br>        }<br>      end,<br>    })<br>  end,<br>})</pre><p>Filter in lsp.buf.format receives client and must return boolean. false will stop from request to format the buffer.</p><p>For Example:</p><p>This will not format buffers which have tsserver attached.</p><pre>-- Never request typescript-language-server for formatting<br>vim.lsp.buf.format {<br>  filter = function(client) return client.name ~= &quot;tsserver&quot; end<br>}</pre><p>That’s it.</p><p><a href="https://github.com/rishavmngo/dot-files">My dot files</a></p><p>References:</p><ul><li><a href="https://github.com/nvim-lua/kickstart.nvim">nvim-lua/kickstart.nvim</a></li><li><a href="https://neovim.io/doc/user/lsp.html">Neovim docs for lsp</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3e5073bbd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>