代码之家  ›  专栏  ›  技术社区  ›  Konrad

Vim函数使用传递的参数插入静态文本

vim
  •  1
  • Konrad  · 技术社区  · 7 年前

    背景

    我对写一个分配给键盘快捷键的函数很感兴趣 ; 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
    

    行为

    函数现在插入 在当前行下。我认为 final_string 构造不当。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Konrad    7 年前

    你使用 setline 首先看起来很奇怪,你传递了太多(而且是错误的)论据。也, 设定线

    append(line('.'), final_string)
    

    应该更有效。

    此外,对于串联字符串,请使用 . 操作员而不是 + here ,例如)。