单词反向转大写

Jiacai Liu

发布: 2022-08-08   更新: 2022-08-08   标签: text

文章目录

输入大写字母的方式主要有以下两种:

  1. 按住 Shift 的同时,依次输入字母是一种,
  2. 当字母比较多时,可以先按下 CapsLock ,然后键入字母

但相信对大多数人来说,大写字母的单词更难读,有相关研究做证明:

Lowercase letters have a more distinctive shape than capital letters, therefore they can be perceived more quickly than uppercase letters. Because readers are frequently exposed to a word, they no longer have to "read" the word, but instantly recognize the meaning by the familiar shape of the group of letters.

因此很多人采用下面的方式输入大写字母的方式:

这样的好处是便于识别是否有拼写错误,对于 Emacs 来说就是 M-u(upcase-word) ,但是有一点麻烦的地方在于:在转化前,需要先 M-b 移动到字母开始处,然后再按 M-u 一次,如果有连字符,那么移动、转大写都需要按多次,显得有些麻烦。

(upcase-word ARG) 支持传入负数向后移动,但是遇到字母中有连字符时只会转化最后一个单词,而且光标不会移动,如果想继续转化,还是需要 M-b ,因此无法胜任,只能自己写代码解决:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
(defun my/upcase-backwards ()
  "Upcase word in reverse direction, back until the first space char or beginning-of-line"
  (interactive)
  (save-excursion
    ;; move to first non-space char
    (skip-syntax-backward " " (line-beginning-position))
	(push-mark)
    (let ((beginning (or (re-search-backward "[[:space:]]" (line-beginning-position) t)
                         (line-beginning-position)))
          (end (mark)))
      (unless (= beginning end)
	    (upcase-region beginning end)))))

(global-set-key (kbd "M-o") 'my/upcase-backwards)

上面的函数用空格作为单词的边界,这样就能一次性处理 a-b-c 这种用连字符串起来的单词了。此外,还处理了以下几个 corner case:

  1. 只在同一行内操作
  2. 当光标所在处为空格时,向后回溯,直到找到非空格字母

示例演示

  • 处理前( | 为光标)
abc  |abc
abc-abc|
  • 处理后
ABC  |abc
ABC-ABC|


收听方式

反馈