Define a new function in elisp
using Org Element API to that returns :title
property of headline element.
For this answer, I wrote a headline-title
function that returns the :title
of the nearest headline above the SRC
block.
(defun headline-title()
(let* ((x
(save-mark-and-excursion
(org-up-heading-safe)
(org-element-property :title (org-element-at-point)))))
(if (and x (not (string-match file-name-invalid-regexp x))) (format "%s" x) "yes" ))
)
Note: The new function that you will define will need to be added to Library of Babel, your local configuration files, or as a file variable inside your org-mode file.
In this example, I've added the headline-title
function as a file variable to the org-mode file.
# Local Variables:
# eval: (defun headline-title nil (let* ((x (save-mark-and-excursion (org-up-heading-safe) (org-element-property :title (org-element-at-point))))) (if (and x (not (string-match file-name-invalid-regexp x))) (format "%s" x) "yes")))
# End:
Tip: After adding the headline-title
function as file variable, save file, close file and re-open your file in emacs. Each time you open the file, you will be prompted to enable the new file variable.
Call new function, e.g. headline-title
, with the :tangle
header
For this example, I defined a single :tangle
header for all the SRC
blocks under each headline.
* bar
:PROPERTIES:
:header-args:sh: :tangle (headline-title)
:END:
#+BEGIN_SRC sh
echo "bar"
#+END_SRC
* foo
:PROPERTIES:
:header-args:sh: :tangle (headline-title)
:END:
#+BEGIN_SRC sh
echo "foo"
#+END_SRC
For SRC
blocks defined outside of headlines, the code example returns yes
to the :tangle
header.
#+BEGIN_SRC sh :tangle (headline-title)
echo "No Headline"
#+END_SRC
Headlines with Formatting or Punctuation might be Bad Choice for File Name when Tangling
* Bad FileName?
:PROPERTIES:
:header-args:sh: :tangle (headline-title)
:END:
#+BEGIN_SRC sh
echo "Headline might be Bad File Name"
#+END_SRC
* /etc/passwd-OMG-C-g-C-g-C-x-C-c-I-just-broke-my-unix-server-using-org-mode
:PROPERTIES:
:header-args:sh: :tangle (headline-title)
:END:
#+BEGIN_SRC sh
echo "Headlines with Formatting might be Bad Choice for File Name when Tangling"
#+END_SRC
Thanks for asking your question!
This answer was tested using:
emacs: GNU Emacs 25.2.1
org-mode: Org mode version 9.1.2