解析缓冲区以存储其内容并重用它的正确方法是什么?
假设我得到了这个缓冲区:
always|five|words|by|line
not|always|the|same|words
sometimes|no|lines|at|all
but|only|five|no|more/less
从行中找到的符号构建列表的最佳方法是什么(如果没有找到则错误很好)?
缓冲区在那里,我可以访问它,像这样获取它的内容
(message "Buffer content : %s" (buffer-substring (point-min) (point-max)))
在我干净地杀死它之后,但不知何故我无法构建允许我这样做的对象(列表“单词”的列表“行”):
(list-length lines)
==> 4
(car (nthcdr 3 lines))
==> sometimes
一个志同道合的灵魂能指引我走向光明吗?感谢您的耐心等待,Lisp 长老。
最佳答案
您也可以使用内置的 split-string
功能,类似split
在 Perl 和其他语言中:
(defun buffer-to-list-of-lists (buf)
(with-current-buffer buf
(save-excursion
(goto-char (point-min))
(let ((lines '()))
(while (not (eobp))
(push (split-string
(buffer-substring (point) (point-at-eol)) "|")
lines)
(beginning-of-line 2))
(nreverse lines)))))
然后在名为
temp
的缓冲区中使用您的示例文本, (buffer-to-list-of-lists "temp")
返回值(("always" "five" "words" "by" "line")
("not" "always" "the" "same" "words")
("sometimes" "no" "lines" "at" "all")
("but" "only" "five" "no" "more/less"))
这将适用于任意数量的行
|
-separated words,这可能对您的应用程序更好,也可能没有。更改 buffer-substring
至 buffer-substring-no-properties
如果您不希望列表中的字符串包含原始缓冲区中的字体信息和其他属性。一旦您按照自己的意愿工作,您还需要更改示例用法
(list-length '(lines))
至 (list-length lines)
.在其当前形式中,您要求获得仅包含符号 lines
的常量单元素列表的长度。 .
关于emacs - 如何正确解析elisp中的缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9872009/