我正在尝试编写一个elisp函数来获取文本区域,引用每一行,并在每行的末尾添加逗号,除了最后一行。
这将是一个示例转换:
这
Aaaa Bbbb CCcc
DDddd eeeee ffffffff
ggggg hhh iiii
要:
"Aaaa Bbbb CCcc",
"DDddd eeeee ffffffff",
"ggggg hhh iiii"
这是我到目前为止所做的:
(defun quote-lines (p1 p2)
(interactive "r")
(save-excursion
(while (<= (point) p2) ; Would like to check if we are on
; the line after p2
(move-beginning-of-line nil)
(insert "\"")
(move-end-of-line nil)
(insert "\",")
(forward-line))
(move-end-of-line nil)
(delete-char 1)))
任何使我的elisp功能更加惯用的帮助也会受到赞赏。
答案 0 :(得分:1)
对于惯用语不能说太多。
我现在只写任何有用的东西。
这是对您的代码的修复(您忘记了goto-char
,因此无效
如果您反向选择区域:
(defun quote-lines (p1 p2)
(interactive "r")
(deactivate-mark)
(save-excursion
(goto-char p1)
(move-beginning-of-line 1)
(while (< (point) p2)
(insert "\"")
(move-end-of-line 1)
(insert "\",")
(forward-line))
(backward-delete-char 1)))
我看到你带了一个while循环。这确实更有效率。 根据具体情况,您可以采用功能性方式。 我觉得它更漂亮,但效率更低。
(defun quote-lines-1 ()
(interactive )
(let* ((beg (if (region-active-p)
(region-beginning)
(point-min)))
(end (if (region-active-p)
(region-end)
(point-max)))
(str (buffer-substring beg end)))
(delete-region beg end)
(insert
(mapconcat (lambda (x) (format "\"%s\"" x))
(split-string str "\n")
",\n"))))
答案 1 :(得分:0)
这就是你所需要的:
(defun quote-lines (beg end)
"Put double-quotes around each line in the region. Put a comma after each line.
Quote each whole line that contains part of the region."
(interactive "r")
(setq beg (save-excursion (goto-char beg) (line-beginning-position))
end (save-excursion (goto-char end) (line-end-position)))
(let ((lines (mapconcat (lambda (line) (format "\"%s\"" line))
(split-string (buffer-substring beg end) "\n" t)
",\n")))
(delete-region beg end)
(insert lines)))
首先,该区域实际上已扩展到包括整条线。
然后将区域分成行(split-string
),引用每一行,然后加上逗号(mapconcat
)。
然后用期望的结果替换该区域。