在vim中附加到所选文本的顶部和底部

时间:2014-04-21 18:27:58

标签: vim

所以我有以下文本(====分隔符表示选定的文本):

This is some text
I'm not interested in.
    This is indented text
    not important.
    =====================
    This text portion is
    selected.
    =====================
    Also not important
    indented text
Other text i'm not
interested in.

现在我想创建一个vim函数,以便在调用时,它会在顶部和底部附加一些默认文本。例如,我想结束:

This is some text
I'm not interested in.
    This is indented text
    not important.
    THIS TEXT WAS APPENDED
    AFTER FUNCTION CALL
    This text portion is
    selected.
    THIS OTHER TEXT WAS
    APPENDED AFTER THE SAME
    FUNCTION CALL
    Also not important
    indented text
Other text i'm not
interested in.

请注意,应保留缩进(感谢benjifisher) 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

这有点草率,但它有效:

function! Frame() range
  '<put!=\"THIS OTHER TEXT WAS\nAPPENDED AFTER\nFUNCTION CALL\"
  '>put=\"THIS OTHER TEXT WAS\nAPPENDED AFTER THE SAME\nFUNCTION CALL\"
endfun

在可视模式下选择您的行,然后键入

:'<,'>call Frame()

(自动插入范围'<,'>。)将:executea:firstlinea:lastline一起使用:help function-range-example,而非'<视觉标记'>:silent,但这有点复杂。如果您不想被告知已经添加了3行(两次),您也可以使用:call append()为每个命令添加前缀。

这是一个版本,可以根据更新的问题中的请求复制第一个和最后一个选定行的缩进。此版本使用:put代替a:firstline,这样可以更方便地使用a:lastline" Add lines at the bottom before adding at the top, since the line numbers " will change when you add lines. function! Frame() range " Define a list of lines and prepend the desired indentation. let botlines = ['THIS OTHER TEXT WAS', 'APPENDED AFTER THE SAME', 'FUNCTION CALL'] let botspaces = matchstr(getline(a:lastline), '\s*') let lines = [] for line in botlines call add(lines, botspaces . line) endfor " Now add those lines at the bottom. call append(a:lastline, lines) " Now do the same thing at the top. let toplines = ['THIS OTHER TEXT WAS', 'APPENDED AFTER', 'FUNCTION CALL'] let topspaces = matchstr(getline(a:firstline), '\s*') let lines = [] for line in toplines call add(lines, topspaces . line) endfor call append(a:firstline - 1, lines) endfun ;可能,如果您想要使用Visual视频以外的范围调用该函数,这将非常有用。

{{1}}