在Emacs中编写“Hello World”的方法?

24

我想用Emacs Lisp编写几个Unix脚本,但貌似没有一种简洁的方法可以输出到标准输出,以便将结果重定向到文件或管道传输到另一个命令。 print函数会在输出字符串周围添加双引号,因此我得到的是"Hello world!"而不是Hello world!

以下是Emacs脚本:

#!/usr/bin/emacs --script
;;
;; 从Unix shell中运行我: ./hello.el > x.txt
;;
(message "Hello world!  我正在将内容写入 STDERR。")
(print "Hello world!  我正在将内容写入 STDOUT 但加上了引号")
(insert "Hello world!  我正在将内容写入 Emacs buffer")
(write-file "y.txt")

这是我希望如何调用它。

hello.el > x.txt
hello.el | wc
2个回答

25

看起来你想使用princ而不是print。 所以,基本上:

(princ "Hello world! I'm writing to STDOUT but I'm not in quotes!")

但是,需要注意的是princ不会自动用\n终止输出。


哎呀,我忘记了 princ。实际上我在几个月前在这个问题中使用过它。https://dev59.com/xUnSa4cB1Zd3GeqPQLBP - anon

7

正如David Antaramian所说,你可能想要使用princ

此外,message支持格式控制字符串(类似于C语言中的printf),它是从format适配过来的。因此,你可能最终想做类似以下的事情:

(princ (format "Hello, %s!\n" "World"))

作为一对函数加演示:
(defun fmt-stdout (&rest args)
  (princ (apply 'format args)))
(defun fmtln-stdout (&rest args)
  (princ (apply 'format
                (if (and args (stringp (car args)))
                    (cons (concat (car args) "\n") (cdr args))
                  args))))

(defun test-fmt ()
  (message "Hello, %s!" "message to stderr")
  (fmt-stdout "Hello, %s!\n" "fmt-stdout, explict newline")
  (fmtln-stdout "Hello, %s!" "fmtln-stdout, implicit newline"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接