Linux下VIM编辑器自动脚本

本文介绍如何使用VIM编辑器的自动化脚本功能,在创建C、H、ASM、SH等文件时,自动填充文件头部信息、注释及基本代码框架,提升编码效率。

前言:VIM自动脚本是在创建C、H、ASM、SH等文件时,自动填写内容到文件中的工具,其语法规则描述如:

       官网描述:https://www.vim.org/

      前人总结铺路https://blog.youkuaiyun.com/yz457694/article/details/77316421

一、脚本作用范围:

           脚本放置在当前用户目录下,文件名为:.vimrc,一般为不可见配置文件,且只对VIM编辑器有效;

           VI编辑器目前不支持vim有些指令,如:set mouse=a(目前在Ubuntu16(Linux4.4.0)上vi已支持vim自动脚本)

二、自动脚本示例:

set nu             "显示行数
set mouse=a        "鼠标控制生效
set tabstop=4      "Tab键为4个空格长度
filetype indent plugin on       "依据文件类型动态配置
set softtabstop=4
set shiftwidth=4
set ruler
set showcmd
set completeopt=preview,menu

"新建不同后缀文件时,依据以下函数自动在新建文件中填充内容,如:注释、文件头等
autocmd BufNewFile *.c exec ":call Set_C_Files()"
autocmd BufNewFile *.h exec ":call Set_H_Files()"
autocmd BufNewFile *.asm exec ":call Set_ASM_Files()"
autocmd BufNewFile *.sh exec ":call Set_SHELL_Files()"

"func中使用到的变量
let $author_name = "Your Name"             "文件中添加作者名
let $author_email = "Your Email"           "文件中添加作者邮箱

"当新建一个*.C文件时执行以下自动补全函数
func Set_C_Files()
		          call setline(1,"/*******************************************************")
		call append(line("."), 	 "* 文件作者: ".$author_name)
		call append(line(".")+1, "* 邮件地址: ".$author_email)
		call append(line(".")+2, "* 文件名称: ".expand("%"))
		call append(line(".")+3, "* 创建时间: ".strftime("%c"))
		call append(line(".")+4, "* 模块描述:")
		call append(line(".")+5, "* ")
		call append(line(".")+6, "* LICENSE:")
		call append(line(".")+7, "* 修改历史:")
		call append(line(".")+8, "*   版本    修改时间        修改人       修改内容")
		call append(line(".")+9, "* -----------------------------------------------------")
		call append(line(".")+10,"*   V0.1   ".strftime("%F")."       ".$author_name."       创建初版")
		call append(line(".")+11,"*******************************************************/")
		call append(line(".")+12,"")
		call append(line(".")+13,"#include <stdio.h>")
		call append(line(".")+14,"#include <stdlib.h>")
		call append(line(".")+15,"#include <string.h>")
		call append(line(".")+16,"")
		call append(line(".")+17,"")
		call append(line(".")+18,"int main(int argc,char *argv[])")
		call append(line(".")+19,"{")
		call append(line(".")+20,"")
		call append(line(".")+21,"    return 0;")
		call append(line(".")+22,"}")
		call append(line(".")+23,"")
		call append(line(".")+24,"/* END Of File '".expand("%")." */")
		call append(line(".")+25,"")
endfun


func Set_H_Files() 
				  call setline(1,"/*******************************************************")
		call append(line("."), 	 "* 文件作者: ".$author_name)
		call append(line(".")+1, "* 邮件地址: ".$author_email)
		call append(line(".")+2, "* 文件名称: ".expand("%"))
		call append(line(".")+3, "* 创建时间: ".strftime("%c"))
		call append(line(".")+4, "* 模块描述:")
		call append(line(".")+5, "* ")
		call append(line(".")+6, "* LICENSE :")
		call append(line(".")+7, "* 修改历史:")
		call append(line(".")+8, "*   版本    修改时间        修改人       修改内容")
		call append(line(".")+9, "* -----------------------------------------------------")
		call append(line(".")+10,"*   V0.1   ".strftime("%F")."       ".$author_name."       创建初版")
		call append(line(".")+11,"*******************************************************/")
		call append(line(".")+12,"")
		call append(line(".")+13,"#ifndef _".toupper(expand("%:r"))."_H")
		call append(line(".")+14,"#define _".toupper(expand("%:r"))."_H")
		call append(line(".")+15,"")
		call append(line(".")+16,"")
		call append(line(".")+17,"")
		call append(line(".")+18,"")
		call append(line(".")+19,"")
		call append(line(".")+20,"")
		call append(line(".")+21,"#endif /* END Of _".toupper(expand("%:r"))."_H */")
		call append(line(".")+22,"")
