My Emacs configuration.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db-org.el 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. ;;; org.el -- Daniel's org mode configuration -*- lexical-binding: t -*-
  2. ;;; Commentary:
  3. ;; This file defines functions used in the main configuration of org-mode and
  4. ;; it’s subpackages. Nothing here changes the behavior of org-mode per se, as
  5. ;; loading this file only defines a couple of functions.
  6. ;;; Code:
  7. (require 'cl-lib)
  8. (require 'org)
  9. (require 'org-agenda)
  10. (require 'org-clock)
  11. (require 'hydra)
  12. (require 'db-customize)
  13. (require 'ox-icalendar)
  14. (autoload 'counsel-org-goto-all "counsel")
  15. (autoload 'which-function "which-func")
  16. (autoload 'org-element-property "org-element")
  17. (declare-function w32-shell-execute "w32fns.c")
  18. ;;; Agenda Customization
  19. (defun db/check-special-org-files-in-agenda (&rest args)
  20. "Check whether the special org-mode files are part of `org-agenda-files', ignoring ARGS.
  21. The special org-mode files are `db/org-default-org-file',
  22. `db/org-default-work-file', `db/org-default-home-file', and
  23. `db/org-default-refile-file'."
  24. (ignore args)
  25. (require 'org)
  26. (let ((agenda-files (mapcar #'file-truename (org-agenda-files t))))
  27. (dolist (file '(db/org-default-org-file
  28. db/org-default-home-file
  29. db/org-default-work-file
  30. db/org-default-refile-file))
  31. (when (and (symbol-value file)
  32. (not (member (file-truename (symbol-value file))
  33. agenda-files)))
  34. (warn "File %s is not part of `org-agenda-files'."
  35. file)))))
  36. (defun db/org-agenda-list-deadlines (&optional match)
  37. "Prepare agenda view that only lists upcoming deadlines.
  38. Ignores MATCH. Date is always today, no forward or backward is
  39. supported. Consequently, no date is shown. Also does not
  40. support any of the usual key bindings, e.g., showing a
  41. clockreport. It is, plainly speaking, just listing all active
  42. deadlines."
  43. (interactive "P")
  44. (catch 'exit
  45. (org-agenda-prepare "Deadlines")
  46. (org-compile-prefix-format 'agenda)
  47. (org-set-sorting-strategy 'agenda)
  48. (let* ((today (org-today))
  49. (thefiles (org-agenda-files nil 'ifmode))
  50. (inhibit-redisplay (not debug-on-error))
  51. s rtn rtnall file files date start-pos)
  52. ;; headline
  53. (unless org-agenda-compact-blocks
  54. (setq s (point))
  55. (if org-agenda-overriding-header
  56. (insert (org-add-props (copy-sequence org-agenda-overriding-header)
  57. nil 'face 'org-agenda-structure) "\n"))
  58. (org-agenda-mark-header-line s))
  59. ;; actual content
  60. (setq date (calendar-gregorian-from-absolute today)
  61. s (point)
  62. start-pos (point)
  63. files thefiles
  64. rtnall nil)
  65. (while (setq file (pop files))
  66. (catch 'nextfile
  67. (org-check-agenda-file file)
  68. (setq rtn (apply 'org-agenda-get-day-entries
  69. file date
  70. '(:deadline)))
  71. (setq rtnall (append rtnall rtn)))) ;; all entries
  72. (when rtnall
  73. (insert (org-agenda-finalize-entries rtnall 'agenda)
  74. "\n"))
  75. ;; finalize
  76. (goto-char (point-min))
  77. (or org-agenda-multi (org-agenda-fit-window-to-buffer))
  78. (unless (and (pos-visible-in-window-p (point-min))
  79. (pos-visible-in-window-p (point-max)))
  80. (goto-char (1- (point-max)))
  81. (recenter -1)
  82. (if (not (pos-visible-in-window-p (or start-pos 1)))
  83. (progn
  84. (goto-char (or start-pos 1))
  85. (recenter 1))))
  86. (goto-char (or start-pos 1))
  87. (add-text-properties
  88. (point-min) (point-max)
  89. `(org-agenda-type agenda
  90. org-redo-cmd
  91. (db/org-agenda-list-deadlines ,match)))
  92. (org-agenda-finalize)
  93. (setq buffer-read-only t)
  94. (message ""))))
  95. (defun db/org-agenda-skip-tag (tag &optional others)
  96. ;; https://stackoverflow.com/questions/10074016/org-mode-filter-on-tag-in-agenda-view
  97. "Skip all entries that correspond to TAG.
  98. If OTHERS is true, skip all entries that do not correspond to TAG."
  99. (let* ((next-headline (save-mark-and-excursion
  100. (or (outline-next-heading) (point-max))))
  101. (current-headline (or (and (org-at-heading-p)
  102. (point))
  103. (save-mark-and-excursion
  104. ;; remember to also consider invisible headings
  105. (org-back-to-heading t))))
  106. (has-tag (member tag (org-get-tags current-headline))))
  107. (if (or (and others (not has-tag))
  108. (and (not others) has-tag))
  109. next-headline
  110. nil)))
  111. ;; A Hydra for changing agenda appearance
  112. ;; http://oremacs.com/2016/04/04/hydra-doc-syntax/
  113. (defun db/org-agenda-span ()
  114. "Return the display span of the current shown agenda."
  115. (let ((args (get-text-property
  116. (min (1- (point-max)) (point))
  117. 'org-last-args)))
  118. (nth 2 args)))
  119. (defhydra hydra-org-agenda-view (:hint none)
  120. "
  121. _d_: ?d? day _g_: time grid=?g? _a_: arch-trees
  122. _w_: ?w? week _[_: inactive _A_: arch-files
  123. _t_: ?t? fortnight _F_: follow=?F? _r_: report=?r?
  124. _m_: ?m? month _e_: entry =?e? _D_: diary=?D?
  125. _y_: ?y? year _q_: quit _L__l__c_: ?l?
  126. "
  127. ("SPC" org-agenda-reset-view)
  128. ("d" org-agenda-day-view
  129. (if (eq 'day (db/org-agenda-span))
  130. "[x]" "[ ]"))
  131. ("w" org-agenda-week-view
  132. (if (eq 'week (db/org-agenda-span))
  133. "[x]" "[ ]"))
  134. ("t" org-agenda-fortnight-view
  135. (if (eq 'fortnight (db/org-agenda-span))
  136. "[x]" "[ ]"))
  137. ("m" org-agenda-month-view
  138. (if (eq 'month (db/org-agenda-span)) "[x]" "[ ]"))
  139. ("y" org-agenda-year-view
  140. (if (eq 'year (db/org-agenda-span)) "[x]" "[ ]"))
  141. ("l" org-agenda-log-mode
  142. (format "% -3S" org-agenda-show-log))
  143. ("L" (org-agenda-log-mode '(4)))
  144. ("c" (org-agenda-log-mode 'clockcheck))
  145. ("F" org-agenda-follow-mode
  146. (format "% -3S" org-agenda-follow-mode))
  147. ("a" org-agenda-archives-mode)
  148. ("A" (org-agenda-archives-mode 'files))
  149. ("r" org-agenda-clockreport-mode
  150. (format "% -3S" org-agenda-clockreport-mode))
  151. ("e" org-agenda-entry-text-mode
  152. (format "% -3S" org-agenda-entry-text-mode))
  153. ("g" org-agenda-toggle-time-grid
  154. (format "% -3S" org-agenda-use-time-grid))
  155. ("D" org-agenda-toggle-diary
  156. (format "% -3S" org-agenda-include-diary))
  157. ("!" org-agenda-toggle-deadlines)
  158. ("["
  159. (let ((org-agenda-include-inactive-timestamps t))
  160. (org-agenda-check-type t 'timeline 'agenda)
  161. (org-agenda-redo)))
  162. ("q" (message "Abort") :exit t))
  163. ;; Show sum of daily efforts in agenda, the following two functions are from
  164. ;; anpandey,
  165. ;; cf. https://emacs.stackexchange.com/questions/21380/show-sum-of-efforts-for-a-day-in-org-agenda-day-title#21902
  166. (defun db/org-agenda-calculate-efforts (limit)
  167. "Sum efforts of day entries up to LIMIT in the agenda buffer.
  168. Entries included are those scheduled for that day, scheduled at
  169. some past day (and still on display) and active timestamps (appointments)."
  170. (let (total)
  171. (save-excursion
  172. (while (< (point) limit)
  173. (when (member (org-get-at-bol 'type)
  174. '("scheduled" "past-scheduled" "timestamp"))
  175. (push (org-entry-get (org-get-at-bol 'org-hd-marker) "Effort") total))
  176. (forward-line)))
  177. (org-duration-from-minutes
  178. (cl-reduce #'+
  179. (mapcar #'org-duration-to-minutes
  180. (cl-remove-if-not 'identity total))))))
  181. (defun db/org-agenda-insert-efforts ()
  182. "Insert efforts for each day into the agenda buffer.
  183. Add this function to `org-agenda-finalize-hook' to enable this."
  184. (save-excursion
  185. (let (pos)
  186. (while (setq pos (text-property-any
  187. (point) (point-max) 'org-agenda-date-header t))
  188. (goto-char pos)
  189. (end-of-line)
  190. (insert-and-inherit
  191. (concat " ("
  192. (db/org-agenda-calculate-efforts
  193. (or (next-single-property-change (point) 'day)
  194. ;; If nothing is shown on the current day, the previous
  195. ;; call may return nil; in that case, don't sum anything
  196. ;; by setting the limit to 0
  197. 0))
  198. ")"))
  199. (forward-line)))))
  200. ;;; Capturing
  201. (defun db/org-timestamp-difference (stamp-1 stamp-2)
  202. "Returns time difference between two given org-mode timestamps."
  203. ;; Things copied from `org-clock-update-time-maybe’
  204. (let* ((s (-
  205. (float-time
  206. (apply #'encode-time (org-parse-time-string stamp-2 t)))
  207. (float-time
  208. (apply #'encode-time (org-parse-time-string stamp-1 t)))))
  209. (neg (< s 0))
  210. (s (abs s))
  211. (h (floor (/ s 3600)))
  212. (m (floor (/ (- s (* 3600 h)) 60))))
  213. (format (if neg "-%d:%02d" "%2d:%02d") h m)))
  214. ;; Capture Code Snippets
  215. ;; from http://ul.io/nb/2018/04/30/better-code-snippets-with-org-capture/
  216. (defun db/org-capture-code-snippet (filename)
  217. "Format Org mode entry for capturing code in active region in
  218. the buffer visiting FILENAME."
  219. (with-current-buffer (find-buffer-visiting filename)
  220. (let ((code-snippet (buffer-substring-no-properties (mark) (- (point) 1)))
  221. (func-name (which-function))
  222. (file-name (buffer-file-name))
  223. (line-number (line-number-at-pos (region-beginning)))
  224. (org-src-mode (let ((mm (intern (replace-regexp-in-string
  225. "-mode" "" (format "%s" major-mode)))))
  226. (or (car (rassoc mm org-src-lang-modes))
  227. (format "%s" mm)))))
  228. (format
  229. "file:%s::%s
  230. In ~%s~:
  231. #+BEGIN_SRC %s
  232. %s
  233. #+END_SRC"
  234. file-name
  235. line-number
  236. func-name
  237. org-src-mode
  238. code-snippet))))
  239. ;; Make capture frame, made for being called via emacsclient
  240. ;; https://cestlaz.github.io/posts/using-emacs-24-capture-2/
  241. (defun db/make-org-capture-frame ()
  242. "Create a new frame for capturing."
  243. (interactive)
  244. (make-frame '((name . "capture")))
  245. (select-frame-by-name "capture")
  246. (delete-other-windows)
  247. (org-capture))
  248. (defun db/delete-frame-if-capture (&rest r)
  249. "If current frame was made for a capture, close after done."
  250. (ignore r)
  251. (when (equal (frame-parameter nil 'name)
  252. "capture")
  253. (delete-frame)))
  254. (advice-add 'org-capture-finalize
  255. :after #'db/delete-frame-if-capture)
  256. ;;; Refiling
  257. (defun db/verify-refile-target ()
  258. "Verify that a certain location is eligible as a refile target.
  259. In other words, exclude tasks with a done state and those with
  260. tag PERIODIC."
  261. (and
  262. ;; Exclude DONE state tasks from refile targets (from bh)
  263. (not (member (nth 2 (org-heading-components))
  264. org-done-keywords))))
  265. ;;; Reset checklists
  266. ;; from `org-checklist’ by James TD Smith (@ ahktenzero (. mohorovi cc)),
  267. ;; version: 1.0
  268. (defun org-reset-checkbox-state-maybe ()
  269. "Reset all checkboxes in an entry if the `RESET_CHECK_BOXES' property is set"
  270. (interactive "*")
  271. (if (org-entry-get (point) "RESET_CHECK_BOXES")
  272. (org-reset-checkbox-state-subtree)))
  273. ;;; Helper Functions for Clocking
  274. (defun db/find-parent-task ()
  275. ;; http://doc.norang.ca/org-mode.html#Clocking
  276. "Return point of the nearest parent task, and NIL if no such task exists."
  277. (save-mark-and-excursion
  278. (save-restriction
  279. (widen)
  280. (let ((parent-task nil))
  281. (or (org-at-heading-p)
  282. (org-back-to-heading t))
  283. (while (and (not parent-task)
  284. (org-up-heading-safe))
  285. (let ((tags (org-get-tags nil 'local)))
  286. (unless (or (member "NOP" tags)
  287. (member "PERIODIC" tags))
  288. (setq parent-task (point)))))
  289. parent-task))))
  290. (defun db/ensure-running-clock ()
  291. "Clocks in into the parent task, if it exists, or the default task."
  292. (when (and (not org-clock-clocking-in)
  293. (not org-clock-resolving-clocks-due-to-idleness))
  294. (let ((parent-task (db/find-parent-task)))
  295. (save-mark-and-excursion
  296. (cond
  297. (parent-task
  298. ;; found parent task
  299. (org-with-point-at parent-task
  300. (org-clock-in)))
  301. ((and (markerp org-clock-default-task)
  302. (marker-buffer org-clock-default-task))
  303. ;; default task is set
  304. (org-with-point-at org-clock-default-task
  305. (org-clock-in)))
  306. (t
  307. (org-clock-in '(4))))))))
  308. (defun db/save-current-org-task-to-file ()
  309. "Format currently clocked task and write it to
  310. `db/org-clock-current-task-file'."
  311. (with-temp-file db/org-clock-current-task-file
  312. (let ((clock-buffer (marker-buffer org-clock-marker)))
  313. (if (null clock-buffer)
  314. (insert "No running clock")
  315. (insert org-clock-heading)))))
  316. (defun db/org-update-frame-title-with-current-clock ()
  317. "Set the title of all active frames to the headline of the
  318. current task."
  319. (interactive)
  320. (let ((clock-buffer (marker-buffer org-clock-marker)))
  321. (when clock-buffer
  322. (dolist (frame (frame-list))
  323. (modify-frame-parameters frame `((name . , org-clock-heading)))))))
  324. (defun db/show-current-org-task ()
  325. "Show title of currently clock in task in modeline."
  326. (interactive)
  327. (message org-clock-current-task))
  328. ;;; Fixes
  329. (defun endless/org-ispell ()
  330. "Configure `ispell-skip-region-alist' for `org-mode'."
  331. (make-local-variable 'ispell-skip-region-alist)
  332. (add-to-list 'ispell-skip-region-alist '(org-property-drawer-re))
  333. (add-to-list 'ispell-skip-region-alist '("~" "~"))
  334. (add-to-list 'ispell-skip-region-alist '("=" "="))
  335. (add-to-list 'ispell-skip-region-alist '("^#\\+BEGIN_SRC" . "^#\\+END_SRC")))
  336. ;;; Hydra
  337. (defun db/clock-in-task-by-id (task-id)
  338. "Clock in org mode task as given by TASK-ID."
  339. (let ((location (org-id-find task-id 'marker)))
  340. (if (null location)
  341. (user-error "Invalid location «%s» given." task-id)
  342. (org-with-point-at location
  343. (org-clock-in))
  344. (org-save-all-org-buffers))))
  345. (defun db/clock-out-task-by-id (task-id)
  346. "Clock out org mode task as given by TASK-ID."
  347. (org-with-point-at (org-id-find task-id 'marker)
  348. (org-clock-out))
  349. (org-save-all-org-buffers))
  350. (defun db/org-clock-out ()
  351. "Clock out current clock."
  352. (interactive)
  353. (org-clock-out))
  354. (defun db/org-clock-in-break-task ()
  355. "Clock into default break task as given by `org-break-task-id’."
  356. (interactive)
  357. (db/clock-in-task-by-id org-break-task-id))
  358. (defun db/org-clock-in-home-task ()
  359. "Clock into default home task as given by `org-home-task-id’."
  360. (interactive)
  361. (db/clock-in-task-by-id org-home-task-id))
  362. (defun db/org-clock-in-work-task ()
  363. "Clock into default work task as given by `org-work-task-id’."
  364. (interactive)
  365. (db/clock-in-task-by-id org-working-task-id))
  366. (defun db/org-clock-in-last-task (&optional arg)
  367. ;; from doc.norang.ca, originally bh/clock-in-last-task
  368. "Clock in the interrupted task if there is one.
  369. Skip the default task and get the next one. If ARG is given,
  370. forces clocking in of the default task."
  371. (interactive "p")
  372. (let ((clock-in-to-task
  373. (cond
  374. ((eq arg 4) org-clock-default-task)
  375. ((and (org-clock-is-active)
  376. (equal org-clock-default-task (cadr org-clock-history)))
  377. (caddr org-clock-history))
  378. ((org-clock-is-active) (cadr org-clock-history))
  379. ((equal org-clock-default-task (car org-clock-history))
  380. (cadr org-clock-history))
  381. (t (car org-clock-history)))))
  382. (widen)
  383. (org-with-point-at clock-in-to-task
  384. (org-clock-in nil))))
  385. (defhydra hydra-org-clock (:color blue)
  386. ;; Quote %, as otherwise they would be misinterpreted as format characters
  387. "\nCurrent Task: %s(replace-regexp-in-string \"%\" \"%%\" org-clock-current-task); "
  388. ("w" (db/org-clock-in-work-task) "work")
  389. ("h" (db/org-clock-in-home-task) "home")
  390. ("b" (db/org-clock-in-break-task) "break")
  391. ("i" (lambda ()
  392. (interactive)
  393. (org-clock-in '(4))) "interactive")
  394. ("a" counsel-org-goto-all "goto")
  395. ("o" org-clock-out "clock out")
  396. ("l" db/org-clock-in-last-task "last")
  397. ("d" (lambda ()
  398. (interactive)
  399. (when (org-clock-is-active)
  400. (save-window-excursion
  401. (org-clock-goto)
  402. (let ((org-inhibit-logging 'note))
  403. (org-todo 'done)
  404. (org-save-all-org-buffers)))))
  405. "default"))
  406. ;;; Babel
  407. (defun org-babel-execute:hy (body params)
  408. ;; http://kitchingroup.cheme.cmu.edu/blog/2016/03/30/OMG-A-Lisp-that-runs-python/
  409. "Execute hy code BODY with parameters PARAMS."
  410. (ignore params)
  411. (let* ((temporary-file-directory ".")
  412. (tempfile (make-temp-file "hy-")))
  413. (with-temp-file tempfile
  414. (insert body))
  415. (unwind-protect
  416. (shell-command-to-string
  417. (format "hy %s" tempfile))
  418. (delete-file tempfile))))
  419. ;;; Custom link handlers
  420. (defun db/org-onenote-open (path)
  421. "Visit OneNote document on PATH."
  422. (unless (file-executable-p db/path-to-onenote)
  423. (user-error "Path for OneNote is not executable, please customize `db/path-to-onenote’."))
  424. (start-process "OneNote" nil db/path-to-onenote "/hyperlink" path))
  425. (defun db/org-outlook-open (id)
  426. "Open the Outlook item identified by ID.
  427. ID should be an Outlook GUID."
  428. (unless (file-executable-p db/path-to-outlook)
  429. (user-error "Path for Outlook is not executable, please customize `db/path-to-outlook’."))
  430. (w32-shell-execute "open" db/path-to-outlook (concat "/select outlook:" id)))
  431. (defun db/org-rfc-open (number)
  432. "Open browser to show RFC of given NUMBER.
  433. If `db/rfc-cache-path' is defined, download the RFC in txt format
  434. there and open it. If the RFC has already been downloaded
  435. before, just open it. If `db/rfc-cache-path' is not defined,
  436. open RFC in HTML format in the default browser."
  437. (cond
  438. ((not (string-match "[1-9][0-9]*" number))
  439. (user-error "Not a valid number for an RFC: %s" number))
  440. ((and db/rfc-cache-path
  441. (file-name-absolute-p db/rfc-cache-path)
  442. (file-writable-p db/rfc-cache-path))
  443. (let ((rfc-path (expand-file-name (format "rfc%s.txt" number)
  444. db/rfc-cache-path)))
  445. (cond
  446. ((file-exists-p rfc-path)
  447. (find-file rfc-path))
  448. (t
  449. (with-temp-buffer
  450. (url-insert-file-contents (format "https://tools.ietf.org/rfc/rfc%s.txt"
  451. number))
  452. (write-file rfc-path))
  453. (find-file rfc-path)))))
  454. (t
  455. (warn "`db/rfc-cache-path' not defined or not an absolute writable path, opening RFC in browser.")
  456. (browse-url (concat "https://tools.ietf.org/html/rfc" number)))))
  457. ;;; Org Utilities
  458. (defun db/org-cleanup-continuous-clocks ()
  459. "Join continuous clock lines in the current buffer."
  460. (interactive)
  461. (let* ((inactive-timestamp (org-re-timestamp 'inactive))
  462. (clock-line (concat "\\(^ *\\)CLOCK: " inactive-timestamp "--" inactive-timestamp " => .*"
  463. "\n"
  464. " *CLOCK: " inactive-timestamp "--\\[\\2\\] => .*$")))
  465. (save-excursion
  466. (goto-char (point-min))
  467. (while (search-forward-regexp clock-line nil t)
  468. (replace-match "\\1CLOCK: [\\4]--[\\3]")
  469. (org-clock-update-time-maybe)))))
  470. (defun db/find-csv-in-org (arg)
  471. "Interactively CSV find file and open it as Org mode table.
  472. Default separator is \";\", but this can be changed interactively
  473. by passing a universal argument."
  474. (interactive "P")
  475. (let ((separator (if arg (read-from-minibuffer "Separator (regular expression): ")
  476. ";")))
  477. (call-interactively #'find-file)
  478. (org-mode)
  479. (org-table-convert-region (point-min) (point-max) separator)))
  480. (defun db/org-mark-current-default-task ()
  481. "Mark current task as default when equal to work task or home task.
  482. Work task and home task are determined by the current values of
  483. `org-working-task-id’ and `org-home-task-id’, respectively."
  484. (let ((current-id (org-id-get org-clock-marker)))
  485. (when (member current-id (list org-working-task-id
  486. org-home-task-id))
  487. (org-clock-mark-default-task))))
  488. (defun db/org-copy-template-for-periodic-task ()
  489. "Copy template of the enclosing periodic task to item at point.
  490. The template must be placed into an item titled 'Template',
  491. called the template item. The template item must be the first
  492. headline of the periodic task, i.e., of the parent of the current
  493. item at point. The body of the template item, without any
  494. drawers, will be copied to point."
  495. (interactive)
  496. (let ((template (save-restriction
  497. (save-mark-and-excursion
  498. (let ((template-element (progn
  499. (outline-up-heading 1 'invisible-ok)
  500. (outline-next-heading)
  501. (org-element-at-point))))
  502. (unless (string-equal (org-element-property :title template-element)
  503. "Template")
  504. (user-error "Template must be first headline in periodic task."))
  505. ;; Starting from the end of the last element in the
  506. ;; subtree, we go up until we find a drawer or a
  507. ;; headline; everything in between is considered to be the template
  508. (let ((content-end (org-element-property :contents-end template-element))
  509. content-begin current-element)
  510. (goto-char content-end)
  511. (while (progn
  512. (setq current-element (org-element-at-point))
  513. (not (memq (org-element-type current-element)
  514. '(drawer property-drawer headline))))
  515. (setq content-begin (org-element-property :begin current-element))
  516. (goto-char (1- content-begin)))
  517. (string-trim-right
  518. (buffer-substring-no-properties content-begin content-end))))))))
  519. (insert template)
  520. (org-update-statistics-cookies nil)))
  521. ;;; Calendar
  522. (defun db/export-diary ()
  523. "Export diary.org as ics file to the current value of `org-icalendar-combined-agenda-file’.
  524. This is done only if the value of this variable is not null."
  525. (interactive)
  526. (cond
  527. ((null org-icalendar-combined-agenda-file)
  528. (message "`org-icalendar-combined-agenda-file’ not set, not exporting diary."))
  529. ((not (file-name-absolute-p org-icalendar-combined-agenda-file))
  530. (user-error "`org-icalendar-combined-agenda-file’ not an absolute path, aborting."))
  531. (t
  532. (progn
  533. (org-save-all-org-buffers)
  534. (let ((org-agenda-files (cl-remove-if #'null
  535. (list db/org-default-org-file
  536. db/org-default-home-file
  537. db/org-default-work-file)))
  538. (org-agenda-new-buffers nil))
  539. ;; check whether we need to do something
  540. (when (cl-some (lambda (org-file)
  541. (file-newer-than-file-p org-file
  542. org-icalendar-combined-agenda-file))
  543. org-agenda-files)
  544. (message "Exporting diary ...")
  545. ;; open files manually to avoid polluting `org-agenda-new-buffers’; we
  546. ;; don’t want these buffers to be closed after exporting
  547. (mapc #'find-file-noselect org-agenda-files)
  548. ;; actual export; calls `org-release-buffers’ and may thus close
  549. ;; buffers we want to keep around … which is why we set
  550. ;; `org-agenda-new-buffers’ to nil
  551. (when (file-exists-p org-icalendar-combined-agenda-file)
  552. (delete-file org-icalendar-combined-agenda-file)
  553. (sit-for 3))
  554. (org-icalendar-combine-agenda-files)
  555. (message "Exporting diary ... done.")))))))
  556. ;;; Find items by link to current headline
  557. (defun db/org-find-items-linking-by-id (id custom-id)
  558. "List all Org Mode items that link to ID.
  559. Uses `org-search-view' to conduct the actual search. ID must be
  560. a UUID as generated by, e.g., `org-id-get-create', and CUSTOM-ID
  561. must consist of ASCII letters, numbers, and hyphens only. Each
  562. of ID and CUSTOM-ID may be nil, but at least one of them must be
  563. not."
  564. (unless (or (not id)
  565. (and (stringp id)
  566. (string-match-p "^[a-f0-9]\\{8\\}-[a-f0-9]\\{4\\}-[a-f0-9]\\{4\\}-[a-f0-9]\\{4\\}-[a-f0-9]\\{12\\}$" id)))
  567. (user-error "Given ID is not a valid UUID: %s" id))
  568. (unless (or (not custom-id)
  569. (and (stringp custom-id)
  570. (string-match-p "[-a-zA-Z0-9]" custom-id)))
  571. ;; sorry, only ASCII right now …
  572. (user-error "CUSTOM_ID must consist of alphanumeric charaters only"))
  573. (let ((query (cond
  574. ((and id custom-id) (format "{\\[\\[id:%s\\]\\|\\[\\[file:[^]]*::#%s\\]\\|\\[#%s\\]}"
  575. id custom-id custom-id))
  576. (id (format "[[id:%s]" id))
  577. (custom-id (format "{\\[file:[^]]*::#%s\\]\\|\\[#%s\\]}"
  578. custom-id custom-id))
  579. (t (user-error "Neither ID nor CUSTOM_ID given")))))
  580. (org-search-view nil query)))
  581. (defun db/org--get-location (&optional arg)
  582. "Interactively query for location and return mark.
  583. Searches through the current file, and through all of
  584. `org-agenda-files', `org-agenda-text-search-extra-files', and the
  585. current buffer, if ARG is non-nil. Search is always conducted up
  586. to level 9. If the selected location does not have an associated
  587. mark, error out."
  588. (let* ((org-refile-targets (if arg
  589. `((org-agenda-files :maxlevel . 9)
  590. (,(cl-remove-if-not
  591. #'stringp org-agenda-text-search-extra-files)
  592. :maxlevel . 9)
  593. (nil :maxlevel . 9))
  594. '((nil :maxlevel . 9))))
  595. (mrk (nth 3 (org-refile-get-location
  596. nil
  597. ;; if the current buffer is associated with a file, search
  598. ;; through it; otherwise, use the default Org Mode file as
  599. ;; default buffer
  600. (if (buffer-file-name)
  601. nil
  602. (get-file-buffer db/org-default-org-file))))))
  603. (if mrk mrk (user-error "Invalid location"))))
  604. (defun db/org-find-links-to-current-item (arg)
  605. "Find links to current item.
  606. Only links using the ID or CUSTOM_ID property are considered.
  607. If ARG is given, or if not in an Org Mode buffer, interactively
  608. prompt for an item."
  609. (interactive "P")
  610. (apply #'db/org-find-items-linking-by-id
  611. (if (and (derived-mode-p 'org-mode) (not arg))
  612. (list (org-id-get) (org-entry-get nil "CUSTOM_ID"))
  613. (org-with-point-at (db/org--get-location)
  614. (list (org-id-get) (org-entry-get nil "CUSTOM_ID"))))))
  615. (defun db/org-add-link-to-other-item (arg)
  616. "Interactively query for item and add link to it at point.
  617. Search through all items of the current buffer, or
  618. `db/org-default-org-file' if the current buffer is not associated
  619. with a file. If ARG is non-nil, include all files in
  620. `org-agenda-files' and `org-agenda-text-search-extra-files' in
  621. this search.
  622. Use `org-store-link' to save link to `org-stored-links'."
  623. (interactive "P")
  624. (unless (derived-mode-p 'org-mode)
  625. (user-error "Not in Org Mode"))
  626. (let ((pom (db/org--get-location arg)))
  627. (save-mark-and-excursion
  628. (org-with-point-at pom
  629. (org-store-link nil t))
  630. (insert (apply #'format "[[%s][%s]]" (cl-first org-stored-links))))))
  631. ;;; End
  632. (provide 'db-org)
  633. ;;; db-org.el ends here