elisp宏写一个函数? [英] elisp macro to write a function?

查看:106
本文介绍了elisp宏写一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些几乎相同的函数,除了它们的名字。例如:

I have written a few nearly identical functions, except for their names. For example:

; x is name, such as function/paragraph/line/etc.
(defun my-x-function
 (interactive)
 (mark-x) (do-more-stuff) (modify-x))

是否可以自动生成此类函数?我感觉这就是宏的作用,但是我不确定如何使用它们。

Is there a way to automatically generate such functions? I have a feeling this is what macros do, but I am not sure how to use them. Any help, maybe including a small example would be great.

谢谢!

推荐答案

是的,这正是宏所做的。这是一个简单的宏,可以根据您指定的模式构建函数:

Yep, that's exactly what macros do. Here's a straightforward macro that builds functions according to the pattern you specified:

(defmacro make-my-function (name)
  (list 'defun (intern (format "my-%s-function" name)) ()
        (list 'interactive)
        (list (intern (format "mark-%s" name)))
        (list 'do-more-stuff)
        (list (intern (format "modify-%s" name)))))

您可以将此宏复制到Emacs中的 * scratch * 缓冲区并进行评估,然后检查它的工作原理是这样的:

You can copy this macro to a *scratch* buffer in Emacs and evaluate it, and then check that it works like this:

(make-my-function x) ; type control-J here
my-x-function ; <-- Emacs's output
(symbol-function 'my-x-function) ; type control-J here
(lambda nil (interactive) (mark-x) (do-more-stuff) (modify-x)) ; <-- Emacs's output

更常见的是使用 backquote 工具可以更简洁地编写宏,但是所有宏在本质上都与上述相同例如。

More commonly one would use the backquote facility to write macros more concisely, but all macros essentially work in the same manner as the above example.

这篇关于elisp宏写一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