如何防止vim替换命令移动光标

4
我所在的公司在源文件中使用特殊的头部,其中包含上次修改的日期。
我编写了一个 vim 脚本,在每次缓冲区写入时自动更新这个日期。
我使用搜索/替换功能来完成这个技巧。
现在的问题是,替换操作会把光标移动到文件开头,这非常麻烦,因为每次缓冲区写入后,用户都需要手动跳回之前的编辑位置。
有没有人知道如何防止 vim 在更新日期时跳转,或者至少让它跳回到先前的位置?

可能是Vim替换所有内容时光标不移动的重复问题。 - Lieven Keersmaekers
只需在脚本的最后一行添加“0”。 - romainl
@romainl 我尝试了,但似乎不起作用。它应该做什么? - Antoine
把光标放在缓冲区的顶部。顺便说一下,你忘记给我们展示你的脚本了。 - romainl
2个回答

7

可以交互地使用 <C-O> 或更改标记 `` 返回到原始位置,如在 vim replace all without cursor moving 中所示。

在Vimscript中,特别是当它在每个缓冲区写入时运行时,我会将代码包装起来:

let l:save_view = winsaveview()
    %substitute///
call winrestview(l:save_view)

以前的移动命令可能仍会影响窗口视图(即在视口中显示的确切行和列),而这个解决方案会将一切恢复原样。

额外内容

还要注意,:substitute中使用的{pattern}会被添加到搜索历史记录中。为了避免这种情况,请追加

call histdel('search', -1)

当在:function中使用时,搜索模式本身不会受到影响。

或者在Vim 8中使用:keeppatterns命令:

keeppatterns %substitute///

相关插件

我在我的AutoAdapt插件中实现了类似的功能。你也可以在那里看到所有这些技巧的应用。


你可以使用 keeppatterns %s/// 替代 call histdel - tckmn

0

我认为使用函数substitute()可以保留您的更改列表和跳转列表。在neovim中,我使用一个函数来以这种方式更改文件修改日期:

M.changeheader = function()
    -- We only can run this function if the file is modifiable
    local bufnr = vim.api.nvim_get_current_buf()
    if not vim.api.nvim_buf_get_option(bufnr, "modifiable") then
        require("notify")("Current file not modifiable!")
        return
    end
    -- if not vim.api.nvim_buf_get_option(bufnr, "modified") then
    --     require("notify")("Current file has not changed!")
    --     return
    -- end
    if vim.fn.line("$") >= 7 then
    os.setlocale("en_US.UTF-8") -- show Sun instead of dom (portuguese)
    local time = os.date("%a, %d %b %Y %H:%M:%S")
    local l = 1
    while l <= 7 do
        vim.fn.setline(l, vim.fn.substitute(vim.fn.getline(l), 'last (change|modified): \\zs.*', time , 'gc'))
        l = l + 1
    end

        require("notify")("Changed file header!")
    end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接