[英]Wrap selection in Open/Close Tag like TextMate?
在TextMate中 ,可以使用ctrl-shift-w將文本包裝在Open / Close標記中,使用ctrl-shift-cmd -w將每行包裝在Open / Close標記的區域中。 如何使用emacs lisp在Emacs中實現相同的功能?
emacs becomes <p>emacs</p>
而......
emacs textmate vi becomes <li>emacs</li> <li>textmate</li> <li>vi</li>
這個答案為您提供了包裹區域的解決方案(一旦您修改它以使用尖括號)。
此例程將提示您使用該標記,並應使用該類型的打開/關閉標記標記該區域中的每一行:
(defun my-tag-lines (b e tag)
"'tag' every line in the region with a tag"
(interactive "r\nMTag for line: ")
(save-restriction
(narrow-to-region b e)
(save-excursion
(goto-char (point-min))
(while (< (point) (point-max))
(beginning-of-line)
(insert (format "<%s>" tag))
(end-of-line)
(insert (format "</%s>" tag))
(forward-line 1)))))
*注意:*如果您希望tag
始終為li
,則刪除標記參數,刪除文本\\nMTag for line:
從調用到interactive,並更新插入調用以僅插入"<li\\>"
as你會期待的。
對於sgml-mode
deratives,標記要標記的區域,鍵入Mx sgml-tag
,然后鍵入要使用的標記名稱(按TAB
鍵獲取可用HTML元素的列表)。 盡管如此,此方法不允許您標記區域中的每一行,您可以通過錄制鍵盤宏來解決此問題。
yasnippet是Textmate的Emacs片段語法的一個特別好的實現。 有了它,您可以導入所有Textmate的片段。 如果你安裝它,我寫的這個片段應該做你想要的:
(defun wrap-region-or-point-with-html-tag (start end)
"Wraps the selected text or the point with a tag"
(interactive "r")
(let (string)
(if mark-active
(list (setq string (buffer-substring start end))
(delete-region start end)))
(yas/expand-snippet (point)
(point)
(concat "<${1:p}>" string "$0</${1:$(replace-regexp-in-string \" .*\" \"\" text)}>"))))
(global-set-key (kbd "C-W") 'wrap-region-or-point-with-html-tag)
編輯:(好的,這是我最后一次嘗試解決這個問題。它與Textmate的版本完全相同。它甚至會在結束標記中的空格后忽略字符)
對不起,我誤解了你的問題。 此功能應編輯該區域中的每一行。
(defun wrap-lines-in-region-with-html-tag (start end)
"Wraps the selected text or the point with a tag"
(interactive "r")
(let (string)
(if mark-active
(list (setq string (buffer-substring start end))
(delete-region start end)))
(yas/expand-snippet
(replace-regexp-in-string "\\(<$1>\\).*\\'" "<${1:p}>"
(mapconcat
(lambda (line) (format "%s" line))
(mapcar
(lambda (match) (concat "<$1>" match "</${1:$(replace-regexp-in-string \" .*\" \"\" text)}>"))
(split-string string "[\r\n]")) "\n") t nil 1) (point) (point))))
Trey的答案中的這個變體也將正確地縮進html。
(defun wrap-lines-region-html (be tag) "'tag' every line in the region with a tag" (interactive "r\\nMTag for line: ") (setq p (point-marker)) (save-excursion (goto-char b) (while (< (point) p) (beginning-of-line) (indent-according-to-mode) (insert (format "<%s>" tag)) (end-of-line) (insert (format "</%s>" tag)) (forward-line 1))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.