Emacs:将单独行上的项目转换为逗号分隔的列表

Emacs:将单独行上的项目转换为逗号分隔的列表,emacs,Emacs,我经常将由换行符或换行符分隔的项目粘贴到Emacs缓冲区中,导致每个项目位于不同的行上,如下所示: one two three four "one", "two", "three", "four" 通常我想要一个逗号分隔值列表,如下所示: one two three four "one", "two", "three", "four" 它将是伟大的,能够做一个触摸式转换从行到列表。我想我可以使用正则表达式来转换它,但它似乎是一种常用的操作,可能已经有了内置的Emacs函数。有人能推荐吗?

我经常将由换行符或换行符分隔的项目粘贴到Emacs缓冲区中,导致每个项目位于不同的行上,如下所示:

one
two
three
four
"one", "two", "three", "four"
通常我想要一个逗号分隔值列表,如下所示:

one
two
three
four
"one", "two", "three", "four"
它将是伟大的,能够做一个触摸式转换从行到列表。我想我可以使用正则表达式来转换它,但它似乎是一种常用的操作,可能已经有了内置的Emacs函数。有人能推荐吗?

M-q会用空格代替换行符(在相当短的单词列表中),但不会添加引号和逗号。或者,可能M-^多次,直到它们都在同一条线上。除此之外,没有任何内置的东西出现在脑海中

显然,键盘宏是一个很好的选择

但是,一种不会产生很多撤销步骤的更快的方法是:

(defun lines-to-cslist (start end &optional arg)
  (interactive "r\nP")
  (let ((insertion
         (mapconcat 
          (lambda (x) (format "\"%s\"" x))
          (split-string (buffer-substring start end)) ", ")))
    (delete-region start end)
    (insert insertion)
    (when arg (forward-char (length insertion)))))
编辑:我确实看到您正在寻找一个函数。。。但是,由于唯一的答案是编写自己的函数(即不存在内置函数),我想我会加入regex的内容,因为其他人可能会无意中发现这一点,并希望有一种替代方法来编写函数并将其放入
.emacs


这是两个步骤,但只是因为您希望引用文本:

正如在Emacs
*scratch*
缓冲区中粘贴的那样(添加了
five-six
,以显示它在每行多个字的情况下工作,如果感兴趣的话):

首先,将单个的
word
替换为
“word”

M-x replace regexp RET\(.*)RET“\1”RET
产生:

"one"
"two"
"three"
"four"
"five six"
"one", "two", "three", "four", "five six"
现在,将每个回车(在Emacs中,
C-q C-j
)替换为

M-x replace regexp RET C-q C-j RET,RET
产生:

"one"
"two"
"three"
"four"
"five six"
"one", "two", "three", "four", "five six"

我今天在工作中为此写了一个解决方案。下面是使用用户指定的分隔符从行转换为csv,从csv转换为行的函数。此功能在当前高亮显示的区域上运行

(defun lines-to-csv (separator)
  "Converts the current region lines to a single line, CSV value, separated by the provided separator string."
  (interactive "sEnter separator character: ")
  (setq current-region-string (buffer-substring-no-properties (region-beginning) (region-end)))
  (insert
   (mapconcat 'identity
              (split-string current-region-string "\n")
              separator)))

(defun csv-to-lines (separator)
  "Converts the current region line, as a csv string, to a set of independent lines, splitting the string based on the provided separator."
  (interactive "sEnter separator character: ")
  (setq current-region-string (buffer-substring-no-properties (region-beginning) (region-end)))
  (insert
   (mapconcat 'identity
              (split-string current-region-string separator)
              "\n")))

要使用此选项,请高亮显示要编辑的区域,然后执行M-x并指定要使用的分隔符。

我通常使用宏来完成这类任务
M-X kmacro开始宏
M-X kmacro结束或调用宏
,然后可以重复执行

光标应该恰好位于列表中最后一行之后,此函数才能按预期工作,但如果您刚刚将某个内容粘贴到缓冲区中,则光标可能自然位于该位置。这对我有用-谢谢。编辑:顺便说一句,这就是我为什么喜欢Emacs@SlowLearner我已将其更改为使用通用参数作为插入后跳转到该位置的指令,因此如果将其称为cslist的M-x lines,则该点将移动到插入字符串的末尾。