Emacs - 通过正则表达式选择文本(理想情况下,只有当正则表达式匹配围绕插入符号时才选择文本

时间:2011-11-27 13:52:08

标签: emacs elisp

我需要使用regexp在Emacs中选择文本。如果我有一个选项可以匹配,只有当匹配是围绕插入符号时,这将是最好的。

示例:

text.....

<start oftext I want to select> text.....
text....
text.... <caret> text....
text....
text.... <end of text I want to select>

some other text

编辑:很抱歉,我显然没有明确说出我的问题,所以这里有一个澄清:

  • Caret被认为是当前放置光标的地方,而不是要匹配的文字文本
  • 要选择的文本的开头和结尾只是文档中没有任何空行的所有文本。

3 个答案:

答案 0 :(得分:1)

在elisp中找到一些关于点的东西并不难。只需使用前后两个搜索。

(defun set-selection-around-parens()
  (interactive)
  (let ( (right-paren (save-excursion ; using save-excursion because
                                      ; we don't want to move the
                                      ; point.
                        (re-search-forward ")" nil t))) ; bound nil
                                                        ; no-error t
         (left-paren (save-excursion (re-search-backward "(" nil t))))
  (when (and right-paren left-paren)
    ;; this is actually a way to activate a mark
    ;; you have to move your point to one side
    (push-mark right-paren)
    (goto-char left-paren)
    (activate-mark))))

当您使用主要选择来选择周围的东西时,您无法保存当前点的位置(您将其命名为插入符号)。要保存当前位置并进行一些选择,您可以使用secondary selection

(require 'second-sel)
(global-set-key [(control meta ?y)]     'secondary-dwim)
(define-key esc-map "y"                 'yank-pop-commands)
(define-key isearch-mode-map "\C-\M-y"  'isearch-yank-secondary)

(defun secondary-selection-deactivate()
  (interactive)
  (x-set-selection 'SECONDARY nil)
  (move-overlay mouse-secondary-overlay (point-min) (point-min) (current-buffer)))

(defun secondary-selection-in-this-buffer-p()
  (and (x-get-selection 'SECONDARY) (overlayp mouse-secondary-overlay) (eq (current-buffer) (overlay-buffer mouse-secondary-overlay))))

(defun set-secondary-selection-around-parens()
  (interactive)
  (let ( (right-paren (save-excursion (re-search-forward ")" nil t)))
         (left-paren (save-excursion (re-search-backward "(" nil t))))
  (when (and right-paren left-paren)
    (primary-to-secondary left-paren right-paren)
    )))

答案 1 :(得分:0)

您没有说明如何定义要选择的文本的开头和结尾。事实上,你的问题根本不清楚。如果您只想突出显示包含文字文本<carat>的所有文字,请执行以下操作:

  1. 使用 M-s h r 突出显示正则表达式。它会提示您输入正则表达式。

  2. 输入此正则表达式以匹配包含字符串<carat>的所有文字:

  3. \(.\|C-qC-j\)*<carat>\(.\|C-qC-j\)*
    

    \(.\|C-qC-j\)*<carat>\(.\|C-qC-j\)*

    (如果你的意思是克拉字符,而不是文字^,那么请用<carat>替换上面的文字。)

    C-q C-j 插入换行符。正则表达式\^匹配除换行符之外的任何字符,因此正则表达式.匹配任何字符,包括换行符。

答案 2 :(得分:0)

我知道这不会直接回答您的问题,但根据您实际选择的内容,最好使用mark-defunmark-paragraph。对于您所处的特定模式,甚至可能有类似LaTeX-mark-environment的内容。如果它是新类型文件的新模式,您可以自定义paragraph-startbeginning-of-defun或类似内容以获得所需结果。当然,如果用户输入正则表达式,这将不是一个好的选择。