Markdown标题自动添加编号

markdown写文档很方便,但是有个困扰的地方,就是标题的编号问题。
写文档的时候,经常会在中间插入新的标题和内容,所以手动管理编号的话,如果新的标题插在前面,则要调整后面所有的编号。

如果在文档完成后再手动加上编号的话,不仅容易忘记,
而且有时候我们是在其他编辑器里编辑文档再导出markdown的,比如用语雀编写文档再导出markdown,这时每次修改文档再导出就要重新给导出的文档添加编号。
我用语雀比较多,常常因此而困扰。

所以,用golang简单写了个命令行工具,用来给markdown文档的标题添加编号。

1. 处理流程

处理过程很简单:

  1. 首先读取markdown文件的所有行
  2. 然后依次解析每一行
    1. 如果是标题行,添加编号
    2. 非标题行,略过
  3. 将添加了编号的内容重新写入markdown文件

2. 主要步骤

主要的步骤有三个:

2.1. 读取markdown文件

// 获取文件所有的行
func getAllLines(fp string) ([]string, error) {
 fi, err := os.Open(fp)
 if err != nil {
 return nil, err
 }
 defer fi.Close()
 br := bufio.NewReader(fi)
 lines := make([]string, 0)
 for {
 a, _, c := br.ReadLine()
 if c == io.EOF {
 break
 }
 lines = append(lines, string(a))
 }
 return lines, nil
}

返回的是文件所有行的数组。

2.2. 添加标题编号

// 添加标题编号,最多支持五级标题
func addTitle(lines []string) ([]string, []ChangedLine) {
	cLines := make([]ChangedLine, 0)
	titles := [5]int{0, 0, 0, 0, 0}
	for index, line := range lines {
	titleLevel := getTitleLevel(line)
	switch titleLevel {
	case 1:
	titles[0]++
	lines[index] = strings.Replace(line, "# ", fmt.Sprintf("# %d. ", titles[0]), 1)
	titles = [5]int{titles[0], 0, 0, 0, 0}
	case 2:
	titles[1]++
	lines[index] = strings.Replace(line, "## ", fmt.Sprintf("## %d.%d. ", titles[0], titles[1]), 1)
	titles = [5]int{titles[0], titles[1], 0, 0, 0}
	case 3:
	titles[2]++
	lines[index] = strings.Replace(line, "### ", fmt.Sprintf("### %d.%d.%d. ", titles[0], titles[1], titles[2]), 1)
	titles = [5]int{titles[0], titles[1], titles[2], 0, 0}
	case 4:
	titles[3]++
	lines[index] = strings.Replace(line, "#### ", fmt.Sprintf("#### %d.%d.%d.%d. ", titles[0], titles[1], titles[2], titles[3]), 1)
	titles = [5]int{titles[0], titles[1], titles[2], titles[3], 0}
	case 5:
	titles[4]++
	lines[index] = strings.Replace(line, "##### ", fmt.Sprintf("##### %d.%d.%d.%d.%d. ", titles[0], titles[1], titles[2], titles[3], titles[4]), 1)
	titles = [5]int{titles[0], titles[1], titles[2], titles[3], titles[4]}
	}
	if titleLevel != -1 {
	cLines = append(cLines, ChangedLine{LineNo: index + 1, Before: line, After: lines[index]})
	}
	}
	return lines, cLines
}

这里支持最多5级标题的编号,写的略显繁琐,本身逻辑比较简单,暂时没有去优化。

获取标题的等级写了简单的小函数:
(根据markdown的语法,根据每行开头 # 的个数来判断是几级的标题)

// 获取标题的等级
func getTitleLevel(s string) int {
	if strings.HasPrefix(s, "# ") {
	return 1
	}
	if strings.HasPrefix(s, "## ") {
	return 2
	}
	if strings.HasPrefix(s, "### ") {
	return 3
	}
	if strings.HasPrefix(s, "#### ") {
	return 4
	}
	if strings.HasPrefix(s, "##### ") {
	return 5
	}
	return -1
}

2.3. 新内容写入markdown文件

// 写入多行数据
func writeLines(fp string, lines []string) error {
	content := strings.Join(lines, "\n")
	return ioutil.WriteFile(fp, []byte(content), 0644)
}

2.4. 步骤合并起来

此命令行工具使用了 cobra 框架,最后把修改的部分也打印出来了。

type ChangedLine struct {
	LineNo int
	Before string
	After string
}
var rootCmd = &cobra.Command{
	Use: "mt",
	Short: "给mkdown标题添加编号",
	RunE: func(cmd *cobra.Command, args []string) error {
	if len(args) < 1 {
	return fmt.Errorf("NO file input!")
	}
	fp := args[0]
	lines, err := getAllLines(fp)
	if err != nil {
	return err
	}
	newLines, changedLines := addTitle(lines)
	err = writeLines(fp, newLines)
	if err != nil {
	return err
	}
	fmt.Println("修改的内容:>>>")
	for _, cl := range changedLines {
	fmt.Println("===================================")
	fmt.Printf("line【%d】:\n修改前:%s\n修改后:%s\n", cl.LineNo, cl.Before, cl.After)
	fmt.Println("===================================")
	}
	return nil
	},
}

3. 使用方法

go build # 编译后生成 mdtitle 二进制文件
./mdtitle xxxx.md # 运行

本文最后附加的下载地址中有完整源码。
其中也包含编译好的二进制(linux和windows版本2个都有)。

4. 补充说明

今天一时起意写的小工具,只是为了方便给自己从语雀导出的markdown加标题编号。
一定还有很多不足之处有待完善,写完之后我自己感觉至少还需要完善:

  1. 没有判断文档是否已经有标题编号,已经有标题编号的情况,应当忽略继续添加标题编号
  2. 标题的层级是硬编码的,目前只支持5级标题(不过5级应该满足大部分情况了)

代码下载地址(其中包含编译好的linux和windows下的二进制):
md-title.zip: https://url11.ctfile.com/f/45455611-859852761-9f5f8e?p=6872
(访问密码: 6872)

作者:wang_yb原文地址:https://www.cnblogs.com/wang_yb/p/17427971.html

%s 个评论

要回复文章请先登录注册