vim 自动在操作符 前后加上空格 C语言

function! Align_Space()
    let current_line = getline('.')

    let replacement = substitute(current_line,'([a-zA-Z0-9_])([!|^&=<>%*/+-])','1 2','g')
    let newline = substitute(replacement,'([!|^&=<>%*/+-])([a-zA-Z0-9_])','1 2','g')
    let replacement = substitute(newline,'([^&])(s*)(&)s*([a-zA-Z0-9_])','1 34','g')
    let newline = substitute(replacement,'s+->s+','->','g')

    let replacement = newline

    if '"' == matchstr(replacement,'"')
        let newline = substitute(replacement,'s+%s+','%','g')
    else
        let newline = replacement
    endif

    call setline('.',newline)

    if newline != current_line
        call cursor(line('.'),col('.') + 1)
    endif
endfunction
autocmd CursorMovedI *.[ch] call Align_Space()

公司编码规范要求操作符前后添加空格,否则报错

为防止疏漏,动手写了一个简单的vim函数

使用正则表达式替换的原理 实现 在输入操作符时,自动为操作符前后添加空格

替换使用了反向引用原理

()a-zA-Z0-9_ 匹配 操作符前后可能出现的 字符

!|^&=<>%*/+- 匹配操作符

对vim的感想:

1 vim的文档还是不够全面,不知道substitute 是否有参数 能够不移动光标

2 如果在函数中return 则autocmd CursorMovedI   配置的 函数不会再次被调用,除非退出再进入插入模式。

遗留问题:

#include<stdio.h>  以及  ++  的情况 依然添加了空格感觉怪怪的

原文地址:https://www.cnblogs.com/shaivas/p/7694649.html