首页 > 解决方案 > 在VIM中用#居中和填充多个空间

问题描述

我想在 Vim 文件的不同部分之间做一些很好的分离:

我想用 # 填充一行,然后在中间写下我的标题:

############################# 居中标题################## ##############

所以,现在(因为默认情况下终端是 80 个字符宽),我做

i (insert mode)
# 
esc
79 . 

这使得一行#'s。

然后我必须计算标题的宽度,计算起点,转到计算的起点并替换为 R。

这有点乏味......另一方面,我知道通过在可视模式下使用 :center 在 VIM 中居中文本。

是否可以将两者结合起来更直接地获得我正在寻找的东西?

标签: vim

解决方案


由于链接线程中的答案不包含解释的 vimscript 解决方案,我将分享我当时写的那个。

function Foo()
    let title = input('Title: ')
    put =title
    center
    let line=getline(line('.'))
    let spaces = matchstr(line, '^\s*\ze\s')
    let prefix = substitute(spaces, ' ', '#', 'g')
    call setline(line('.'), prefix . ' ' . trim(line) . ' ')
    normal 80A#
    normal d80|
endfunction

noremap <leader>x :call Foo()<cr>
let title = input('Title: ') -> Function that ask for title and store it in var
put =title -> paste content to current line
center -> center it to fill beginning with spaces
let line=getline(line('.')) -> get content of current line into variable
let spaces = matchstr(line, '^\s*\ze\s') -> stores all whitespaces expect last one into variable
let prefix = substitute(spaces, ' ', '#', 'g') -> converts spaces to #
call setline(line('.'), prefix . ' ' . trim(line) . ' ') -> changes content of current line
normal 80A# -> append many # at the end of line
normal d80| -> delete everything after 80 column

推荐阅读