Skip to content

README/use case: describe how to make ['_'] = { 'trim_whitespace', 'trim_newlines' }, play nice with editorconfig autocommands #586

Open
@matu3ba

Description

@matu3ba

Did you check existing requests?

  • I have searched the existing issues

Describe the feature

Wanted: Extend the configuration in the usage section to some more low level usage, but probably it is simpler to mention 1. combined actions, 2. ['_'] problems:

local fmts_by_ft = {
  c = { 'clang-format' }, -- // clang-format off|on
  ['_'] = { 'trim_whitespace', 'trim_newlines' }, -- <- might make problems behavior for external fmting etc
}

local user_fmts_by_ft = {
  zig = function(args)
    vim.lsp.buf.code_action { context = { only = { 'source.fixAll' } }, apply = true }
    vim.loop.sleep(5)
    -- SHENNANIGAN conform.nvim can screw up formatting the first time
    vim.lsp.buf.format()
  end,
}

vim.api.nvim_create_autocmd('BufWritePre', {
  group = aucmds_conform_fmt,
  pattern = '*',
  callback = function(args)
    local ft = vim.bo[args.buf].filetype
    if fmts_by_ft[ft] == nil then
      if user_fmts_by_ft[ft] ~= nil then
        user_fmts_by_ft[ft]()
      else
        conform.format { bufnr = args.buf, formatters = { 'trim_whitespace', 'trim_newlines' } }
      end
    else
      conform.format { bufnr = args.buf, formatters = { fmts_by_ft[vim.bo[args.buf].filetype] } }
    end
  end,
})

Provide background

Justification: Running one or multiple code actions to autofix code and then the formatter (because formatter might break code for the autofix) prevents trim_whitespace and trim_newlines from being usable.

For example, I have

vim.api.nvim_create_autocmd('BufWritePre', {
  group = aucmds_zig_fmt,
  pattern = { '*.zig', '*.zon' },
  callback = function()
    vim.lsp.buf.code_action {
      -- SHENNANIGAN lsp.CodeActionContext: diagnostics field is optional,
      -- but shown as error by lsp from meta information
      context = { only = { 'source.fixAll' } },
      apply = true,
    }
    vim.loop.sleep(5)
    -- SHENNANIGAN conform.nvim can screw up formatting the first time
    vim.lsp.buf.format()
  end,
})

What is the significance of this feature?

nice to have

Additional details

Going more low level makes things less error prone, if the options '*' and _ or doing lsp actions before formatting (or custom checks) are wanted.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions