修改Helm以支持中文拼音搜索

拼音搜索需要注意几个问题:

  1. 拼音正则表达式很容易爆栈:

    (invalid-regexp "Regular expression too big")
    
  2. 支持模糊匹配以获得更好体验 (但会使得正则表达式长度倍增引发问题1):

    (cl-assert (string-match (xxx-build-pinyin-regexp "cs") "测个试"))
    

解决正则表达式爆栈问题的几种思路:

  1. 修改 Emacs 源码,加大缓冲尺寸[1]

    /* This is not an arbitrary limit: the arguments which represent offsets
    into the pattern are two bytes long.  So if 2^15 bytes turns out to
    be too small, many things would have to change.  */
    
    # define MAX_BUF_SIZE (1 << 15)
    
  2. 限制正则表达式大小[2]

    a) @tumashu 大佬暴力法:每生成一个汉字的表达式就试一次,直至遇到 too big 错误。

    b) 我采用的手动计算法: 计算每增加一个(匹配/排除)分组需要消耗多少字节,增加第一个字母/汉字需要多少字节,增加后续汉字需要消耗多少字节。。。 必要时跳过重复/同音字多的汉字。

  3. 把 helm 候选项中的汉字转为拼音,避免生成拼音表达式

    原先的确这么想过,不过考虑到 helm 已经很慢了,就打消了这个念头。

[1] regex-emacs.c\src - emacs.git - Emacs source repository

[2] 如何防止正则表达式爆表?

1 个赞