是否可以根据 vim 帮助提示修复 'help-curwin' 命令/功能?

Is it possible to fix the 'help-curwin' command / function from vim help tips?

我不太了解 vim 脚本,只是足以修补我的 vimrc。所以我正在寻找某人的帮助以了解可以在这里做什么。

我使用 vim 帮助页面 'tips.txt' 中的 HelpCurWin 命令,标记 'help-curwin'。该命令旨在打开当前 window 中的给定帮助页面,而不是打开新的拆分。这部分工作正常。这是代码:

" Command to open help page in current window.
command -bar -nargs=? -complete=help HelpCurwin
      \ execute s:HelpCurwin(<q-args>)
let s:did_open_help = v:false
function s:HelpCurwin(subject) abort
  let mods = 'silent noautocmd keepalt'
  if !s:did_open_help
    execute mods .. ' help'
    execute mods .. ' helpclose'
    let s:did_open_help = v:true
  endif
  if !getcompletion(a:subject, 'help')->empty()
    execute mods .. ' edit ' .. &helpfile
  endif
  return 'help ' .. a:subject
endfunction

这是一个与 nvim 文档略有不同的版本(我都试过了):

" Command to open help page in current window.
command -bar -nargs=? -complete=help HelpCurwin
      \ execute s:HelpCurwin(<q-args>)
let s:did_open_help = v:false
function s:HelpCurwin(subject) abort
  let mods = 'silent noautocmd keepalt'
  if !s:did_open_help
    execute mods .. ' help'
    execute mods .. ' helpclose'
    let s:did_open_help = v:true
  endif
  " Fix from nvim documentation.
  if !empty(getcompletion(a:subject, 'help'))
    execute mods .. ' edit ' .. &helpfile
  endif
  return 'help ' .. a:subject
endfunction

正如我所说,在当前 window 中打开帮助页面的主要目标已经实现,但是,我注意到了 3 个副作用:

  1. 当我打开特定的帮助页面时,默认的'help.txt'页面会自动添加到缓冲区列表中,
  2. 'help.txt' 页面将不会作为“未列出”的缓冲区添加到列表中,这会使标签线和缓冲区列表变得混乱,
  3. 即使我在没有指定页面的情况下发出 :HelpCurwin,'help.txt' 页面也会被列为常规缓冲区并且不会得到语法高亮显示(即使文件类型设置正确)。

这些不是关键问题,但它困扰着我,如果有人能帮助我修复它,我将不胜感激,或者,如果不可能,请解释原因。

编辑:我忘记说明我个人使用这个函数主要是从垂直拆分 windows,所以我希望主要针对该用例改进它。

这是我想出的一个解决方案,它比推荐的解决方案更简单 (IMO),并且不会遇到污染缓冲区列表的问题。

" Open help in the current window with :Help
command! -bar -nargs=? -complete=help Help call s:HelpHere(<q-args>)

function! s:HelpHere(subject) abort

  " remember the state of the windows
  let l:window_id = win_getid()
  let l:window_width = winwidth(0)
  let l:num_windows = winnr('$')
  
  " open the help window
  execute 'help ' .. a:subject

  " close the original window if a new help window was opened, and
  " if it should have opened immediately above the original window
  if l:num_windows < winnr('$') && (l:num_windows == 1 || l:window_width >= 80)
    call win_execute(l:window_id, 'close')
  endif

endfunction

新的:Help命令由函数s:HelpHere实现。这个函数只是将它的参数传递给标准 :help 命令,然后如果 :help 创建了一个新的 window.

则关闭原来的 window

大多数时候,这模拟了在调用 :Help 的 window 中打开帮助 window。

但是,如果从窄 window 调用标准 :help 命令,那么它将在可能的几个垂直拆分 windows 之上创建一个新的 window , 所以关闭原来的 window 并不能模拟我们想要的。在这种情况下,我的 :Help 命令不会关闭原来的 window,只是保留 :help.

的默认行为