簡體   English   中英

將字符串轉換為首字母大寫-Emacs Lisp

[英]Convert string to title case - Emacs Lisp

我正在尋找一個elisp函數,該函數接受一個字符串並以標題大小寫返回相同的字符串(即,所有單詞都大寫,除了“ a”,“ an”,“ on”,“ the”等)。

我找到了這個腳本 ,它需要一個標記區域。

只是,我需要一個接受字符串變量的函數,因此可以將其與replace-regex 我希望看到上述腳本的版本可以接受或...

像這樣嗎

(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"))

我想說,您鏈接的腳本在標題框方面做得很好。 您可以按原樣使用它。

這給我們留下了兩個問題:

  • 我們如何使其接受字符串?
  • 我們如何編寫一個既可以接受字符串也可以接受(標記)區域的函數?

通常在未顯示的臨時緩沖區中使用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(或更高版本)下。

使用Mx

upcase-initials-region是'C源代碼'中的一個交互式內置函數。

upcase-initials-region BEG END

大寫該區域中每個單詞的首字母。 這意味着每個單詞的第一個字符都將轉換為標題大寫或大寫,其余部分則保持不變。 在程序中,提供兩個參數,即要操作的開始和結束字符位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM