10

Is it possible to get property values from org file headers? For example, I have a file named something.org with following content:

#+TITLE: Awesome File
#+AUTHOR: My Name
#+XYZ: xyz

/content/

How could one get title or XYZ? I want to get those values for some buffer-local variables.

d12frosted
  • 384
  • 3
  • 11

2 Answers2

11

You could use a slight modification of the answer to another question. After trying the full stuff in some org-file you can put https://emacs.stackexchange.com/questions/21459/programmatically-read-and-set-buffer-wide-org-mode-property into your init file and just use org-global-props in your org-file.

#+TITLE: Awesome File
#+AUTHOR: My Name
#+XYZ: xyz

  /content/
  #+BEGIN_SRC emacs-lisp
;; Definition of `org-global-props' that could go into your init file:
(defun org-global-props (&optional property buffer)
  "Get the plists of global org properties of current buffer."
  (unless property (setq property "PROPERTY"))
  (with-current-buffer (or buffer (current-buffer))
    (org-element-map (org-element-parse-buffer) 'keyword (lambda (el) (when (string-match property (org-element-property :key el)) el)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Stuff for your org-file:
(mapcar (lambda (prop)
      (list (org-element-property :key prop)
        (org-element-property :value prop)))
    (org-global-props "\\(AUTHOR\\|TITLE\\|XYZ\\)"))
  #+END_SRC

  #+RESULTS:
  | TITLE  | Awesome File |
  | AUTHOR | My Name      |
  | XYZ    | xyz          |

In order to get value of first property with key you can use following function.

(defun org-global-prop-value (key)
  "Get global org property KEY of current buffer."
  (org-element-property :value (car (org-global-props key))))

For example, (org-global-prop-value "author") returns My Name. Keep in mind, that key respects case sensitivity rules for search.

Tobias
  • 33,167
  • 1
  • 37
  • 77
  • Nice, pretty almost what I wanted. Will do some modification and it would be perfect. BTW, thanks for the link. I saw that question, but didn't see that it's useful for my case as well :-P – d12frosted Apr 19 '16 at 11:04
  • But anyway, (org-element-property :value (car (org-global-props "AUTHOR"))) is fine enough. Thanks again. – d12frosted Apr 19 '16 at 11:08
  • 2
    @d12frosted Yes, ... it is more like getting you on the right track. – Tobias Apr 19 '16 at 13:26
  • @d12frosted Please post what was the perfect answer for you. You might not be the only one who it is perfect for. – grettke Feb 16 '19 at 02:28
4

org-collect-keywords will do this for you.

In your document, (org-collect-keywords '("TITLE" "XYZ")) will return (("TITLE" "Awesome File") ("XYZ" "xyz")).

amitp
  • 2,541
  • 14
  • 24