Emacs Lisp Region操作

Table of Contents

上代码

 1: (defun ykyk-org-insert-str-to-head-tail (flag)
 2:   "操作一个region,或光标所在处的单词,在其首、尾各插入一个字符。
 3: 如果flag为`b',则在操作区域的首、尾各插入一个`*'字符,用于org-mode加粗字符串;
 4: 如果flag为`y',则在操作区域的首、尾各插入一个`「」'字符,用于org-mode加粗字符串;
 5: 如果flag为`d',则在操作区域的首、尾各插入一个`+'字符,用于org-mode删除字符串;
 6: 如果flag尾`q',则在操作区域的首、尾各插入一个`~'字符,用于org-mode引用一段代码。"
 7:   (interactive "sb(*)/y(「」)/d(+)/q(~): ")
 8:   (let (from to input-str output-str)
 9:     ;; 如果当前选中了region,则操作region
10:     (if (use-region-p)
11:         (progn
12:           (setq from (region-beginning))
13:           (setq to (region-end))
14:           (setq input-str (buffer-substring-no-properties from to)))
15:         ;; 如果当前没有选中region,则操作光标所在处的单词
16:         (progn
17:           (setq bounds (bounds-of-thing-at-point 'word))
18:           (setq from (car bounds))
19:           (setq to (cdr bounds))
20:           (setq input-str (buffer-substring-no-properties from to))))
21:     ;; 根据命令标志flag值的不同,插入不同的字符串
22:     (cond
23:       ((string-equal flag "b") (setq output-str (concat " *" input-str "* ")))
24:       ((string-equal flag "y") (setq output-str (concat "「" input-str "」")))
25:       ((string-equal flag "d") (setq output-str (concat " +" input-str "+ ")))
26:       ((string-equal flag "q") (setq output-str (concat " ~" input-str "~ "))))
27:     ;; 操作字符串区域
28:     (progn
29:       (delete-region from to)
30:       (goto-char from)
31:       (insert output-str)
32:       (goto-char (+ to 4)))))
33: 
34: ;; 绑定my-org-insert-str-to-head-tail函数到org-mode-hook并设置快捷键
35: (add-hook 'org-mode-hook
36:           (lambda ()
37:             (local-set-key (kbd "<f3>") 'ykyk-org-insert-str-to-head-tail)))
38: 

关键点

  • (interactive "s" ): 获取交互输入的内容
  • (use-region-p ): 是否选中了区域
  • (buffer-substring-no-properties from to): 返回区域开始和结束位置的内容
  • (delete-region from to):删除区域开始和结束位置的内容
  • (goto-char from): 跳转到区域开始的位置

资源

Date: 2023-05-25 四 11:28