【问题标题】:Vim: how to :source a part of the bufferVim:如何 :source 缓冲区的一部分
【发布时间】:2013-12-14 06:40:55
【问题描述】:

众所周知,我们可以通过:so %:source当前缓冲区。

但有时我想:source 只是缓冲区的一部分,而不是整个缓冲区。比如说,我刚刚在我的.vimrc 中添加了一些内容,并且想要获取该部分的资源,但我不想重新获取所有其他内容。

我尝试了选择文本和:so(实际上是:'<,'>so),但它报告不允许范围。那么,这是怎么做到的呢?

当然,我可以将需要的部分保存到临时文件并获取它,但这显然很烦人。

【问题讨论】:

    标签: vim


    【解决方案1】:

    为什么不使用以下映射来获取文件(或范围):

    " source the current file
    nmap <leader>vs :source %<CR>
    " source a visual range
    vmap <leader>vs y:@"<CR>
    

    现在,你可以按,vs(如果你的mapleader是,),选择的范围将被源化,否则,在正常模式下,当前文件将被源化。

    【讨论】:

    • 这就是为什么我如此喜欢宏(注册)!只需一个“:@”就可以了! ♪ 无需打扰映射或函数。很少有人知道命令模式下的宏与普通模式下一样有用。
    【解决方案2】:

    如果您只选择了一行,则以下工作:

    yq:p<enter>
    

    这也可以:

    y:<control-r>"<enter>
    

    【讨论】:

      【解决方案3】:

      感谢 Ingo Karkat,我采纳了他的主要想法并对其进行了改进。我想改进的地方:

      • 我们必须使用额外的用户指定命令:Execute 而不是标准的:so(好吧,我们可以将用户指定的命令命名为:So,反正使用新的大写版本的命令很烦人)
      • 副作用很小:执行命令后寄存器@z损坏。

      使用下面的脚本,我们可以像以前一样使用:so {file} 命令,我们也可以使用范围::'&lt;,'&gt;so(实际上扩展为:'&lt;,'&gt;Source


      这里:

      " This script provides :Source command, a drop-in replacement for
      " built-in :source command, but this one also can take range and execute just
      " a part of the buffer.
      "
      
      
      " Sources given range of the buffer
      function! <SID>SourcePart(line1, line2)
         let tmp = @z
         silent exec a:line1.",".a:line2."yank z"
         let @z = substitute(@z, '\n\s*\\', '', 'g')
         @z
         let @z = tmp
      endfunction
      
      
      
      " if some argument is given, this command calls built-in command :source with
      " given arguments; otherwise calls function <SID>SourcePart() which sources
      " visually selected lines of the buffer.
      command! -nargs=? -bar -range Source if empty("<args>") | call <SID>SourcePart(<line1>, <line2>) | else | exec "so <args>" | endif
      
      
      
      " in order to achieve _real_ drop-in replacement, I like to abbreviate
      " existing :so[urce] command to the new one.
      "
      " So, we can call :so %  just as before, and we are also call  '<,'>so
      
      cnoreabbr so     Source
      cnoreabbr sou    Source
      cnoreabbr sour   Source
      cnoreabbr sourc  Source
      cnoreabbr source Source
      

      【讨论】:

      • 您在使用cnoreabbr时需要小心。它们在意想不到的地方扩展,例如搜索。有关更多信息,请参阅此帖子stackoverflow.com/questions/7513380/…
      • @PeterRincker,谢谢你的留言,会检查的。
      【解决方案4】:

      您可以定义以下命令,对当前行或传递的范围进行操作:

      ":[range]Execute    Execute text lines as ex commands.
      "           Handles |line-continuation|.
      command! -bar -range Execute silent <line1>,<line2>yank z | let @z = substitute(@z, '\n\s*\\', '', 'g') | @z
      

      【讨论】:

      • 非常感谢,我采纳了你的主要思路并进行了改进,有兴趣的可以看我的回答。
      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多