如何在Emacs或Vim中分配字符串

6
在Emacs或Vim中,如何像这个例子一样顺畅地连接字符串:
Transform from:
    (alpha, beta, gamma) blah (123, 456, 789)
To:
    (alpha=123, beta=456, gamma=789)
它需要扩展到:
  • 许多这样的行
  • 括号内有许多元素
我最近经常需要这种转换。
我在Emacs中使用Evil,因此Vim的答案也可能会有所帮助。
更新:
解决方案不如我希望的那么通用。例如,当我有一个字符串列表并希望将它们分配到一个大型XML文档中时,我希望该解决方案也能适用。例如:
<item foo="" bar="barval1"/>
<item foo="" bar="barval2"/>
<item foo="" bar="barval3"/>
<item foo="" bar="barval4"/>

fooval1
fooval2
fooval3
fooval4

我已经制定了一个解决方案,并将其作为答案添加。

1
“blah” 是固定文本还是随机文本? - Kent
6个回答

2
%s/(\(\S\{-}\), \(\S\{-}\), \(\S\{-}\)).\{-}(\(\S\{-}\), \(\S\{-}\), \(\S\{-}\))/(\1=\4, \2=\5, \3=\6)

%s:全局搜索和替换

\(\S{-}\),:非贪婪搜索,查找到下一个逗号之前的非空格字符,用括号括起来进行反向引用。

\1=\4:输出第一个匹配项,一个“=”号,然后是第四个匹配项。


哇,这很不错!但是它能处理超过三个元素的列表吗? - Prince Goulash
返回翻译后的文本:不,但它可以扩展以实现这一点。我不确定是否有一种编写动态正则表达式来处理变量等内容的方法...我想这就是sed和awk发挥作用的地方。 - ash

2
针对这种文本转换,我会使用awk:
这个一行命令可能会有所帮助:
awk -F'\\(|\\)' '{split($2,t,",");split($4,v,",");printf "( "; for(x in t)s=s""sprintf("%s=%s, ", t[x],v[x]);sub(", $","",s);printf s")\n";s=""}' file

小测试:

kent$  cat test
(alpha, beta, gamma) blah (123, 456, 789)
(a, b, c) foo (1, 2, 3)
(x, y, z, m, n) bar (100, 200, 300, 400, 500)

kent$  awk -F'\\(|\\)' '{split($2,t,",");split($4,v,",");printf "( "; for(x in t)s=s""sprintf("%s=%s, ", t[x],v[x]);sub(", $","",s);printf s")\n";s=""}' test

( alpha=123,  beta= 456,  gamma= 789)
( a=1,  b= 2,  c= 3)
(  m= 400,  n= 500, x=100,  y= 200,  z= 300)

1
这里是一个 Vimscript 解决方案。它远不如 ash 的答案优雅,但它适用于任何长度的列表。
function! ListMerge()
    " Get line, remove text between lists, split lists at parentheses:
    let curline = getline('.')
    let curline = substitute(curline,')\zs.*\ze(','','g')
    let curline = substitute(curline,'(','','g')
    let lists = map(split(curline,')'),'split(v:val,",")')
    " Return if we don't have two lists of equal length:
    if len(lists) != 2 || len(lists[0]) != len(lists[1])
        return
    endif
    " Loop over the lists, remove whitespace, build the replacement string:
    let i=0
    let string = '('
    while i<len(lists[0])
        let string .= substitute(lists[0][i],'^ *','','')
        let string .= '='
        let string .= substitute(lists[1][i],'^ *','','')
        let string .= ', '
        let i+=1
    endwhile
    " Add the concluding bracket:
    let string = substitute(string,', $',')','')
    " Replace the current line with the string:
    execute "normal! S" . string
endfunction

然后您可以像这样在所有行上调用此函数:

:%call ListMerge()

1

Prince Goulash答案的Emacs Lisp版本

