特性:前缀空白字符移除
文档
:2025-07-26-11-07:
移除前缀空白字符。
使用: <<@(LINK,rm-ws-p=1)>>
如片段展开的最终结果嵌套在另外的片段中,且含缩进,移
除其缩进。
使用场景:
考虑如下文本块:
a:
(progn
<<b>>)
b:
(def rm-ws-p
\"Remove whitespace prefix
<<c>>\")
c:
移除前缀空白字符。
当展开 a 时,我们会得到如下片段:
(progn
(def rm-ws-p
\"Remove whitespace prefix
移除前缀空白字符。\"))
受 a 缩进影响,作为 b 的 docstring, c 每行都被填
充了缩进用的空白字符。为此,我们提供此特性移除前
缀空白字符。经此特性处理后, a 展开为:
(progn
(def rm-ws-p
\"Remove whitespace prefix
移除前缀空白字符。\"))
:end:
实现
#+name: 2025-07-26-11-08
#+begin_src emacs-lisp :eval no
(lambda (&optional body conf)
"Remove whitespace prefix.
<<@([[id:org-noweb-expand-link::feat-doc:remove-whitespace-prefix]],rm-ws-p=1)>>"
;; 有 body 时往 body 每行行首加入 mark;
;; 无 body 时当 hook 用。
;;
;; 依赖: rm-ws-p.
(let* ((mark (concat
"org-noweb-expand-link"
":rm-ws-p"))
(re (concat "^[ \t]*" mark)))
(cond
(body
(cond
((and (plist-get conf :rm-ws-p)
(not (plist-get conf :failed)))
(add-hook 'org-babel-tangle-body-hook
rm-ws-p)
(string-join
(mapcar
(lambda (line) (concat mark line))
(string-split body "\n"))
"\n"))
(body)))
(t
(save-match-data
(goto-char (point-min))
(while (re-search-forward re nil t)
(replace-match "")))
(remove-hook 'org-babel-tangle-body-hook
rm-ws-p)))))
#+end_src
注册到整体结构中的文本片段:
#+name: 2025-07-26-11-09
#+begin_src emacs-lisp :eval no
;;; Remove Whitespace Prefix
(!let ((rm-ws-p
(make-symbol
(concat
"org-noweb-expand-link" ":"
"remove-whitespace-prefix"))))
(!def rm-ws-p
<<@([[id:org-noweb-expand-link::remove-whitespace-prefix]])>>)
(entry 'add-post-process
rm-ws-p 'remove-whitespace-prefix)
(entry 'add-babel-var 'rm-ws-p))
#+end_src