簡體   English   中英

如何在 Emacs 中折疊 html 標簽?

[英]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>" 我猜您希望\\1BEGIN模式的第一個子組匹配的任何內容替換。

代碼中的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.

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