(require 'cl)

(defun split-and-trim (str separator)
  (let ((strs (split-string str separator)))
    (mapcar (lambda (s)
              (replace-regexp-in-string "^\\s-+" "" s))
            (mapcar (lambda (s)
                      (replace-regexp-in-string "\\s-$" "" s)) strs))))

(defun my/merge-list (beg end)
  (interactive "r")
  (goto-char beg)
  (let ((endmark (set-mark end))
        (regexp "(\\([^)]+\\))[^(]+(\\([^)]+\\))"))
    (while (re-search-forward regexp end t)
      (let ((replace-start (match-beginning 0))
            (replace-end   (match-end 0))
            (keys-str (match-string-no-properties 1))
            (values-str (match-string-no-properties 2)))
        (let* ((keys (split-and-trim keys-str ","))
               (values (split-and-trim values-str ",")))
          (while (> (length keys) (length values))
            (setq values (append values '(""))))
          (let* ((pairs (mapcar* (lambda (k v)
                                   (format "%s=%s" k v)) keys values))
                 (transformed (format "(%s)" (mapconcat #'identity pairs ", "))))
            (goto-char replace-start)
            (delete-region replace-start replace-end)
            (insert transformed)))))
    (goto-char (marker-position endmark))))

例如,您选择以下地区:
(alpha, beta, gamma)  blah (123, 456, 789)
(alpha, beta, gamma, delta)  blah (123, 456, 789, aaa)

在执行M-x my/merge-list之后

(alpha=123, beta=456, gamma=789)
(alpha=123, beta=456, gamma=789, delta=aaa)

1

我要描述的这种方法有点古怪,但它包含了我能够处理的最少量的Elisp代码。只有当要连接的列表在去除其中的逗号后可以被解释为Lisp列表时,它才适用。数字和字母字符序列(如您的示例)都可以。

首先,请确保已加载Common Lisp库:M-:(require 'cl)RET

现在,从第一个列表的开头开始:

M-C-k ; kill-forward-sexp

C-e ; move-end-of-line

M-C-b ; backward-sexp

M-C-k ; kill-forward-sexp

C-a ; move-beginning-of-line

C-k ; kill-line

现在blah(或其他任何内容)是剪贴板中的第一条目,第二个列表是第二个条目,第一个列表是第三个条目。

输入(,然后按下M-:eval-expression),深呼吸,然后输入以下内容:

(loop with (a b) = (mapcar (lambda (x) (car (read-from-string (remove ?, x))))
                     (subseq kill-ring 1 3))
   for x in a for y in b do (insert (format "%s=%s, " y x)))

最后输入DELDEL),完成!如果需要的话,您可以将其转换为宏。


0
我的方法是创建一个命令来设置匹配列表,然后使用replace-regexp作为第二个命令来分发匹配列表,利用replace-regexp现有的\功能。
评估Elisp,例如在.emacs文件中:
(defvar match-list nil
  "A list of matches, as set through the set-match-list and consumed by the cycle-match-list function. ")
(defvar match-list-iter nil
  "Iterator through the global match-list variable. ")
(defun reset-match-list-iter ()
  "Set match-list-iter to the beginning of match-list and return it. "
  (interactive)
  (setq match-list-iter match-list))
(defun make-match-list (match-regexp use-regexp beg end)
  "Set the match-list variable as described in the documentation for set-match-list. "
  ;; Starts at the beginning of region, searches forward and builds match-list.
  ;; For efficiency, matches are appended to the front of match-list and then reversed
  ;; at the end.
  ;;
  ;; Note that the behavior of re-search-backward is such that the same match-list
  ;; is not created by starting at the end of the region and searching backward.
  (let ((match-list nil))
    (save-excursion
      (goto-char beg)
      (while
          (let ((old-pos (point)) (new-pos (re-search-forward match-regexp end t)))
            (when (equal old-pos new-pos)
              (error "re-search-forward makes no progress.  old-pos=%s new-pos=%s end=%s match-regexp=%s"
                     old-pos new-pos end match-regexp))
            new-pos)
        (setq match-list
              (cons (replace-regexp-in-string match-regexp
                                              use-regexp
                                              (match-string 0)
                                              t)
                    match-list)))
      (setq match-list (nreverse match-list)))))
(defun set-match-list (match-regexp use-regexp beg end)
  "Set the match-list global variable to a list of regexp matches.  MATCH-REGEXP
is used to find matches in the region from BEG to END, and USE-REGEXP is the
regexp to place in the match-list variable.

For example, if the region contains the text: {alpha,beta,gamma}
and MATCH-REGEXP is: \\([a-z]+\\),
and USE-REGEXP is: \\1
then match-list will become the list of strings: (\"alpha\" \"beta\")"
  (interactive "sMatch regexp: \nsPlace in match-list: \nr")
  (setq match-list (make-match-list match-regexp use-regexp beg end))
  (reset-match-list-iter))
(defun cycle-match-list (&optional after-end-string)
  "Return the next element of match-list.

If AFTER-END-STRING is nil, cycle back to the beginning of match-list.
Else return AFTER-END-STRING once the end of match-list is reached."
  (let ((ret-elm (car match-list-iter)))
    (unless ret-elm
      (if after-end-string
          (setq ret-elm after-end-string)
        (reset-match-list-iter)
        (setq ret-elm (car match-list-iter))))
    (setq match-list-iter (cdr match-list-iter))
    ret-elm))
(defadvice replace-regexp (before my-advice-replace-regexp activate)
  "Advise replace-regexp to support match-list functionality. "
  (reset-match-list-iter))

然后解决原始问题:

M-x set-match-list
Match regexp: \([0-9]+\)[,)]
Place in match-list: \1

M-x replace-regexp
Replace regexp: \([a-z]+\)\([,)]\)
Replace regexp with: \1=\,(cycle-match-list)\2

针对这个 XML 示例的解决方案是:

[Select fooval strings.]
M-x set-match-list
Match regexp: .+
Place in match-list: \&

[Select XML tags.]
M-x replace-regexp
Replace regexp: foo=""
Replace regexp with: foo="\,(cycle-match-list)"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接