Execute typescript organize imports automatically

I’m trying to set up my neovim typescript config to organize imports automatically, but it’s not working. I’m using the command provided in this post to organize imports. When I use it directly on my neovim it works, but when I try to set it up in an autocmd it doesn’t.
Here is my config:

local lspconfig = require("lspconfig")
local capabilities = require("cmp_nvim_lsp").default_capabilities()
lspconfig.ts_ls.setup({
  capabilities = capabilities,
  on_attach = function(client, bufnr)
    require("lualine")
    vim.api.nvim_create_autocmd({ "BufWritePre" }, {
      callback = ':lua vim.lsp.buf.execute_command({command = "_typescript.organizeImports", arguments = {vim.fn.expand("%:p")}})',
    })
  end,
})

I’m quite new to lua and neovim, so I don’t know much about what I’m doing hahaha

This is working for me:

    local function organize_imports()
      local params = {
        command = "_typescript.organizeImports",
        arguments = { vim.api.nvim_buf_get_name(0) },
        title = "",
      }
      vim.lsp.buf.execute_command(params)
    end
...


      ts_ls = {
        on_attach = function(client, bufnr)
          client.server_capabilities.documentFormattingProvider = false
          vim.api.nvim_create_autocmd("BufWritePre", {
            buffer = bufnr,
            command = "OrganizeImports",
          })
        end,
        commands = {
          OrganizeImports = {
            organize_imports,
            description = "Organize Imports",
          },
        },
        single_file_support = false,
      },

see full file here: dotfiles-3/public/config/nvim/lua/duhl/lazy/lsp.lua at main · danieluhl/dotfiles-3 · GitHub

1 Like

Thanks for the help!

I tried doing that but it didn’t worked.

local function organize_imports()
	local params = {
		command = "_typescript.organizeImports",
		arguments = { vim.api.nvim_buf_get_name(0) },
		title = "",
	}
	vim.lsp.buf.execute_command(params)
end

local lspconfig = require("lspconfig")

lspconfig.ts_ls.setup({
	on_attach = function(client, bufnr)
		client.server_capabilities.documentFormattingProvider = false
		vim.api.nvim_create_autocmd("BufWritePre", {
			buffer = bufnr,
			command = "OrganizeImports",
		})
	end,
	commands = {
		OrganizeImports = {
			organize_imports,
			description = "Organize Imports",
		},
	},
	single_file_support = false,
})

This is how my code looks currently. The OrganizeImports command is not running directly with :OrganizeImports also