繁体   English   中英

像TextMate一样打开/关闭标签中的换行选择?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM