I am rewriting my ancient vim config into Lua with nvim. I am using Mason to grab lsp language servers and for the most part it works great!

I have this in my remaps so I can <leader>f to format the current file (still need to figure out formatting on save too, but I can’t for the life of me get Markdown formatting working.

vim.keymap.set("n", "<leader>f", function()
	vim.lsp.buf.format()
end)

I have markdownlint, marksman, prettier, and prettierd all installed wth Mason (though I haven’t written any keymaps or configs for them). Any idea how I can format my Markdown? I write in it all day every day so it’s gonna help a ton if I can get it working. Secondly any ideas how I can do the same mapping for the formatting on save? Still pretty new to Lua.

  • muntoo@lemmy.world
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    1 year ago

    For autoformatting, try an autocmd:

    autocmd BufWritePre * lua vim.lsp.buf.format()
    

    Or alternatively, I use:

    autocmd BufWritePre * lua require("utils").format()
    
    -- Formats the current buffer
    function utils.format()
      local whitelist = { "python", "rust" }
      if vim.tbl_contains(whitelist, vim.bo.filetype) then
        vim.lsp.buf.format()
      end
    end