endfun


func Set_ASM_Files()
				  call setline(1,";*******************************************************")
		call append(line("."), 	 ";* 文件作者: ".$author_name)
		call append(line(".")+1, ";* 邮件地址: ".$author_email)
		call append(line(".")+2, ";* 文件名称: ".expand("%"))
		call append(line(".")+3, ";* 创建时间: ".strftime("%c"))
		call append(line(".")+4, ";* 模块描述:")
		call append(line(".")+5, ";* ")
		call append(line(".")+6, ";* LICENSE :")
		call append(line(".")+7, ";* 修改历史:")
		call append(line(".")+8, ";*   版本    修改时间        修改人       修改内容")
		call append(line(".")+9, ";* -----------------------------------------------------")
		call append(line(".")+10,";*   V0.1   ".strftime("%F")."       ".$author_name."       创建初版")
		call append(line(".")+11,";******************************************************")
		call append(line(".")+12,"")
		call append(line(".")+13,"")
		call append(line(".")+14,"")
		call append(line(".")+15,"")
		call append(line(".")+16,";/* END Of File '".expand("%")."' */")
		call append(line(".")+17,"")
endfun

func Set_SHELL_Files()	
				  call setline(1,"#!\\bin\\bash")
		call append(line("."),   "#######################################################")
		call append(line(".")+1, "# 文件作者: ".$author_name)
		call append(line(".")+2, "# 邮件地址: ".$author_email)
		call append(line(".")+3, "# 文件名称: ".expand("%"))
		call append(line(".")+4, "# 创建时间: ".strftime("%c"))
		call append(line(".")+5, "# 模块描述:")
		call append(line(".")+6, "# ")
		call append(line(".")+7, "# LICENSE :")
		call append(line(".")+8, "# 修改历史:")
		call append(line(".")+9, "#   版本    修改时间        修改人       修改内容")
		call append(line(".")+10,"# -----------------------------------------------------")
		call append(line(".")+11,"#   V0.1   ".strftime("%F")."       ".$author_name."       创建初版")
		call append(line(".")+12,"########################################################")
		call append(line(".")+13,"")
		call append(line(".")+14,"")
		call append(line(".")+15,"")
		call append(line(".")+16,"")
		call append(line(".")+17,"")
		call append(line(".")+18,"# /* END Of File '".expand("%")."' */")
		call append(line(".")+19,"")
endfun


"符号自动补全
:inoremap ( ()<ESC>i
:inoremap ) <c-r>=ClosePair(')')<CR>
:inoremap { {<CR>}<ESC>O
:inoremap } <c-r>=ClosePair('}')<CR>
:inoremap [ []<ESC>i
:inoremap ] <c-r>=ClosePair(']')<CR>
:inoremap " ""<ESC>i
:inoremap ' ''<ESC>i
function! ClosePair(char)
if getline('.')[col('.') - 1] == a:char
            return "\<Right>"
else
            return a:char
endif
endfunction
filetype plugin indent on 
set completeopt=longest,menu

另一个版本的写法,ubuntu上验证过了,开箱即用:

" =================== 基础行为 ===================
set nocompatible            " 去掉 Vi 兼容模式
filetype plugin indent on   " 让插件、缩进规则按文件类型加载
syntax on                   " 语法高亮

" =================== 显示与界面 ===================
set number                  " 绝对行号
set showmatch               " 括号配对闪烁
set matchtime=1
" set cursorline            " 显示光标当前行横线
set ruler                   " 右下角状态栏
set showcmd

" =================== 编码 ===================
set encoding=utf-8
set fileencodings=utf-8,gb18030,cp936
set termencoding=utf-8
set formatoptions+=m        " 多字节字符折行友好
set ambiwidth=double        " 解决中文引号显示问题

" =================== 缩进 ===================
set autoindent
set cindent
set smartindent
set shiftwidth=4            " 自动缩进 4 列
set softtabstop=4
set tabstop=4               " 真正的 <Tab> 宽度
set expandtab               " 把 <Tab> 变成空格(写 Python 必备)
set smarttab

" =================== 搜索 ===================
set hlsearch                " 高亮结果
set incsearch               " 实时跳转
set ignorecase smartcase    " 忽略大小写,但有大写字母时区分

