Emacs优化backward-kill-word函数

为什么要改进?

原生的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)
Emacs优化backward-kill-word函数_第1张图片
改进后的效果.gif

你可能感兴趣的:(Emacs优化backward-kill-word函数)