将字符串转换为首字母大写 - Emacs Lisp

Convert string to title case - Emacs Lisp

我正在寻找一个接受字符串的 elisp 函数,returns 在标题大小写中相同(即所有单词大写,"a"、"an"、"on", "the", 等等).

我找到了this script,需要标记区域

只是,我需要一个接受字符串变量的函数,所以我可以将它与replace-regex一起使用。我很想看到上面脚本的一个版本,它可以接受 or...

是这样的吗?

(progn
  (defun title-case (input) ""
         (let* (
                (words (split-string input))
                (first (pop words))
                (last (car(last words)))
                (do-not-capitalize '("the" "of" "from" "and" "yet"))) ; etc
           (concat (capitalize first)
                   " "
                   (mapconcat (lambda (w)
                                (if (not(member (downcase w) do-not-capitalize))
                                    (capitalize w)(downcase w)))
                              (butlast words) " ")
                   " " (capitalize last))))
  (title-case "the presentation of this HEADING OF my own from my keyboard and yet\n"))

我想说您链接到的脚本在标题大小写方面做得很好。你可以使用它 as-is.

这给我们留下了两个问题:

  • 我们如何让它接受一个字符串?
  • 我们如何编写接受字符串或(标记的)区域的函数?

在 Emacs 中使用字符串通常是在不显示的临时缓冲区中完成的。你可以像这样写一个包装器:

(defun title-capitalization-string (s)
  (with-temp-buffer
    (erase-buffer)
    (insert s)
    (title-capitalization (point-min)
                          (point-max))
    (buffer-substring-no-properties (point-min)
                                    (point-max))))

现在,对于一个神奇地完成你的意思的函数,考虑这样的事情:

(defun title-capitalization-dwim (&optional arg)
  (interactive)
  (cond
   (arg
    (title-capitalization-string arg))
   ((use-region-p)
    (title-capitalization-string
     (buffer-substring-no-properties (region-beginning)
                                     (region-end))))
   (t
    (title-capitalization-string
     (buffer-substring-no-properties (point-at-bol)
                                     (point-at-eol))))))

它接受一个可选参数,或一个活动区域或回退到当前行的文本。请注意,此函数在交互使用时并不是很有用,因为它不显示任何效果。还给小费https://www.emacswiki.org/emacs/titlecase.el

许可证

除了站点的默认许可外,我将所有这些代码都置于 Apache License 2.0 和 GPL 2.0(或更高版本,由您选择)之下。

使用M-x

upcase-initials-region is an interactive built-in function in ‘C source code’.

(upcase-initials-region BEG END)

Upcase the initial of each word in the region. This means that each word’s first character is converted to either title case or upper case, and the rest are left unchanged. In programs, give two arguments, the starting and ending character positions to operate on.