1

我正在尝试编写一个 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 函数更惯用的帮助也将不胜感激。

4

2 回答 2

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"))))
于 2013-10-26T20:27:56.807 回答
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)。

然后该区域被替换为期望的结果。

于 2013-11-28T01:53:10.497 回答