[英]How to fold html tag in Emacs?
我正在使用 hs-minor-mode 和 fold-dwim 模式。
我在正則表達式下面添加了通過設置變量 hs-special-modes-alist 來匹配 html 標簽:
(html-mode "<\\([A-Za-z][A-Za-z0-9]*\\)[^>]*>.*?" "</\\1>" "-->" nil nil)
;; Format: (MODE START END COMMENT-START FORWARD-SEXP-FUNC ADJUST-BEG-FUNC)
但是當我在 html 文件中使用它(使用命令 fold-dwim-toggle.)時沒有效果。
這是我的 .emacs 文件中的相關部分:
;; hideshow
(setq hs-special-modes-alist
(mapcar 'purecopy
'((c-mode "{" "}" "/[*/]" nil nil)
(c++-mode "{" "}" "/[*/]" nil nil)
(bibtex-mode ("@\\S(*\\(\\s(\\)" 1))
(java-mode "{" "}" "/[*/]" nil nil)
(js-mode "{" "}" "/[*/]" nil)
;; (html-mode "<!-- {{{ " "<!-- }}} -->" " -->" nil t)
(html-mode "<\([A-Za-z][A-Za-z0-9]*\)[^>]*>.*?" "</\1>" "-->" nil nil) ;gw: self edited, see blw ref:
;; http://www.regular-expressions.info/examples.html
)))
我不熟悉hs-special-modes-alist
。 但是簡要地查看源代碼,我看不出任何跡象表明END
模式可以引用BEGIN
模式的子組,我假設,這是您嘗試使用"</\\1>"
。 我猜您希望\\1
被BEGIN
模式的第一個子組匹配的任何內容替換。
代碼中的hs-special-modes-alist
示例都沒有使用子組匹配號(例如\\1
)。 並且文檔說END
本身需要是一個正則表達式。 據推測,它獨立於匹配開頭的START
匹配結尾。
該文檔確實提到START
本身可以“是(COMPLEX-START MDATA-SELECTOR)
形式的列表,其中COMPLEX-START
是帶有多個部分的正則表達式, MDATA-SELECTOR
是一個整數,指定哪個子匹配是正確的在調用hs-forward-sexp-func
之前調整點的位置。
我不認為這與您想要的立即對應,但至少它表明使用了子組匹配。 也許您可以使用它來匹配開始和結束標簽。 我沒有進一步查看代碼,例如查看hs-forward-sexp-func
的使用位置和方式。
另一方面,您通常需要在 Lisp 字符串中使用雙反斜杠。 所以如果你想要\\1
你可能需要使用"</\\\\1>"
。 同樣,對於\\(
- 使用\\\\(
等。
也許這會讓你更接近你想要的。
(請注意,順便說一句,正則表達式是嘗試解析 HTML 代碼等內容的糟糕方法。)
我在這里回答了這個問題: Does emacs offer hide show for html mode ,但又來了。
我為 mhtml-mode 寫了這個,它工作得很好,它可以按標簽折疊 HTML 以及嵌入的 CSS 和 JS。 只需將它添加到您的 emacs 配置文件中,您就可以開始使用了。
;; When called this automatically detects the submode at the current location.
;; It will then either forward to end of tag(HTML) or end of code block(JS/CSS).
;; This will be passed to hs-minor-mode to properly navigate and fold the code.
(defun mhtml-forward (arg)
(interactive "P")
(pcase (get-text-property (point) 'mhtml-submode)
('nil (sgml-skip-tag-forward 1))
(submode (forward-sexp))))
;; Adds the tag and curly-brace detection to hs-minor-mode for mhtml.
(add-to-list 'hs-special-modes-alist
'(mhtml-mode
"{\\|<[^/>]*?"
"}\\|</[^/>]*[^/]>"
"<!--"
mhtml-forward
nil))
正則表達式細分:
"{\\\\|<[^/>]*?"
: 匹配{
或任何打開的 HTML 標簽。 它最多匹配但不包括開始標記中的結束>
。 這允許將<script>
和<style>
標簽視為 HTML 標簽而不是 JS 或 CSS。
"}\\\\|</[^/>]*[^/]>"
:匹配}
或結束標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.