我有兴趣编写一个在调用时分配给键盘快捷键; 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
的构造正确。
答案 0 :(得分:2)
您对setline
的使用似乎很奇怪-首先,您传递了太多(和错误的)参数。另外,setline
将替换您说不希望的当前行。
类似
append(line('.'), final_string)
应该更好地工作。
另外,要连接字符串,请使用.
运算符,而不要使用+
(例如,请参见here)。