為什么要改進?
原生的backward-kill-word函數對母語為非英文的文本處理不是很友善,同時如果backward-word中出現空格或換行符時處理得也不好。
改進點
下面對其進行改進,定制自己的backward-kill-word函數。改進點如下:
- 如果光標前一個word為中文,只刪除前一個中文字;
- 如果光標前一個word全為英文,且backward-word中含有空格,則只刪除到空格處;
- 如果光標前一個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