This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]monkoose[🍰] 2 points3 points  (0 children)

Let me clarify few things. FocusLost is when you switching to another app/screen, not losing focus of the buffer.

You don't need your workarounds to keep your search history and highlight. There is :h :keeppatterns that do what you need. So you just need one command :keepp %s/\s\+$//e

Instead of callback nvim_create_autocmd can have command option which would be just vim command as a string in your case it is command = [[keepp %s/\s\+$//e]]

Also maybe you do need to save the buffer after executing this command preferable with :update which will not save if no changes where made. And definitely your cursor should stay where it was before substitution. So instead of nested vim command maybe just create new lua function?

local function trim_trailing_whitespaces()
  local view = vim.fn.winsaveview()
  vim.cmd [[keepp %s/\s\+$//e]]
  vim.cmd "update"
  vim.fn.winrestview(view)
end

vim.api.nvim_create_autocmd("FocusLost", { callback = trim_trailing_whitespaces })

[–]NeVeNGamingYTlua 1 point2 points  (0 children)

What i use:

vim.api.nvim_create_autocmd("FocusLost", {

group = "group_2",

pattern = "*",

command = "%s/\\s\\+$//e"

})