Vim 函数插入带有传递参数的静态文本



Background

我有兴趣编写一个分配给键盘快捷键的函数;s在调用时将:

  • 取用户参数
  • 反映80 - (string_length(argument) + 4) = n的计算值
  • 插入内容的静态文本:

    # + space argument + space + n * "-"
    

对于参数abc函数将插入:

# abc ---------------------------------------------------------------------

问题

下面的代码不会插入所需的文本,而只会插入值0

法典

" The functions inserts RStudio like section break. Starting with a word and
" continuing with a number of - characters.

function! InsertSectionBreak()
let title = input("Section title: ")            " Collect title
let title_length = strlen(title)                " Number of repetitions
let times = 80 - (title_length + 1)
let char = "-"                                  " Create line break
let sep_line =  repeat(char, times)     
let final_string = '#' + title + ' ' + sep_line " Create final title string
call setline('.', , getline('.'), final_string) " Get current line and insert string
endfunction

" Map function to keyboard shortcut ';s'
nmap <silent>  ;s  :call InsertSectionBreak()<CR>

更新

根据评论中表达的建议,我将函数重新起草为:

function! InsertSectionBreak()
let title = input("Section title: ")            " Collect title
let title_length = strlen(title)                " Number of repetitions
let times = 80 - (title_length + 1)
let char = "-"                  " Create line break
let sep_line =  repeat(char, times)     
let final_string = '#' + title + ' ' + sep_line " Create final title string
call append(line('.'), final_string)            " Get current line and insert string
endfunction

行为

该函数现在在当前行下插入0。我认为final_string没有正确构造。

你对setline的使用似乎很奇怪——首先,你传递了太多(和错误的(论点。此外,setline将替换您说不想要的当前行。

类似的东西

append(line('.'), final_string)

应该工作得更好。

此外,对于连接字符串,请使用.运算符而不是+(例如,请参阅此处(。

最新更新