" =================== 撤销/备份 ===================
set undofile                " 持久撤销(~/.vim/undodir 下)
set undodir=~/.vim/undodir
set backupdir=~/.vim/backups
set directory=~/.vim/swaps
if !isdirectory(&undodir)   | call mkdir(&undodir, 'p') | endif
if !isdirectory(&backupdir) | call mkdir(&backupdir, 'p') | endif
if !isdirectory(&directory)| call mkdir(&directory, 'p') | endif

" =================== 按键习惯 ===================
set backspace=2             " 退格删除任意字符
set completeopt=menu,menuone,noselect
inoremap <C-j> <C-n>        " 补全下拉
inoremap <C-k> <C-p>


" =================== 自定义命令 ===================
command! W w                      " 命令模式下 :W 也能保存

" ========== 自动补全括号和引号 ==========
" 普通括号
inoremap ( ()<Left>
" 方括号
inoremap [ []<Left>
" 花括号
inoremap { {}<Left>
" 单引号
inoremap ' ''<Left>
" 双引号
inoremap " ""<Left>

" ==============  工具函数:空文件才插入  ==============
function! s:PutTemplate(lines)
  if line('$') > 1 || getline(1) != ''
    return
  endif
  delete _
  call setline(1, a:lines)
  normal! gg
endfunction

" ==============  通用头注释  ==============
function! s:Header()
  return [
        \ '/******************************************',
        \ ' * -- Copyright (c) 2025 fridin@yeah.net --',
        \ ' * File Name: '.expand('%'),
        \ ' * Time: '.strftime('%c'),
        \ ' * Ver: v1.0',
        \ ' * Description:',
        \ ' ******************************************/',
        \ ''
        \ ]
endfunction

" ==============  C 源文件  ==============
autocmd BufNewFile *.c call s:PutTemplate(
      \ s:Header() + [
      \ '#include <stdio.h>',
      \ '#include <string.h>',
      \ '#include <stdlib.h>',
      \ '#include <stdbool.h>',
      \ '',
      \ '#ifndef uint8_t',
      \ 'typedef unsigned char uint8_t;',
      \ '#endif',
      \ '',
      \ '#ifndef uint16_t',
      \ 'typedef unsigned short uint16_t;',
      \ '#endif',
      \ '',
      \ '#ifndef uint32_t',
      \ 'typedef unsigned int uint32_t;',
      \ '#endif',
      \ '',
      \ '',
      \ 'int main(void)',
      \ '{',
      \ '',
      \ '    return 0;',
      \ '}',
      \ ''
      \ ])

" ==============  C++ 源文件  ==============
autocmd BufNewFile *.cpp call s:PutTemplate(
      \ s:Header() + [
      \ '#include <iostream>',
      \ '',
      \ 'using namespace std;',
      \ '',
      \ 'int main()',
      \ '{',
      \ '    cout << "C plus File Demo" << endl;',
      \ '    return 0;',
      \ '}',
      \ ''
      \ ])

" ==============  头文件  ==============
autocmd BufNewFile *.h call s:PutTemplate(
      \ s:Header() + [
      \ '#ifndef _'.toupper(expand('%:t:r')).'_H_',
      \ '#define _'.toupper(expand('%:t:r')).'_H_',
      \ '',
      \ '',
      \ '#endif /* End of _'.toupper(expand('%:t:r')).'_H_ */',
      \ ''
      \ ])

" ==============  Shell 脚本  ==============
autocmd BufNewFile *.sh call s:PutTemplate([
      \ '#!/bin/bash',
      \ '###############################################',
      \ '# -- Copyright (c) 2025 fridin@yeah.net --',
      \ '# File Name: '.expand('%'),
      \ '# Created Time: '.strftime('%c'),
      \ '# Version: v1.0',
      \ '# Description: ',
      \ '###############################################',
      \ '',
      \ '',
      \ ''
      \ ])

" ==============  Python 脚本  ==============
autocmd BufNewFile *.py call s:PutTemplate([
      \ '#!/usr/bin/env python3',
      \ '# -*- coding: utf-8 -*-',
      \ '# -- Copyright (c) 2025 fridin@yeah.net --',
      \ '# Module Name: '.expand('%:t'),
      \ '# Created: '.strftime('%Y-%m-%d'),
      \ '# Version: v1.0',
      \ '# Description: ',
      \ '',
      \ 'import os',
      \ 'import sys',
      \ '',
      \ '',
      \ 'def script_entry():',
      \ '    """',
      \ '    主函数',
      \ '    """',
      \ '    print("python script demo!")',
      \ '',
      \ 'if __name__ == "__main__":',
      \ '    script_entry()',
      \ ''
      \ ])

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值