" 端口对齐脚本 ver 1.3(空格对齐版)
function! AlignVerilogPorts()
let s:max_type = 0
let s:max_reg = 0
let s:max_bits = 0
let s:max_name = 0
let s:port_list = []
" 第一阶段:定位端口块范围
normal! gg
call search('module\s\+\w*(\s*$', 'W')
normal! j
let start_line = line('.')
call search(');', 'W')
normal! k
let end_line = line('.')
let port_block_lines = getline(start_line, end_line)
" 第二阶段:解析内容
for raw_line in port_block_lines
let line = substitute(raw_line, '\s*$', '', '') " 清理行尾空格
" 处理独立注释行
if line =~ '^\s*//'
call add(s:port_list, {'type': 'comment', 'content': line})
continue
endif
" 处理端口声明
let clean_line = substitute(line, '\s*//.*$', '', '') " 移除行尾注释
let clean_line = substitute(clean_line, '^\s*,', '', '') " 移除行首逗号
let parts = matchlist(clean_line,
\ '^\s*\(input\|output\|inout\)\s\+\(reg\|wire\)\?\s*\(\[.*\]\)\?\s*\(\w\+\)')
if !empty(parts)
" 提取端口元素(处理bits字段中的Tab)
let type = parts[1]
let regwire = !empty(parts[2]) ? parts[2] : ''
let bits = !empty(parts[3]) ? substitute(parts[3], '\t', ' ', 'g') : ''
let name = parts[4]
let comment = matchstr(line, '//.*$') " 保留原始注释
" 更新对齐参数
let s:max_type = max([s:max_type, len(type)+1])
let s:max_reg = max([s:max_reg, len(regwire)+1])
let s:max_bits = max([s:max_bits, len(bits)])
let s:max_name = max([s:max_name, len(name)])
" 存储端口信息
call add(s:port_list, {
\ 'type': 'port',
\ 'port_type': type,
\ 'regwire': regwire,
\ 'bits': bits,
\ 'name': name,
\ 'comment': comment})
endif
endfor
" 第三阶段:生成对齐内容
let formatted = []
let cnt = 0
for item in s:port_list
if item.type == 'comment'
call add(formatted, item.content)
else
let port = item
let prefix = (cnt == 0) ? ' ' : ' ,'
" 各字段对齐处理(强制使用空格)
let type_str = printf('%-'.s:max_type.'s', port.port_type)
let reg_str = printf('%-'.s:max_reg.'s', port.regwire)
let bit_str = printf('%-'.s:max_bits.'s', port.bits)
let name_str = printf('%-'.s:max_name.'s', port.name)
" 组合完整行并清理Tab
let line = prefix . type_str . reg_str . bit_str . ' ' . name_str
if !empty(port.comment)
let line .= ' ' . port.comment
endif
let line = substitute(line, '\t', ' ', 'g') " 全局替换Tab为空格
call add(formatted, substitute(line, '\s\+$', '', ''))
let cnt += 1
endif
endfor
" 第四阶段:替换原始内容
execute start_line.','.end_line.'d'
call append(start_line-1, formatted)
endfunction
" 快捷键绑定建议(按需启用)
" nnoremap <silent> <leader>al :call AlignVerilogPorts()<CR>
根据下面的要求,优化以上脚本。
1.能兼容parameter的定义
2.其他功能保持不变