自动转换表格格式的Vim自定义命令

2023-04-27  本文已影响0人  SpaceCat

0、介绍

有时候会遇到将xls格式的表格,转换为markdown格式的情况。手工转换,非常麻烦,这里在vim中通过一个自定义命令实现。

1、代码实现

vimrc中添加如下内容:

" convert a table copy from excel to makedown table format
" convert a column value list to a markdown format row
function! GenerateAMarkdownTableRowFunc(colValueList)
    let resultStr = ''
    let i = 0
    for colValue in a:colValueList
        let resultStr = resultStr . " | " . colValue
        let i = i + 1
    endfor
    let resultStr = resultStr . " |"
    " remove the space at the beginning
    let resultStr = strpart(resultStr, 1, strlen(resultStr) - 1)
    return resultStr
endfunction
" call GenerateAMarkdownTableRowFunc to convert xls table to markdown
function! GenerateMarkdownTable() 
    " read all lines into a list
    let allLines = []
    g/$/let line = getline(".") | call add(allLines, line)
    let resultLines = []

    " deal with the table head
    let colValueList = split(allLines[0], '\t', 1)
    call add(resultLines, GenerateAMarkdownTableRowFunc(colValueList))
    " deal with the split line between table body and head
    let colValueList = split(allLines[0], '\t', 1)
    let tmpColSplitLineStr = ''
    let i = 0
    for colValue in colValueList
        let tmpColSplitLineStr = tmpColSplitLineStr . " | " . "---"
        let i = i + 1
    endfor
    let tmpColSplitLineStr = tmpColSplitLineStr . " |"
    call add(resultLines, strpart(tmpColSplitLineStr, 1, strlen(tmpColSplitLineStr) - 1))

    " deal with the table body
    let index = 1
    while index < len(allLines)
        let curLine = allLines[index]
        let valList = split(curLine, '\t', 1)
        call add(resultLines, GenerateAMarkdownTableRowFunc(valList))
        let index = index + 1
    endwhile

    " join all lines
    let resultStr = join(resultLines, "\n")
    " replace content of current buffer
    let @u = resultStr
    normal! ggdG
    normal! 0"up
    echo "Markdown table converted!"
endfunction
command GenerateMarkdownTable exec GenerateMarkdownTable()

重新启动vim即可生效。

2、使用

假设有表格从excel中粘贴到一个空的vim缓冲区中,是如下格式:

姓名  年龄  性别  描述
Tom     男   tom是一个好孩子
Jeff    41  男   
Kate    33  女   Kate is a good girl.

执行前面自定义的vim命令,:GenerateMarkdownTable,即可将其转换为如下格式:

| 姓名 | 年龄 | 性别 | 描述 |
| --- | --- | --- | --- |
| Tom |  | 男 | tom是一个好孩子 |
| Jeff | 41 | 男 |  |
| Kate | 33 | 女 | Kate is a good girl. |

3、说明

这个例子中,除了实现了前面的需求,也可以学习到如何读取vim缓冲区中的内容进行变换,有很多灵活运用的空间。

上一篇 下一篇

猜你喜欢

热点阅读