Next: , Up: Update Old Project   [Index]


B.1.2.1 Add a Key-Value

This script replaces add-s3-bucket with more abstract code to add any key-value combo after the ‘version’ macro. It takes two values, the key and the value. It checks whether the key exists in the current Org file as ‘#+key:’. If it does, then it simply returns nil. If it does not, then it adds ‘#+key:value" after the =version’ macro.

NOTE: there is already an org procedure called org-collect-keywords that searches for and return key-value pairs; consider using it instead.

(defun add-key-value (key value)
  "Check for the existence of a key KEY; if not found, add it
with value VALUE."
  (with-current-buffer (car (find-file-noselect "*.org" nil nil t))
    (goto-char (point-min))
    (let* ((tree (project-tree (current-buffer)))
           ;; hl1 limits the search to the first headline
           (hl1 (org-element-map tree (quote headline) (lambda (hl) (org-element-property :begin hl)) nil t)))
      (message  "In add-key-value; searching for key: %s..." key)
      (if (re-search-forward (format "^#[+]%s:" key) hl1 t)
          (message "...found.")
        (progn
          (message "...key: %s not found; adding value: %s..." key value)
          (re-search-forward "^#[+]macro:version")
          (beginning-of-line 2)
          (insert (format "#+%s:%s" key value))
          (message "Added #+%s:%s at point %d" key value (line-beginning-position))
          (newline)
          (save-buffer)
          (revert-buffer t t t))))))