小函数-自动生成博客首页链接
背景
由于我的博客是通过 org mode publish 手动生成的,每次添加新的页面都要在首页上添加相应的导航,这个过程非常的烦人。它的过程大体如下:
- 在首页的 org 文件中找一个位置,插入类似 [[][]] 这样的链接
- 首先复制下当前 buffer 的 父文件夹/文件名,类似 xxx/yyy.org 的形式, 填入到第一个[] 中。
- 复制下当前博客的 title,填入到第二个[]中。
这个过程,其实完全可以做到自动化,自动提取信息,然后填入到[[][]]中。
下面通过 elisp 来实现这个过程,只需要通过一个函数就可以做到。
elisp 代码
首先,这个过程做了两件事情:
- 自动生成链接字符串
- 打开首页文件 buffer
具体的代码如下:
(defun blog-path-for-index ()
(interactive)
(setq subpath (substring buffer-file-name (string-match-p
"/[[:word:]_?]+/[[:word:]-?]+.org$"
buffer-file-name) (length buffer-file-name)))
(goto-line 1)
(setq url (format "[[.%s][%s]]" subpath
(buffer-substring-no-properties (search-forward "#+TITLE: ") (line-end-position) )))
(kill-new url)
(message "Will open index file, paste the content to somewhere....")
(sit-for 1)
(find-file "../index.org")
)
这个函数非常的简单,需要注意的就是正则表达式如何写。
这里面有很多很常用的函数:
- buffer-file-name 当前 buffer 的路径
- string-match-p 正则匹配字符串
- substring 获取子字符串 从 start 到 end
- goto-line 将光标定位到第几行
- search-forward 搜索字符串
- line-beginning-position 光标所在行第一个位置
- line-end-position 行最后一个位置
- buffer-substring-no-properties 获取 buffer 从开始到结束位置的内容,而非位置。
- kill-new 将字符复制到剪贴板
- sit-for sleep 的功能
- find-file 打开指定的文件 buffer