扩展emacs之一:计算buffer选中区域的字符串长度

Posted csfreebird

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了扩展emacs之一:计算buffer选中区域的字符串长度相关的知识,希望对你有一定的参考价值。

这是一个简单的场景,目的是将其他语言编写的程序集成到emacs里面,而不是打开emacs shell,执行这个脚本。

假设有一个文件,里面存放的是文本,用emacs打开,

然后选择一段文本

现在运行一个自定义命令M-x get-length

get-length会运行预先准备好的newlisp脚本,来统计被选中的文本的长度,输出到一个新的 buffer,并显示该buffer.


现在准备一个文本文件: input.txt,里面有一堆字符串

maaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddmaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddmaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddmaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddmaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddmaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

编写一个elisp文件region.el

(defun region-length (startPos endPos)
  "Do some text processing on region. This command calls the external script “wc”."
  (interactive "r")
  (let (cmdStr)
    (setq cmdStr "/your/path/length.lsp") ; full path to your script
    (shell-command-on-region startPos endPos cmdStr nil nil nil t)
    (switch-to-buffer-other-window "*Shell Command Output*")
    )
  )

说明:

shell-command-on-region的第4个参数nil表示会打开*Shell Command Output* buffer.

newlisp脚本lenght.lsp输出的结果到stdout,会写入到这个buffer中. newlisp脚本需要设置绝对路径


现在看一下length.lsp

#!/usr/bin/newlisp

(while (read-line)  
  (setf str (current-line))
  (println (length str))
  )
(exit)

现在测试一下:

M-x load-file 加载region.el

然后打开input.txt buffer,选中几个字符

M-x region-length


结果会打开一个buffer,显示长度。






以上是关于扩展emacs之一:计算buffer选中区域的字符串长度的主要内容,如果未能解决你的问题,请参考以下文章

设置 Emacs 默认字体 par-buffer/mode

[daily] emacs显示file name buffer的全路径

emacs 如何让buffer变的可交互 让buffer操作shell

2020-03-01emacs 中使用LISP

excel统计一个区域里共有多少个数

Emacs 光标控制