LoginSignup
4
4

More than 5 years have passed since last update.

Emacsで選択範囲の文字を特定の用途へ置換する関数を作っておく

Last updated at Posted at 2014-02-02

選択範囲をリストに指定した文字で置換します。

複数行を半角スペース一つあけて1行に連結
:small_blue_diamond:選択 -> M-x my-join-multi-lines

ブログ用にエスケープ
:small_blue_diamond:選択 -> M-x my-escape-region-for-blog-post

全角数字を半角数字に
:small_blue_diamond:選択 -> M-x my-convert-to-single-byte-number

半角数字を全角数字に
:small_blue_diamond:選択 -> M-x my-convert-to-multi-byte-number

句読点などの約物を半角に
:small_blue_diamond:選択 -> M-x my-convert-yakumono-to-half-width

(defun my-replace-strings-in-region-by-list ($list)
  "Replace strings in a region according to $list"
  (if mark-active
      (let* (($beg (region-beginning))
             ($end (region-end))
             ($word (buffer-substring-no-properties $beg $end)))
        (mapc (lambda ($r)
                (setq $word (replace-regexp-in-string (car $r) (cdr $r) $word)))
              $list)
        (delete-region $beg $end)
        (insert $word))
    (error "Need to make region")))
;; 複数行を一行に
(defun my-join-multi-lines ()
  "Escape code in region for blog post"
  (interactive)
  (my-replace-strings-in-region-by-list
   '(("\n+" . " "))))
;; ブログ用にエスケープ
(defun my-escape-region-for-blog-post ()
  "Escape code in region for blog post"
  (interactive)
  (my-replace-strings-in-region-by-list
   '(("\&" . "&")
     ("\<" . "&lt;")
     ("\>" . "&gt;")
     ;; ("\"" . "&quot;")
     ;; ("\'" . "&#039;")
     ("\t" . "  "))))
;; 全角数字を半角数字に
(defun my-convert-to-single-byte-number ()
  "Convert multi-byte number in region into single-byte number"
  (interactive)
  (my-replace-strings-in-region-by-list
   '(("1" . "1")
     ("2" . "2")
     ("3" . "3")
     ("4" . "4")
     ("5" . "5")
     ("6" . "6")
     ("7" . "7")
     ("8" . "8")
     ("9" . "9")
     ("0" . "0"))))
;; 半角数字を全角数字に
(defun my-convert-to-multi-byte-number ()
  "Convert multi-byte number in region into single-byte number"
  (interactive)
  (my-replace-strings-in-region-by-list
   '(("1" ."1")
     ("2" ."2")
     ("3" ."3")
     ("4" ."4")
     ("5" ."5")
     ("6" ."6")
     ("7" ."7")
     ("8" ."8")
     ("9" ."9")
     ("0" ."0"))))
;; 句読点などの約物を半角に
(defun my-convert-yakumono-to-half-width ()
  "Replace multi byte punctuation marks to half width chars"
  (interactive)
  (my-replace-strings-in-region-by-list
   '(("、" . "、")
     ("。" . "。")
     ("「" . "「")
     ("」" . "」")
     ("[" . "[")
     ("]" . "]")
     ("{" . "{")
     ("}" . "}")
     ("(" . "(")
     (")" . ")")
     ("・" . "・"))))

何か設定しておくと便利な置換がありましたらコメント欄で教えて下さい。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4