0

I would like to evaluate an element in an alist, like dynamically generating an alist key for the current year:

((format-time-string "%Y") . ?y) => ("2022" . ?y)

(In my case the goal is to dynamically create a org tag for the current year in org-tag-alist, but this question is more general about alists.)

Even after reading manual entries for alists and quoting (which all alist construction examples I've found use), I am stumped how to achieve this elegantly.

4
  • emacs.stackexchange.com/tags/elisp/info
    – Drew
    Jun 26, 2022 at 22:31
  • Weird, not only did that question not show up in web searches, it did not show up in the suggested posts while creating this question. Jun 26, 2022 at 22:41
  • Marked as duplicate. Hopefully this Q&A will show up in search results when the other does not, filling the gap and saving others time, which was my goal in posting this. Jun 26, 2022 at 22:50
  • 1
    Although the answer is common, the questions that have this common answer are all over the place, which makes it hard to search for duplicates (or to provide automated suggestions). See this answer for a partial list of questions whose answer is exactly the same: use backquote.
    – NickD
    Jun 27, 2022 at 14:28

1 Answer 1

0

Backquotes allow selective element evaluation:

`(,(format-time-string "%Y") . ?y)

The , indicates an element to be evaluated, so ,(format-time-string "%Y") will evaluate to the current year (e.g., "2022") while ?y will remain unevaluted.


Example for org-tag-alist to create a tag for the current year, mapped to the y key:

(setq org-tag-alist `((,(format-time-string "%Y") . ?y)))

Using backquotes you can even splice lists into alists using ,@ notation, see doc for details.

I have used elisp for years and never encountered backquotes! Hoping this will help someone find it when web searching. Credit to this SO answer I stumbled upon while searching for a related issue.

Not the answer you're looking for? Browse other questions tagged or ask your own question.