美文网首页码路拾遗Emacs LispEmacs
Emacs优化backward-kill-word函数

Emacs优化backward-kill-word函数

作者: 齐格Insight | 来源:发表于2016-10-17 10:21 被阅读75次

    为什么要改进?

    原生的backward-kill-word函数对母语为非英文的文本处理不是很友善,同时如果backward-word中出现空格或换行符时处理得也不好。

    改进点

    下面对其进行改进,定制自己的backward-kill-word函数。改进点如下:

    1. 如果光标前一个word为中文,只删除前一个中文字;
    2. 如果光标前一个word全为英文,且backward-word中含有空格,则只删除到空格处;
    3. 如果光标前一个word全为英文,且backward-word中含有换行符,则只删除到换行符处。

    代码

    (defun aborn/backward-kill-word ()
      "Customize/Smart backward-kill-word."
      (interactive)
      (let* ((cp (point))
             (backword)
             (end)
             (space-pos)
             (backword-char (if (bobp)
                                ""           ;; cursor in begin of buffer
                              (buffer-substring cp (- cp 1)))))
        (if (equal (length backword-char) (string-width backword-char))
            (progn
              (save-excursion
                (setq backword (buffer-substring (point) (progn (forward-word -1) (point)))))
              (setq ab/debug backword)
              (save-excursion
                (when (and backword          ;; when backword contains space
                           (s-contains? " " backword))
                  (setq space-pos (ignore-errors (search-backward " ")))))
              (save-excursion
                (let* ((pos (ignore-errors (search-backward-regexp "\n")))
                       (substr (when pos (buffer-substring pos cp))))
                  (when (or (and substr (s-blank? (s-trim substr)))
                            (s-contains? "\n" backword))
                    (setq end pos))))
              (if end
                  (kill-region cp end)
                (if space-pos
                    (kill-region cp space-pos)
                  (backward-kill-word 1))))
          (kill-region cp (- cp 1)))         ;; word is non-english word
        ))
    

    绑定快捷键

    (global-set-key [C-backspace] 'aborn/backward-kill-word)
    
    改进后的效果.gif

    相关文章

      网友评论

        本文标题:Emacs优化backward-kill-word函数

        本文链接:https://www.haomeiwen.com/subject/snvayttx.html