适用于#+的宏阅读器

时间:2018-08-31 15:54:50

标签: common-lisp

我正在尝试编写Common Lisp代码的格式化程序,为此我需要调整阅读器的行为,例如使用阅读器宏进行评论。目前正在查看#+例如

$("#object").html("<div class=\"cv-block\">\n        <div id=\"parent_div_1\">\n            obiect.firstn\n            obiect.lastn\n        </div>\n\n        <div id=\"parent_div_2\">\n            obiect.date\n        </div>\n\n        obiect.message\n\n    </div>");

默认的阅读器行为是完全丢弃当前不活动的分支,但是出于我的目的,我需要保留两者。我认为这意味着我需要#+的阅读器宏。

但是#也是许多其他事物的前缀。如何编写一个处理#+的读取器宏,同时保留其他所有#的默认行为?

1 个答案:

答案 0 :(得分:0)

#字符是调度宏字符,这意味着您可以为#+组合定义阅读器宏,而不会影响以散列开头的任何其他阅读器宏。 您可以从下面的代码开始,并对其进行自定义以执行您想要的操作:

;; define the reader function
(defun custom-comment-reader-macro (stream char &optional num)
  ;; char will be #\+ in our case, and num will be nil.
  ;; stream will be the code input stream
  (declare (ignore char num))
  ;; this is the default behaviour of #+, you can customize it below
  (if (member (intern (string (read stream)) :keyword)
              *features*)
      (read stream)
      (progn (read stream)              ;ignore next token
             (values))))                ;return nothing

;; tell the reader to use our function when it encounters #+
(set-dispatch-macro-character #\# #\+ #'custom-comment-reader-macro)

相关问题