Org-Mode Inline Macro in the Buffer

In org-mode, macros can be used to expand text but are only visible when exported. However, by combining org-macro and emacs' built in font-locking system, you can expand macros inline in the buffer.

For example, here’s a macro that expands to the text returned by an elisp expression which gets today’s date. In the buffer, you don’t get to see the expanded value (though it does show up if you export it).

#+MACRO: today (eval (format-time-string "%m-%d-%Y"))

* Today's date is {{{today}}}

Adding the following to your init.el tells emacs to font-lock text in org-mode buffers when it sees triple curly braces. Using the display overrides the text shown when there is a match. Then the macro is expanded programatically the same way (for the most part) org-mode does it during export.

;; Display macros inline in buffers
(add-to-list 'font-lock-extra-managed-props 'display)

(font-lock-add-keywords
 'org-mode
 '(("\\({{{[a-zA-Z#%)(_-+0-9]+}}}\\)" 0
    `(face nil display
           ,(format "%s"
                    (let* ((input-str (match-string 0))
                          (el (with-temp-buffer
                                (insert input-str)
                                (goto-char (point-min))
                                (org-element-context)))
                          (text (org-macro-expand el org-macro-templates)))
                      (if text
                          text
                        input-str)))))))

Now you can see the macro expansion inline in the buffer.

#+MACRO: today (eval (format-time-string "%m-%d-%Y"))

* Today's date is 2022-10-29