org-capture.el 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906
  1. ;;; org-capture.el --- Fast note taking in Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2010-2018 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains an alternative implementation of the functionality
  23. ;; that used to be provided by org-remember.el. The implementation is more
  24. ;; streamlined, can produce more target types (e.g. plain list items or
  25. ;; table lines). Also, it does not use a temporary buffer for editing
  26. ;; the captured entry - instead it uses an indirect buffer that visits
  27. ;; the new entry already in the target buffer (this was an idea by Samuel
  28. ;; Wales). John Wiegley's excellent `remember.el' is not needed anymore
  29. ;; for this implementation, even though we borrow heavily from its ideas.
  30. ;; This implementation heavily draws on ideas by James TD Smith and
  31. ;; Samuel Wales, and, of cause, uses John Wiegley's remember.el as inspiration.
  32. ;;; TODO
  33. ;; - find a clever way to not always insert an annotation maybe a
  34. ;; predicate function that can check for conditions for %a to be
  35. ;; used. This could be one of the properties.
  36. ;; - Should there be plist members that arrange for properties to be
  37. ;; asked for, like James proposed in his RFC?
  38. ;;; Code:
  39. (require 'cl-lib)
  40. (require 'org)
  41. (declare-function org-at-encrypted-entry-p "org-crypt" ())
  42. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  43. (declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction))
  44. (declare-function org-decrypt-entry "org-crypt" ())
  45. (declare-function org-encrypt-entry "org-crypt" ())
  46. (declare-function org-table-analyze "org-table" ())
  47. (declare-function org-table-current-dline "org-table" ())
  48. (declare-function org-table-fix-formulas "org-table" (key replace &optional limit delta remove))
  49. (declare-function org-table-goto-line "org-table" (N))
  50. (defvar dired-buffers)
  51. (defvar org-end-time-was-given)
  52. (defvar org-remember-default-headline)
  53. (defvar org-remember-templates)
  54. (defvar org-table-border-regexp)
  55. (defvar org-table-current-begin-pos)
  56. (defvar org-table-fix-formulas-confirm)
  57. (defvar org-table-hlines)
  58. (defvar org-capture-clock-was-started nil
  59. "Internal flag, noting if the clock was started.")
  60. (defvar org-capture-last-stored-marker (make-marker)
  61. "Marker pointing to the entry most recently stored with `org-capture'.")
  62. ;; The following variable is scoped dynamically by org-protocol
  63. ;; to indicate that the link properties have already been stored
  64. (defvar org-capture-link-is-already-stored nil)
  65. (defvar org-capture-is-refiling nil
  66. "Non-nil when capture process is refiling an entry.")
  67. (defvar org-capture--prompt-history-table (make-hash-table :test #'equal)
  68. "Hash table for all history lists per prompt.")
  69. (defvar org-capture--prompt-history nil
  70. "History list for prompt placeholders.")
  71. (defgroup org-capture nil
  72. "Options concerning capturing new entries."
  73. :tag "Org Capture"
  74. :group 'org)
  75. (defun org-capture-upgrade-templates (templates)
  76. "Update the template list to the new format.
  77. TEMPLATES is a template list, as in `org-capture-templates'. The
  78. new format unifies all the date/week tree targets into one that
  79. also allows for an optional outline path to specify a target."
  80. (let ((modified-templates
  81. (mapcar
  82. (lambda (entry)
  83. (pcase entry
  84. ;; Match templates with an obsolete "tree" target type. Replace
  85. ;; it with common `file+olp-datetree'. Add new properties
  86. ;; (i.e., `:time-prompt' and `:tree-type') if needed.
  87. (`(,key ,desc ,type (file+datetree . ,path) ,tpl . ,props)
  88. `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl ,@props))
  89. (`(,key ,desc ,type (file+datetree+prompt . ,path) ,tpl . ,props)
  90. `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl
  91. :time-prompt t ,@props))
  92. (`(,key ,desc ,type (file+weektree . ,path) ,tpl . ,props)
  93. `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl
  94. :tree-type week ,@props))
  95. (`(,key ,desc ,type (file+weektree+prompt . ,path) ,tpl . ,props)
  96. `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl
  97. :tree-type week :time-prompt t ,@props))
  98. ;; Other templates are left unchanged.
  99. (_ entry)))
  100. templates)))
  101. (unless (equal modified-templates templates)
  102. (message "Deprecated date/weektree capture templates changed to `file+olp+datetree'."))
  103. modified-templates))
  104. (defcustom org-capture-templates nil
  105. "Templates for the creation of new entries.
  106. Each entry is a list with the following items:
  107. keys The keys that will select the template, as a string, characters
  108. only, for example \"a\" for a template to be selected with a
  109. single key, or \"bt\" for selection with two keys. When using
  110. several keys, keys using the same prefix key must be together
  111. in the list and preceded by a 2-element entry explaining the
  112. prefix key, for example
  113. (\"b\" \"Templates for marking stuff to buy\")
  114. The \"C\" key is used by default for quick access to the
  115. customization of the template variable. But if you want to use
  116. that key for a template, you can.
  117. description A short string describing the template, will be shown during
  118. selection.
  119. type The type of entry. Valid types are:
  120. entry an Org node, with a headline. Will be filed
  121. as the child of the target entry or as a
  122. top-level entry.
  123. item a plain list item, will be placed in the
  124. first plain list at the target
  125. location.
  126. checkitem a checkbox item. This differs from the
  127. plain list item only is so far as it uses a
  128. different default template.
  129. table-line a new line in the first table at target location.
  130. plain text to be inserted as it is.
  131. target Specification of where the captured item should be placed.
  132. In Org files, targets usually define a node. Entries will
  133. become children of this node, other types will be added to the
  134. table or list in the body of this node.
  135. Most target specifications contain a file name. If that file
  136. name is the empty string, it defaults to `org-default-notes-file'.
  137. A file can also be given as a variable or as a function called
  138. with no argument. When an absolute path is not specified for a
  139. target, it is taken as relative to `org-directory'.
  140. Valid values are:
  141. (file \"path/to/file\")
  142. Text will be placed at the beginning or end of that file
  143. (id \"id of existing Org entry\")
  144. File as child of this entry, or in the body of the entry
  145. (file+headline \"path/to/file\" \"node headline\")
  146. Fast configuration if the target heading is unique in the file
  147. (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
  148. For non-unique headings, the full outline path is safer
  149. (file+regexp \"path/to/file\" \"regexp to find location\")
  150. File to the entry matching regexp
  151. (file+olp+datetree \"path/to/file\" \"Level 1 heading\" ...)
  152. Will create a heading in a date tree for today's date.
  153. If no heading is given, the tree will be on top level.
  154. To prompt for date instead of using TODAY, use the
  155. :time-prompt property. To create a week-tree, use the
  156. :tree-type property.
  157. (file+function \"path/to/file\" function-finding-location)
  158. A function to find the right location in the file
  159. (clock)
  160. File to the entry that is currently being clocked
  161. (function function-finding-location)
  162. Most general way: write your own function which both visits
  163. the file and moves point to the right location
  164. template The template for creating the capture item. If you leave this
  165. empty, an appropriate default template will be used. See below
  166. for more details. Instead of a string, this may also be one of
  167. (file \"/path/to/template-file\")
  168. (function function-returning-the-template)
  169. in order to get a template from a file, or dynamically
  170. from a function.
  171. The rest of the entry is a property list of additional options. Recognized
  172. properties are:
  173. :prepend Normally newly captured information will be appended at
  174. the target location (last child, last table line,
  175. last list item...). Setting this property will
  176. change that.
  177. :immediate-finish When set, do not offer to edit the information, just
  178. file it away immediately. This makes sense if the
  179. template only needs information that can be added
  180. automatically.
  181. :jump-to-captured When set, jump to the captured entry when finished.
  182. :empty-lines Set this to the number of lines the should be inserted
  183. before and after the new item. Default 0, only common
  184. other value is 1.
  185. :empty-lines-before Set this to the number of lines the should be inserted
  186. before the new item. Overrides :empty-lines for the
  187. number lines inserted before.
  188. :empty-lines-after Set this to the number of lines the should be inserted
  189. after the new item. Overrides :empty-lines for the
  190. number of lines inserted after.
  191. :clock-in Start the clock in this item.
  192. :clock-keep Keep the clock running when filing the captured entry.
  193. :clock-resume Start the interrupted clock when finishing the capture.
  194. Note that :clock-keep has precedence over :clock-resume.
  195. When setting both to t, the current clock will run and
  196. the previous one will not be resumed.
  197. :time-prompt Prompt for a date/time to be used for date/week trees
  198. and when filling the template.
  199. :tree-type When `week', make a week tree instead of the month tree.
  200. :unnarrowed Do not narrow the target buffer, simply show the
  201. full buffer. Default is to narrow it so that you
  202. only see the new stuff.
  203. :table-line-pos Specification of the location in the table where the
  204. new line should be inserted. It should be a string like
  205. \"II-3\", meaning that the new line should become the
  206. third line before the second horizontal separator line.
  207. :kill-buffer If the target file was not yet visited by a buffer when
  208. capture was invoked, kill the buffer again after capture
  209. is finalized.
  210. The template defines the text to be inserted. Often this is an
  211. Org mode entry (so the first line should start with a star) that
  212. will be filed as a child of the target headline. It can also be
  213. freely formatted text. Furthermore, the following %-escapes will
  214. be replaced with content and expanded:
  215. %[pathname] Insert the contents of the file given by
  216. `pathname'. These placeholders are expanded at the very
  217. beginning of the process so they can be used to extend the
  218. current template.
  219. %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
  220. Only placeholders pre-existing within the template, or
  221. introduced with %[pathname] are expanded this way. Since this
  222. happens after expanding non-interactive %-escapes, those can
  223. be used to fill the expression.
  224. %<...> The result of format-time-string on the ... format specification.
  225. %t Time stamp, date only. The time stamp is the current time,
  226. except when called from agendas with `\\[org-agenda-capture]' or
  227. with `org-capture-use-agenda-date' set.
  228. %T Time stamp as above, with date and time.
  229. %u, %U Like the above, but inactive time stamps.
  230. %i Initial content, copied from the active region. If %i is
  231. indented, the entire inserted text will be indented as well.
  232. %a Annotation, normally the link created with `org-store-link'.
  233. %A Like %a, but prompt for the description part.
  234. %l Like %a, but only insert the literal link.
  235. %c Current kill ring head.
  236. %x Content of the X clipboard.
  237. %k Title of currently clocked task.
  238. %K Link to currently clocked task.
  239. %n User name (taken from the variable `user-full-name').
  240. %f File visited by current buffer when org-capture was called.
  241. %F Full path of the file or directory visited by current buffer.
  242. %:keyword Specific information for certain link types, see below.
  243. %^g Prompt for tags, with completion on tags in target file.
  244. %^G Prompt for tags, with completion on all tags in all agenda files.
  245. %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
  246. You may define a prompt like: %^{Please specify birthday}t.
  247. The default date is that of %t, see above.
  248. %^C Interactive selection of which kill or clip to use.
  249. %^L Like %^C, but insert as link.
  250. %^{prop}p Prompt the user for a value for property `prop'.
  251. %^{prompt} Prompt the user for a string and replace this sequence with it.
  252. A default value and a completion table ca be specified like this:
  253. %^{prompt|default|completion2|completion3|...}.
  254. %? After completing the template, position cursor here.
  255. %\\1 ... %\\N Insert the text entered at the nth %^{prompt}, where N
  256. is a number, starting from 1.
  257. Apart from these general escapes, you can access information specific to
  258. the link type that is created. For example, calling `org-capture' in emails
  259. or in Gnus will record the author and the subject of the message, which you
  260. can access with \"%:from\" and \"%:subject\", respectively. Here is a
  261. complete list of what is recorded for each link type.
  262. Link type | Available information
  263. ------------------------+------------------------------------------------------
  264. bbdb | %:type %:name %:company
  265. vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
  266. gnus | %:from %:fromname %:fromaddress
  267. | %:to %:toname %:toaddress
  268. | %:fromto (either \"to NAME\" or \"from NAME\")
  269. | %:date %:date-timestamp (as active timestamp)
  270. | %:date-timestamp-inactive (as inactive timestamp)
  271. gnus | %:group, for messages also all email fields
  272. eww, w3, w3m | %:type %:url
  273. info | %:type %:file %:node
  274. calendar | %:type %:date
  275. When you need to insert a literal percent sign in the template,
  276. you can escape ambiguous cases with a backward slash, e.g., \\%i."
  277. :group 'org-capture
  278. :version "24.1"
  279. :set (lambda (s v) (set s (org-capture-upgrade-templates v)))
  280. :type
  281. (let ((file-variants '(choice :tag "Filename "
  282. (file :tag "Literal")
  283. (function :tag "Function")
  284. (variable :tag "Variable")
  285. (sexp :tag "Form"))))
  286. `(repeat
  287. (choice :value ("" "" entry (file "~/org/notes.org") "")
  288. (list :tag "Multikey description"
  289. (string :tag "Keys ")
  290. (string :tag "Description"))
  291. (list :tag "Template entry"
  292. (string :tag "Keys ")
  293. (string :tag "Description ")
  294. (choice :tag "Capture Type " :value entry
  295. (const :tag "Org entry" entry)
  296. (const :tag "Plain list item" item)
  297. (const :tag "Checkbox item" checkitem)
  298. (const :tag "Plain text" plain)
  299. (const :tag "Table line" table-line))
  300. (choice :tag "Target location"
  301. (list :tag "File"
  302. (const :format "" file)
  303. ,file-variants)
  304. (list :tag "ID"
  305. (const :format "" id)
  306. (string :tag " ID"))
  307. (list :tag "File & Headline"
  308. (const :format "" file+headline)
  309. ,file-variants
  310. (string :tag " Headline"))
  311. (list :tag "File & Outline path"
  312. (const :format "" file+olp)
  313. ,file-variants
  314. (repeat :tag "Outline path" :inline t
  315. (string :tag "Headline")))
  316. (list :tag "File & Regexp"
  317. (const :format "" file+regexp)
  318. ,file-variants
  319. (regexp :tag " Regexp"))
  320. (list :tag "File [ & Outline path ] & Date tree"
  321. (const :format "" file+olp+datetree)
  322. ,file-variants
  323. (option (repeat :tag "Outline path" :inline t
  324. (string :tag "Headline"))))
  325. (list :tag "File & function"
  326. (const :format "" file+function)
  327. ,file-variants
  328. (sexp :tag " Function"))
  329. (list :tag "Current clocking task"
  330. (const :format "" clock))
  331. (list :tag "Function"
  332. (const :format "" function)
  333. (sexp :tag " Function")))
  334. (choice :tag "Template "
  335. (string)
  336. (list :tag "File"
  337. (const :format "" file)
  338. (file :tag "Template file"))
  339. (list :tag "Function"
  340. (const :format "" function)
  341. (function :tag "Template function")))
  342. (plist :inline t
  343. ;; Give the most common options as checkboxes
  344. :options (((const :format "%v " :prepend) (const t))
  345. ((const :format "%v " :immediate-finish) (const t))
  346. ((const :format "%v " :jump-to-captured) (const t))
  347. ((const :format "%v " :empty-lines) (const 1))
  348. ((const :format "%v " :empty-lines-before) (const 1))
  349. ((const :format "%v " :empty-lines-after) (const 1))
  350. ((const :format "%v " :clock-in) (const t))
  351. ((const :format "%v " :clock-keep) (const t))
  352. ((const :format "%v " :clock-resume) (const t))
  353. ((const :format "%v " :time-prompt) (const t))
  354. ((const :format "%v " :tree-type) (const week))
  355. ((const :format "%v " :unnarrowed) (const t))
  356. ((const :format "%v " :table-line-pos) (string))
  357. ((const :format "%v " :kill-buffer) (const t)))))))))
  358. (defcustom org-capture-before-finalize-hook nil
  359. "Hook that is run right before a capture process is finalized.
  360. The capture buffer is still current when this hook runs and it is
  361. widened to the entire buffer."
  362. :group 'org-capture
  363. :version "24.1"
  364. :type 'hook)
  365. (defcustom org-capture-after-finalize-hook nil
  366. "Hook that is run right after a capture process is finalized.
  367. Suitable for window cleanup."
  368. :group 'org-capture
  369. :version "24.1"
  370. :type 'hook)
  371. (defcustom org-capture-prepare-finalize-hook nil
  372. "Hook that is run before the finalization starts.
  373. The capture buffer is current and still narrowed."
  374. :group 'org-capture
  375. :version "24.1"
  376. :type 'hook)
  377. (defcustom org-capture-bookmark t
  378. "When non-nil, add a bookmark pointing at the last stored
  379. position when capturing."
  380. :group 'org-capture
  381. :version "24.3"
  382. :type 'boolean)
  383. ;;; The property list for keeping information about the capture process
  384. (defvar org-capture-plist nil
  385. "Plist for the current capture process, global, to avoid having to pass it.")
  386. (defvar org-capture-current-plist nil
  387. "Local variable holding the plist in a capture buffer.
  388. This is used to store the plist for use when finishing a capture process
  389. because another such process might have changed the global variable by then.
  390. Each time a new capture buffer has been set up, the global `org-capture-plist'
  391. is copied to this variable, which is local in the indirect buffer.")
  392. (defvar org-capture-clock-keep nil
  393. "Local variable to store the value of the :clock-keep parameter.
  394. This is needed in case org-capture-finalize is called interactively.")
  395. (defun org-capture-put (&rest stuff)
  396. "Add properties to the capture property list `org-capture-plist'."
  397. (while stuff
  398. (setq org-capture-plist (plist-put org-capture-plist
  399. (pop stuff) (pop stuff)))))
  400. (defun org-capture-get (prop &optional local)
  401. "Get properties from the capture property list `org-capture-plist'.
  402. When LOCAL is set, use the local variable `org-capture-current-plist',
  403. this is necessary after initialization of the capture process,
  404. to avoid conflicts with other active capture processes."
  405. (plist-get (if local org-capture-current-plist org-capture-plist) prop))
  406. ;;; The minor mode
  407. (defvar org-capture-mode-map
  408. (let ((map (make-sparse-keymap)))
  409. (define-key map "\C-c\C-c" #'org-capture-finalize)
  410. (define-key map "\C-c\C-k" #'org-capture-kill)
  411. (define-key map "\C-c\C-w" #'org-capture-refile)
  412. map)
  413. "Keymap for `org-capture-mode', a minor mode.
  414. Use this map to set additional keybindings for when Org mode is used
  415. for a capture buffer.")
  416. (defvar org-capture-mode-hook nil
  417. "Hook for the `org-capture-mode' minor mode.")
  418. (define-minor-mode org-capture-mode
  419. "Minor mode for special key bindings in a capture buffer.
  420. Turning on this mode runs the normal hook `org-capture-mode-hook'."
  421. nil " Cap" org-capture-mode-map
  422. (setq-local
  423. header-line-format
  424. (substitute-command-keys
  425. "\\<org-capture-mode-map>Capture buffer. Finish \
  426. `\\[org-capture-finalize]', refile `\\[org-capture-refile]', \
  427. abort `\\[org-capture-kill]'.")))
  428. ;;; The main commands
  429. (defvar org-capture-initial nil)
  430. (defvar org-capture-entry nil)
  431. ;;;###autoload
  432. (defun org-capture-string (string &optional keys)
  433. "Capture STRING with the template selected by KEYS."
  434. (interactive "sInitial text: \n")
  435. (let ((org-capture-initial string)
  436. (org-capture-entry (org-capture-select-template keys)))
  437. (org-capture)))
  438. (defcustom org-capture-templates-contexts nil
  439. "Alist of capture templates and valid contexts.
  440. For example, if you have a capture template \"c\" and you want
  441. this template to be accessible only from `message-mode' buffers,
  442. use this:
  443. \\='((\"c\" ((in-mode . \"message-mode\"))))
  444. Here are the available contexts definitions:
  445. in-file: command displayed only in matching files
  446. in-mode: command displayed only in matching modes
  447. not-in-file: command not displayed in matching files
  448. not-in-mode: command not displayed in matching modes
  449. in-buffer: command displayed only in matching buffers
  450. not-in-buffer: command not displayed in matching buffers
  451. [function]: a custom function taking no argument
  452. If you define several checks, the agenda command will be
  453. accessible if there is at least one valid check.
  454. You can also bind a key to another capture template depending on
  455. contextual rules.
  456. \\='((\"c\" \"d\" ((in-mode . \"message-mode\"))))
  457. Here it means: in `message-mode buffers', use \"c\" as the
  458. key for the capture template otherwise associated with \"d\".
  459. \(The template originally associated with \"d\" is not displayed
  460. to avoid duplicates.)"
  461. :version "24.3"
  462. :group 'org-capture
  463. :type '(repeat (list :tag "Rule"
  464. (string :tag " Capture key")
  465. (string :tag "Replace by template")
  466. (repeat :tag "Available when"
  467. (choice
  468. (cons :tag "Condition"
  469. (choice
  470. (const :tag "In file" in-file)
  471. (const :tag "Not in file" not-in-file)
  472. (const :tag "In buffer" in-buffer)
  473. (const :tag "Not in buffer" not-in-buffer)
  474. (const :tag "In mode" in-mode)
  475. (const :tag "Not in mode" not-in-mode))
  476. (regexp))
  477. (function :tag "Custom function"))))))
  478. (defcustom org-capture-use-agenda-date nil
  479. "Non-nil means use the date at point when capturing from agendas.
  480. When nil, you can still capture using the date at point with
  481. `\\[org-agenda-capture]'."
  482. :group 'org-capture
  483. :version "24.3"
  484. :type 'boolean)
  485. ;;;###autoload
  486. (defun org-capture (&optional goto keys)
  487. "Capture something.
  488. \\<org-capture-mode-map>
  489. This will let you select a template from `org-capture-templates', and
  490. then file the newly captured information. The text is immediately
  491. inserted at the target location, and an indirect buffer is shown where
  492. you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the \
  493. previous
  494. state of Emacs, so that you can continue your work.
  495. When called interactively with a `\\[universal-argument]' prefix argument \
  496. GOTO, don't
  497. capture anything, just go to the file/headline where the selected
  498. template stores its notes.
  499. With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to \
  500. the last note stored.
  501. When called with a `C-0' (zero) prefix, insert a template at point.
  502. When called with a `C-1' (one) prefix, force prompting for a date when
  503. a datetree entry is made.
  504. ELisp programs can set KEYS to a string associated with a template
  505. in `org-capture-templates'. In this case, interactive selection
  506. will be bypassed.
  507. If `org-capture-use-agenda-date' is non-nil, capturing from the
  508. agenda will use the date at point as the default date. Then, a
  509. `C-1' prefix will tell the capture process to use the HH:MM time
  510. of the day at point (if any) or the current HH:MM time."
  511. (interactive "P")
  512. (when (and org-capture-use-agenda-date
  513. (eq major-mode 'org-agenda-mode))
  514. (setq org-overriding-default-time
  515. (org-get-cursor-date (equal goto 1))))
  516. (cond
  517. ((equal goto '(4)) (org-capture-goto-target))
  518. ((equal goto '(16)) (org-capture-goto-last-stored))
  519. (t
  520. (let* ((orig-buf (current-buffer))
  521. (annotation (if (and (boundp 'org-capture-link-is-already-stored)
  522. org-capture-link-is-already-stored)
  523. (plist-get org-store-link-plist :annotation)
  524. (ignore-errors (org-store-link nil))))
  525. (entry (or org-capture-entry (org-capture-select-template keys)))
  526. initial)
  527. (setq initial (or org-capture-initial
  528. (and (org-region-active-p)
  529. (buffer-substring (point) (mark)))))
  530. (when (stringp initial)
  531. (remove-text-properties 0 (length initial) '(read-only t) initial))
  532. (when (stringp annotation)
  533. (remove-text-properties 0 (length annotation)
  534. '(read-only t) annotation))
  535. (cond
  536. ((equal entry "C")
  537. (customize-variable 'org-capture-templates))
  538. ((equal entry "q")
  539. (user-error "Abort"))
  540. (t
  541. (org-capture-set-plist entry)
  542. (org-capture-get-template)
  543. (org-capture-put :original-buffer orig-buf
  544. :original-file (or (buffer-file-name orig-buf)
  545. (and (featurep 'dired)
  546. (car (rassq orig-buf
  547. dired-buffers))))
  548. :original-file-nondirectory
  549. (and (buffer-file-name orig-buf)
  550. (file-name-nondirectory
  551. (buffer-file-name orig-buf)))
  552. :annotation annotation
  553. :initial initial
  554. :return-to-wconf (current-window-configuration)
  555. :default-time
  556. (or org-overriding-default-time
  557. (org-current-time)))
  558. (org-capture-set-target-location)
  559. (condition-case error
  560. (org-capture-put :template (org-capture-fill-template))
  561. ((error quit)
  562. (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
  563. (error "Capture abort: %s" error)))
  564. (setq org-capture-clock-keep (org-capture-get :clock-keep))
  565. (if (equal goto 0)
  566. ;;insert at point
  567. (org-capture-insert-template-here)
  568. (condition-case error
  569. (org-capture-place-template
  570. (eq (car (org-capture-get :target)) 'function))
  571. ((error quit)
  572. (if (and (buffer-base-buffer (current-buffer))
  573. (string-prefix-p "CAPTURE-" (buffer-name)))
  574. (kill-buffer (current-buffer)))
  575. (set-window-configuration (org-capture-get :return-to-wconf))
  576. (error "Capture template `%s': %s"
  577. (org-capture-get :key)
  578. (nth 1 error))))
  579. (if (and (derived-mode-p 'org-mode)
  580. (org-capture-get :clock-in))
  581. (condition-case nil
  582. (progn
  583. (if (org-clock-is-active)
  584. (org-capture-put :interrupted-clock
  585. (copy-marker org-clock-marker)))
  586. (org-clock-in)
  587. (setq-local org-capture-clock-was-started t))
  588. (error
  589. "Could not start the clock in this capture buffer")))
  590. (if (org-capture-get :immediate-finish)
  591. (org-capture-finalize)))))))))
  592. (defun org-capture-get-template ()
  593. "Get the template from a file or a function if necessary."
  594. (let ((txt (org-capture-get :template)) file)
  595. (cond
  596. ((and (listp txt) (eq (car txt) 'file))
  597. (if (file-exists-p
  598. (setq file (expand-file-name (nth 1 txt) org-directory)))
  599. (setq txt (org-file-contents file))
  600. (setq txt (format "* Template file %s not found" (nth 1 txt)))))
  601. ((and (listp txt) (eq (car txt) 'function))
  602. (if (fboundp (nth 1 txt))
  603. (setq txt (funcall (nth 1 txt)))
  604. (setq txt (format "* Template function %s not found" (nth 1 txt)))))
  605. ((not txt) (setq txt ""))
  606. ((stringp txt))
  607. (t (setq txt "* Invalid capture template")))
  608. (org-capture-put :template txt)))
  609. (defun org-capture-finalize (&optional stay-with-capture)
  610. "Finalize the capture process.
  611. With prefix argument STAY-WITH-CAPTURE, jump to the location of the
  612. captured item after finalizing."
  613. (interactive "P")
  614. (when (org-capture-get :jump-to-captured)
  615. (setq stay-with-capture t))
  616. (unless (and org-capture-mode
  617. (buffer-base-buffer (current-buffer)))
  618. (error "This does not seem to be a capture buffer for Org mode"))
  619. (run-hooks 'org-capture-prepare-finalize-hook)
  620. ;; Did we start the clock in this capture buffer?
  621. (when (and org-capture-clock-was-started
  622. org-clock-marker
  623. (eq (marker-buffer org-clock-marker) (buffer-base-buffer))
  624. (>= org-clock-marker (point-min))
  625. (< org-clock-marker (point-max)))
  626. ;; Looks like the clock we started is still running.
  627. (if org-capture-clock-keep
  628. ;; User may have completed clocked heading from the template.
  629. ;; Refresh clock mode line.
  630. (org-clock-update-mode-line t)
  631. ;; Clock out. Possibly resume interrupted clock.
  632. (let (org-log-note-clock-out) (org-clock-out))
  633. (when (and (org-capture-get :clock-resume 'local)
  634. (markerp (org-capture-get :interrupted-clock 'local))
  635. (buffer-live-p (marker-buffer
  636. (org-capture-get :interrupted-clock 'local))))
  637. (let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
  638. (org-with-point-at clock-in-task (org-clock-in)))
  639. (message "Interrupted clock has been resumed"))))
  640. (let ((abort-note nil))
  641. ;; Store the size of the capture buffer
  642. (org-capture-put :captured-entry-size (- (point-max) (point-min)))
  643. (widen)
  644. ;; Store the insertion point in the target buffer
  645. (org-capture-put :insertion-point (point))
  646. (if org-note-abort
  647. (let ((beg (org-capture-get :begin-marker 'local))
  648. (end (org-capture-get :end-marker 'local)))
  649. (if (not (and beg end)) (setq abort-note 'dirty)
  650. (setq abort-note t)
  651. (org-with-wide-buffer (kill-region beg end))))
  652. ;; Postprocessing: Update Statistics cookies, do the sorting
  653. (when (derived-mode-p 'org-mode)
  654. (save-excursion
  655. (when (ignore-errors (org-back-to-heading))
  656. (org-update-parent-todo-statistics)
  657. (org-update-checkbox-count)))
  658. ;; FIXME Here we should do the sorting
  659. ;; If we have added a table line, maybe recompute?
  660. (when (and (eq (org-capture-get :type 'local) 'table-line)
  661. (org-at-table-p))
  662. (if (not (org-table-get-stored-formulas)) (org-table-align)
  663. ;; Adjust formulas, if necessary. We assume a non-nil
  664. ;; `:immediate-finish' means that no confirmation is
  665. ;; required. Else, obey `org-table-fix-formulas-confirm'.
  666. ;;
  667. ;; The delta required to fix formulas depends on the
  668. ;; number of rows inserted by the template.
  669. (when (or (org-capture-get :immediate-finish)
  670. (not org-table-fix-formulas-confirm)
  671. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  672. (org-table-fix-formulas
  673. "@" nil (1- (org-table-current-dline))
  674. (count-lines (org-capture-get :begin-marker 'local)
  675. (org-capture-get :end-marker 'local))))
  676. (org-table-recalculate 'all)))) ;FIXME: should we iterate?
  677. ;; Store this place as the last one where we stored something
  678. ;; Do the marking in the base buffer, so that it makes sense after
  679. ;; the indirect buffer has been killed.
  680. (org-capture-store-last-position)
  681. ;; Run the hook
  682. (run-hooks 'org-capture-before-finalize-hook))
  683. (when (org-capture-get :decrypted)
  684. (save-excursion
  685. (goto-char (org-capture-get :decrypted))
  686. (org-encrypt-entry)))
  687. ;; Kill the indirect buffer
  688. (let ((return-wconf (org-capture-get :return-to-wconf 'local))
  689. (new-buffer (org-capture-get :new-buffer 'local))
  690. (kill-buffer (org-capture-get :kill-buffer 'local))
  691. (base-buffer (buffer-base-buffer (current-buffer))))
  692. ;; Kill the indirect buffer
  693. (kill-buffer (current-buffer))
  694. ;; Narrow back the target buffer to its previous state
  695. (with-current-buffer (org-capture-get :buffer)
  696. (let ((reg (org-capture-get :initial-target-region))
  697. (pos (org-capture-get :initial-target-position))
  698. (ipt (org-capture-get :insertion-point))
  699. (size (org-capture-get :captured-entry-size)))
  700. (if (not reg)
  701. (widen)
  702. (cond ((< ipt (car reg))
  703. ;; insertion point is before the narrowed region
  704. (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
  705. ((> ipt (cdr reg))
  706. ;; insertion point is after the narrowed region
  707. (narrow-to-region (car reg) (cdr reg)))
  708. (t
  709. ;; insertion point is within the narrowed region
  710. (narrow-to-region (car reg) (+ size (cdr reg)))))
  711. ;; now place back the point at its original position
  712. (if (< ipt (car reg))
  713. (goto-char (+ size pos))
  714. (goto-char (if (< ipt pos) (+ size pos) pos))))))
  715. ;; Kill the target buffer if that is desired
  716. (when (and base-buffer new-buffer kill-buffer)
  717. (with-current-buffer base-buffer (save-buffer))
  718. (kill-buffer base-buffer))
  719. ;; Restore the window configuration before capture
  720. (set-window-configuration return-wconf))
  721. (run-hooks 'org-capture-after-finalize-hook)
  722. ;; Special cases
  723. (cond
  724. (abort-note
  725. (cl-case abort-note
  726. (clean
  727. (message "Capture process aborted and target buffer cleaned up"))
  728. (dirty
  729. (error "Capture process aborted, but target buffer could not be \
  730. cleaned up correctly"))))
  731. (stay-with-capture
  732. (org-capture-goto-last-stored)))
  733. ;; Return if we did store something
  734. (not abort-note)))
  735. (defun org-capture-refile ()
  736. "Finalize the current capture and then refile the entry.
  737. Refiling is done from the base buffer, because the indirect buffer is then
  738. already gone. Any prefix argument will be passed to the refile command."
  739. (interactive)
  740. (unless (eq (org-capture-get :type 'local) 'entry)
  741. (user-error "Refiling from a capture buffer makes only sense \
  742. for `entry'-type templates"))
  743. (let* ((base (or (buffer-base-buffer) (current-buffer)))
  744. (pos (make-marker))
  745. (org-capture-is-refiling t)
  746. (kill-buffer (org-capture-get :kill-buffer 'local))
  747. (jump-to-captured (org-capture-get :jump-to-captured 'local)))
  748. ;; Since `org-capture-finalize' may alter buffer contents (e.g.,
  749. ;; empty lines) around entry, use a marker to refer to the
  750. ;; headline to be refiled. Place the marker in the base buffer,
  751. ;; as the current indirect one is going to be killed.
  752. (set-marker pos (save-excursion (org-back-to-heading t) (point)) base)
  753. ;; `org-capture-finalize' calls `org-capture-goto-last-stored' too
  754. ;; early. We want to wait for the refiling to be over, so we
  755. ;; control when the latter function is called.
  756. (org-capture-put :kill-buffer nil :jump-to-captured nil)
  757. (org-capture-finalize)
  758. (save-window-excursion
  759. (with-current-buffer base
  760. (org-with-point-at pos
  761. (call-interactively 'org-refile))))
  762. (when kill-buffer
  763. (with-current-buffer base (save-buffer))
  764. (kill-buffer base))
  765. (when jump-to-captured (org-capture-goto-last-stored))))
  766. (defun org-capture-kill ()
  767. "Abort the current capture process."
  768. (interactive)
  769. ;; FIXME: This does not do the right thing, we need to remove the
  770. ;; new stuff by hand it is easy: undo, then kill the buffer
  771. (let ((org-note-abort t)
  772. (org-capture-before-finalize-hook nil))
  773. (org-capture-finalize)))
  774. (defun org-capture-goto-last-stored ()
  775. "Go to the location where the last capture note was stored."
  776. (interactive)
  777. (org-goto-marker-or-bmk org-capture-last-stored-marker
  778. (plist-get org-bookmark-names-plist
  779. :last-capture))
  780. (message "This is the last note stored by a capture process"))
  781. ;;; Supporting functions for handling the process
  782. (defun org-capture-put-target-region-and-position ()
  783. "Store the initial region with `org-capture-put'."
  784. (org-capture-put
  785. :initial-target-region
  786. ;; Check if the buffer is currently narrowed
  787. (when (org-buffer-narrowed-p)
  788. (cons (point-min) (point-max))))
  789. ;; store the current point
  790. (org-capture-put :initial-target-position (point)))
  791. (defvar org-time-was-given) ; dynamically scoped parameter
  792. (defun org-capture-set-target-location (&optional target)
  793. "Find TARGET buffer and position.
  794. Store them in the capture property list."
  795. (let ((target-entry-p t))
  796. (save-excursion
  797. (pcase (or target (org-capture-get :target))
  798. (`(file ,path)
  799. (set-buffer (org-capture-target-buffer path))
  800. (org-capture-put-target-region-and-position)
  801. (widen)
  802. (setq target-entry-p nil))
  803. (`(id ,id)
  804. (pcase (org-id-find id)
  805. (`(,path . ,position)
  806. (set-buffer (org-capture-target-buffer path))
  807. (widen)
  808. (org-capture-put-target-region-and-position)
  809. (goto-char position))
  810. (_ (error "Cannot find target ID \"%s\"" id))))
  811. (`(file+headline ,path ,headline)
  812. (set-buffer (org-capture-target-buffer path))
  813. ;; Org expects the target file to be in Org mode, otherwise
  814. ;; it throws an error. However, the default notes files
  815. ;; should work out of the box. In this case, we switch it to
  816. ;; Org mode.
  817. (unless (derived-mode-p 'org-mode)
  818. (org-display-warning
  819. (format "Capture requirement: switching buffer %S to Org mode"
  820. (current-buffer)))
  821. (org-mode))
  822. (org-capture-put-target-region-and-position)
  823. (widen)
  824. (goto-char (point-min))
  825. (if (re-search-forward (format org-complex-heading-regexp-format
  826. (regexp-quote headline))
  827. nil t)
  828. (beginning-of-line)
  829. (goto-char (point-max))
  830. (unless (bolp) (insert "\n"))
  831. (insert "* " headline "\n")
  832. (beginning-of-line 0)))
  833. (`(file+olp ,path . ,outline-path)
  834. (let ((m (org-find-olp (cons (org-capture-expand-file path)
  835. outline-path))))
  836. (set-buffer (marker-buffer m))
  837. (org-capture-put-target-region-and-position)
  838. (widen)
  839. (goto-char m)
  840. (set-marker m nil)))
  841. (`(file+regexp ,path ,regexp)
  842. (set-buffer (org-capture-target-buffer path))
  843. (org-capture-put-target-region-and-position)
  844. (widen)
  845. (goto-char (point-min))
  846. (if (not (re-search-forward regexp nil t))
  847. (error "No match for target regexp in file %s" path)
  848. (goto-char (if (org-capture-get :prepend)
  849. (match-beginning 0)
  850. (match-end 0)))
  851. (org-capture-put :exact-position (point))
  852. (setq target-entry-p
  853. (and (derived-mode-p 'org-mode) (org-at-heading-p)))))
  854. (`(file+olp+datetree ,path . ,outline-path)
  855. (let ((m (if outline-path
  856. (org-find-olp (cons (org-capture-expand-file path)
  857. outline-path))
  858. (set-buffer (org-capture-target-buffer path))
  859. (point-marker))))
  860. (set-buffer (marker-buffer m))
  861. (org-capture-put-target-region-and-position)
  862. (widen)
  863. (goto-char m)
  864. (set-marker m nil)
  865. (require 'org-datetree)
  866. (org-capture-put-target-region-and-position)
  867. (widen)
  868. ;; Make a date/week tree entry, with the current date (or
  869. ;; yesterday, if we are extending dates for a couple of hours)
  870. (funcall
  871. (if (eq (org-capture-get :tree-type) 'week)
  872. #'org-datetree-find-iso-week-create
  873. #'org-datetree-find-date-create)
  874. (calendar-gregorian-from-absolute
  875. (cond
  876. (org-overriding-default-time
  877. ;; Use the overriding default time.
  878. (time-to-days org-overriding-default-time))
  879. ((or (org-capture-get :time-prompt)
  880. (equal current-prefix-arg 1))
  881. ;; Prompt for date.
  882. (let ((prompt-time (org-read-date
  883. nil t nil "Date for tree entry:"
  884. (current-time))))
  885. (org-capture-put
  886. :default-time
  887. (cond ((and (or (not (boundp 'org-time-was-given))
  888. (not org-time-was-given))
  889. (not (= (time-to-days prompt-time) (org-today))))
  890. ;; Use 00:00 when no time is given for another
  891. ;; date than today?
  892. (apply #'encode-time
  893. (append `(0 0 ,org-extend-today-until)
  894. (cl-cdddr (decode-time prompt-time)))))
  895. ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)"
  896. org-read-date-final-answer)
  897. ;; Replace any time range by its start.
  898. (apply #'encode-time
  899. (org-read-date-analyze
  900. (replace-match "\\1 \\2" nil nil
  901. org-read-date-final-answer)
  902. prompt-time (decode-time prompt-time))))
  903. (t prompt-time)))
  904. (time-to-days prompt-time)))
  905. (t
  906. ;; Current date, possibly corrected for late night
  907. ;; workers.
  908. (org-today))))
  909. ;; the following is the keep-restriction argument for
  910. ;; org-datetree-find-date-create
  911. (when outline-path 'subtree-at-point))))
  912. (`(file+function ,path ,function)
  913. (set-buffer (org-capture-target-buffer path))
  914. (org-capture-put-target-region-and-position)
  915. (widen)
  916. (funcall function)
  917. (org-capture-put :exact-position (point))
  918. (setq target-entry-p
  919. (and (derived-mode-p 'org-mode) (org-at-heading-p))))
  920. (`(function ,fun)
  921. (funcall fun)
  922. (org-capture-put :exact-position (point))
  923. (setq target-entry-p
  924. (and (derived-mode-p 'org-mode) (org-at-heading-p))))
  925. (`(clock)
  926. (if (and (markerp org-clock-hd-marker)
  927. (marker-buffer org-clock-hd-marker))
  928. (progn (set-buffer (marker-buffer org-clock-hd-marker))
  929. (org-capture-put-target-region-and-position)
  930. (widen)
  931. (goto-char org-clock-hd-marker))
  932. (error "No running clock that could be used as capture target")))
  933. (target (error "Invalid capture target specification: %S" target)))
  934. (org-capture-put :buffer (current-buffer)
  935. :pos (point)
  936. :target-entry-p target-entry-p
  937. :decrypted
  938. (and (featurep 'org-crypt)
  939. (org-at-encrypted-entry-p)
  940. (save-excursion
  941. (org-decrypt-entry)
  942. (and (org-back-to-heading t) (point))))))))
  943. (defun org-capture-expand-file (file)
  944. "Expand functions, symbols and file names for FILE.
  945. When FILE is a function, call it. When it is a form, evaluate
  946. it. When it is a variable, return its value. When it is
  947. a string, treat it as a file name, possibly expanding it
  948. according to `org-directory', and return it. If it is the empty
  949. string, however, return `org-default-notes-file'. In any other
  950. case, raise an error."
  951. (let ((location (cond ((equal file "") org-default-notes-file)
  952. ((stringp file) (expand-file-name file org-directory))
  953. ((functionp file) (funcall file))
  954. ((and (symbolp file) (boundp file)) (symbol-value file))
  955. (t nil))))
  956. (or (org-string-nw-p location)
  957. (error "Invalid file location: %S" location))))
  958. (defun org-capture-target-buffer (file)
  959. "Get a buffer for FILE.
  960. FILE is a generalized file location, as handled by
  961. `org-capture-expand-file'."
  962. (let ((file (org-capture-expand-file file)))
  963. (or (org-find-base-buffer-visiting file)
  964. (progn (org-capture-put :new-buffer t)
  965. (find-file-noselect file)))))
  966. (defun org-capture-place-template (&optional inhibit-wconf-store)
  967. "Insert the template at the target location, and display the buffer.
  968. When `inhibit-wconf-store', don't store the window configuration, as it
  969. may have been stored before."
  970. (unless inhibit-wconf-store
  971. (org-capture-put :return-to-wconf (current-window-configuration)))
  972. (delete-other-windows)
  973. (org-switch-to-buffer-other-window
  974. (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
  975. (widen)
  976. (org-show-all)
  977. (goto-char (org-capture-get :pos))
  978. (setq-local outline-level 'org-outline-level)
  979. (pcase (org-capture-get :type)
  980. ((or `nil `entry) (org-capture-place-entry))
  981. (`table-line (org-capture-place-table-line))
  982. (`plain (org-capture-place-plain-text))
  983. (`item (org-capture-place-item))
  984. (`checkitem (org-capture-place-item)))
  985. (org-capture-mode 1)
  986. (setq-local org-capture-current-plist org-capture-plist))
  987. (defun org-capture-place-entry ()
  988. "Place the template as a new Org entry."
  989. (let ((reversed? (org-capture-get :prepend))
  990. (level 1))
  991. (when (org-capture-get :exact-position)
  992. (goto-char (org-capture-get :exact-position)))
  993. (cond
  994. ;; Insert as a child of the current entry.
  995. ((org-capture-get :target-entry-p)
  996. (setq level (org-get-valid-level
  997. (if (org-at-heading-p) (org-outline-level) 1)
  998. 1))
  999. (if reversed? (outline-next-heading) (org-end-of-subtree t t)))
  1000. ;; Insert as a top-level entry at the beginning of the file.
  1001. (reversed?
  1002. (goto-char (point-min))
  1003. (unless (org-at-heading-p) (outline-next-heading)))
  1004. ;; Otherwise, insert as a top-level entry at the end of the file.
  1005. (t (goto-char (point-max))))
  1006. (let ((origin (point)))
  1007. (unless (bolp) (insert "\n"))
  1008. (org-capture-empty-lines-before)
  1009. (let ((beg (point)))
  1010. (org-capture-position-for-last-stored beg)
  1011. (let ((template (org-capture-get :template)))
  1012. (org-capture-verify-tree template)
  1013. (org-paste-subtree level template 'for-yank))
  1014. (let ((end (if (org-at-heading-p) (line-end-position 0) (point))))
  1015. (org-capture-empty-lines-after)
  1016. (unless (org-at-heading-p) (outline-next-heading))
  1017. (org-capture-mark-kill-region origin (point))
  1018. (org-capture-narrow beg end)
  1019. (when (or (search-backward "%?" beg t)
  1020. (search-forward "%?" end t))
  1021. (replace-match "")))))))
  1022. (defun org-capture-place-item ()
  1023. "Place the template as a new plain list item."
  1024. (let* ((txt (org-capture-get :template))
  1025. (target-entry-p (org-capture-get :target-entry-p))
  1026. (ind 0)
  1027. beg end)
  1028. (if (org-capture-get :exact-position)
  1029. (goto-char (org-capture-get :exact-position))
  1030. (cond
  1031. ((not target-entry-p)
  1032. ;; Insert as top-level entry, either at beginning or at end of file
  1033. (setq beg (point-min) end (point-max)))
  1034. (t
  1035. (setq beg (1+ (point-at-eol))
  1036. end (save-excursion (outline-next-heading) (point)))))
  1037. (setq ind nil)
  1038. (if (org-capture-get :prepend)
  1039. (progn
  1040. (goto-char beg)
  1041. (when (org-list-search-forward (org-item-beginning-re) end t)
  1042. (goto-char (match-beginning 0))
  1043. (setq ind (current-indentation))))
  1044. (goto-char end)
  1045. (when (org-list-search-backward (org-item-beginning-re) beg t)
  1046. (setq ind (current-indentation))
  1047. (org-end-of-item)))
  1048. (unless ind (goto-char end)))
  1049. ;; Remove common indentation
  1050. (setq txt (org-remove-indentation txt))
  1051. ;; Make sure this is indeed an item
  1052. (unless (string-match (concat "\\`" (org-item-re)) txt)
  1053. (setq txt (concat "- "
  1054. (mapconcat 'identity (split-string txt "\n")
  1055. "\n "))))
  1056. ;; Prepare surrounding empty lines.
  1057. (unless (bolp) (insert "\n"))
  1058. (org-capture-empty-lines-before)
  1059. (setq beg (point))
  1060. (unless (eolp) (save-excursion (insert "\n")))
  1061. (unless ind
  1062. (org-indent-line)
  1063. (setq ind (current-indentation))
  1064. (delete-region beg (point)))
  1065. ;; Set the correct indentation, depending on context
  1066. (setq ind (make-string ind ?\ ))
  1067. (setq txt (concat ind
  1068. (mapconcat 'identity (split-string txt "\n")
  1069. (concat "\n" ind))
  1070. "\n"))
  1071. ;; Insert item.
  1072. (insert txt)
  1073. (org-capture-empty-lines-after)
  1074. (org-capture-position-for-last-stored beg)
  1075. (setq end (point))
  1076. (org-capture-mark-kill-region beg end)
  1077. (org-capture-narrow beg end)
  1078. (when (or (re-search-backward "%\\?" beg t)
  1079. (re-search-forward "%\\?" end t))
  1080. (replace-match ""))))
  1081. (defun org-capture-place-table-line ()
  1082. "Place the template as a table line."
  1083. (require 'org-table)
  1084. (let ((text
  1085. (pcase (org-trim (org-capture-get :template))
  1086. ((pred (string-match-p org-table-border-regexp))
  1087. "| %?Bad template |")
  1088. (text (concat text "\n"))))
  1089. (table-line-pos (org-capture-get :table-line-pos))
  1090. beg end)
  1091. (cond
  1092. ((org-capture-get :exact-position)
  1093. (setq beg (org-capture-get :exact-position))
  1094. (setq end (save-excursion (outline-next-heading) (point))))
  1095. ((not (org-capture-get :target-entry-p))
  1096. ;; Table is not necessarily under a heading. Find first table
  1097. ;; in the buffer.
  1098. (setq beg (point-min) end (point-max)))
  1099. (t
  1100. ;; We are at a heading, limit search to the body.
  1101. (setq beg (line-beginning-position 2))
  1102. (setq end (save-excursion (outline-next-heading) (point)))))
  1103. (goto-char beg)
  1104. ;; Narrow to the table, possibly creating one if necessary.
  1105. (catch :found
  1106. (while (re-search-forward org-table-dataline-regexp end t)
  1107. (pcase (org-element-lineage (org-element-at-point) '(table) t)
  1108. (`nil nil)
  1109. ((pred (lambda (e) (eq 'table.el (org-element-property :type e))))
  1110. nil)
  1111. (table
  1112. (goto-char (org-element-property :contents-end table))
  1113. (narrow-to-region (org-element-property :post-affiliated table)
  1114. (point))
  1115. (throw :found t))))
  1116. ;; No table found. Create it with an empty header.
  1117. (goto-char end)
  1118. (unless (bolp) (insert "\n"))
  1119. (let ((origin (point)))
  1120. (insert "| |\n|----|\n")
  1121. (narrow-to-region origin (point))))
  1122. ;; In the current table, find the appropriate location for TEXT.
  1123. (cond
  1124. ((and table-line-pos
  1125. (string-match "\\(I+\\)\\([-+][0-9]+\\)" table-line-pos))
  1126. (goto-char (point-min))
  1127. (let ((line
  1128. (condition-case _
  1129. (progn
  1130. (save-match-data (org-table-analyze))
  1131. (aref org-table-hlines
  1132. (- (match-end 1) (match-beginning 1))))
  1133. (error
  1134. (error "Invalid table line specification %S" table-line-pos))))
  1135. (delta (string-to-number (match-string 2 table-line-pos))))
  1136. (forward-line (+ line delta (if (< delta 0) 0 -1)))
  1137. (forward-line))) ;insert below
  1138. ((org-capture-get :prepend)
  1139. (goto-char (point-min))
  1140. (cond
  1141. ((not (re-search-forward org-table-hline-regexp nil t)))
  1142. ((re-search-forward org-table-dataline-regexp nil t) (beginning-of-line))
  1143. (t (goto-char (org-table-end)))))
  1144. (t
  1145. (goto-char (org-table-end))))
  1146. ;; Insert text and position point according to template.
  1147. (let ((origin (point)))
  1148. (unless (bolp) (insert "\n"))
  1149. (let ((beg (point))
  1150. (end (save-excursion
  1151. (insert text)
  1152. (point))))
  1153. (org-capture-position-for-last-stored 'table-line)
  1154. (org-capture-mark-kill-region origin end)
  1155. (org-capture-narrow beg end)
  1156. (when (or (search-backward "%?" beg t)
  1157. (search-forward "%?" end t))
  1158. (replace-match "")))
  1159. (org-table-align))))
  1160. (defun org-capture-place-plain-text ()
  1161. "Place the template plainly.
  1162. If the target locator points at an Org node, place the template into
  1163. the text of the entry, before the first child. If not, place the
  1164. template at the beginning or end of the file.
  1165. Of course, if exact position has been required, just put it there."
  1166. (cond
  1167. ((org-capture-get :exact-position)
  1168. (goto-char (org-capture-get :exact-position)))
  1169. ((and (org-capture-get :target-entry-p)
  1170. (bolp)
  1171. (looking-at org-outline-regexp))
  1172. ;; Place the text into this entry.
  1173. (if (org-capture-get :prepend)
  1174. ;; Skip meta data and drawers.
  1175. (org-end-of-meta-data t)
  1176. ;; Go to end of the entry text, before the next headline
  1177. (outline-next-heading)))
  1178. (t
  1179. ;; Beginning or end of file.
  1180. (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
  1181. (let ((origin (point)))
  1182. (unless (bolp) (insert "\n"))
  1183. (org-capture-empty-lines-before)
  1184. (org-capture-position-for-last-stored (point))
  1185. (let ((beg (point)))
  1186. (insert (org-capture-get :template))
  1187. (unless (bolp) (insert "\n"))
  1188. ;; Ignore the final newline character so as to not alter data
  1189. ;; after inserted text. Yet, if the template is empty, make
  1190. ;; sure END matches BEG instead of pointing before it.
  1191. (let ((end (max beg (1- (point)))))
  1192. (org-capture-empty-lines-after)
  1193. (org-capture-mark-kill-region origin (point))
  1194. (org-capture-narrow beg end)
  1195. (when (or (search-backward "%?" beg t)
  1196. (search-forward "%?" end t))
  1197. (replace-match ""))))))
  1198. (defun org-capture-mark-kill-region (beg end)
  1199. "Mark the region that will have to be killed when aborting capture."
  1200. (let ((m1 (copy-marker beg))
  1201. (m2 (copy-marker end t)))
  1202. (org-capture-put :begin-marker m1)
  1203. (org-capture-put :end-marker m2)))
  1204. (defun org-capture-position-for-last-stored (where)
  1205. "Memorize the position that should later become the position of last capture."
  1206. (cond
  1207. ((integerp where)
  1208. (org-capture-put :position-for-last-stored
  1209. (move-marker (make-marker) where
  1210. (or (buffer-base-buffer (current-buffer))
  1211. (current-buffer)))))
  1212. ((eq where 'table-line)
  1213. (org-capture-put :position-for-last-stored
  1214. (list 'table-line
  1215. (org-table-current-dline))))
  1216. (t (error "This should not happen"))))
  1217. (defun org-capture-store-last-position ()
  1218. "Store the last-captured position."
  1219. (let* ((where (org-capture-get :position-for-last-stored 'local))
  1220. (pos (cond
  1221. ((markerp where)
  1222. (prog1 (marker-position where)
  1223. (move-marker where nil)))
  1224. ((and (listp where) (eq (car where) 'table-line))
  1225. (if (org-at-table-p)
  1226. (save-excursion
  1227. (org-table-goto-line (nth 1 where))
  1228. (point-at-bol))
  1229. (point))))))
  1230. (with-current-buffer (buffer-base-buffer (current-buffer))
  1231. (org-with-point-at pos
  1232. (when org-capture-bookmark
  1233. (let ((bookmark (plist-get org-bookmark-names-plist :last-capture)))
  1234. (when bookmark (with-demoted-errors (bookmark-set bookmark)))))
  1235. (move-marker org-capture-last-stored-marker (point))))))
  1236. (defun org-capture-narrow (beg end)
  1237. "Narrow, unless configuration says not to narrow."
  1238. (unless (org-capture-get :unnarrowed)
  1239. (narrow-to-region beg end)
  1240. (goto-char beg)))
  1241. (defun org-capture-empty-lines-before (&optional n)
  1242. "Set the correct number of empty lines before the insertion point.
  1243. Point will be after the empty lines, so insertion can directly be done."
  1244. (setq n (or n (org-capture-get :empty-lines-before)
  1245. (org-capture-get :empty-lines) 0))
  1246. (let ((pos (point)))
  1247. (org-back-over-empty-lines)
  1248. (delete-region (point) pos)
  1249. (when (> n 0) (newline n))))
  1250. (defun org-capture-empty-lines-after (&optional n)
  1251. "Set the correct number of empty lines after the inserted string.
  1252. Point will remain at the first line after the inserted text."
  1253. (setq n (or n (org-capture-get :empty-lines-after)
  1254. (org-capture-get :empty-lines) 0))
  1255. (org-back-over-empty-lines)
  1256. (while (looking-at "[ \t]*\n") (replace-match ""))
  1257. (let ((pos (point)))
  1258. (when (> n 0) (newline n))
  1259. (goto-char pos)))
  1260. (defvar org-clock-marker) ; Defined in org.el
  1261. (defun org-capture-insert-template-here ()
  1262. "Insert the capture template at point."
  1263. (let* ((template (org-capture-get :template))
  1264. (type (org-capture-get :type))
  1265. beg end pp)
  1266. (unless (bolp) (insert "\n"))
  1267. (setq beg (point))
  1268. (cond
  1269. ((and (eq type 'entry) (derived-mode-p 'org-mode))
  1270. (org-capture-verify-tree (org-capture-get :template))
  1271. (org-paste-subtree nil template t))
  1272. ((and (memq type '(item checkitem))
  1273. (derived-mode-p 'org-mode)
  1274. (save-excursion (skip-chars-backward " \t\n")
  1275. (setq pp (point))
  1276. (org-in-item-p)))
  1277. (goto-char pp)
  1278. (org-insert-item)
  1279. (skip-chars-backward " ")
  1280. (skip-chars-backward "-+*0123456789).")
  1281. (delete-region (point) (point-at-eol))
  1282. (setq beg (point))
  1283. (org-remove-indentation template)
  1284. (insert template)
  1285. (org-capture-empty-lines-after)
  1286. (goto-char beg)
  1287. (org-list-repair)
  1288. (org-end-of-item))
  1289. (t
  1290. (insert template)
  1291. (org-capture-empty-lines-after)
  1292. (skip-chars-forward " \t\n")
  1293. (unless (eobp) (beginning-of-line))))
  1294. (setq end (point))
  1295. (goto-char beg)
  1296. (when (re-search-forward "%\\?" end t)
  1297. (replace-match ""))))
  1298. (defun org-capture-set-plist (entry)
  1299. "Initialize the property list from the template definition."
  1300. (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
  1301. (org-capture-put :key (car entry) :description (nth 1 entry)
  1302. :target (nth 3 entry))
  1303. (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
  1304. (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
  1305. ;; The template may be empty or omitted for special types.
  1306. ;; Here we insert the default templates for such cases.
  1307. (cond
  1308. ((eq type 'item) (setq txt "- %?"))
  1309. ((eq type 'checkitem) (setq txt "- [ ] %?"))
  1310. ((eq type 'table-line) (setq txt "| %? |"))
  1311. ((member type '(nil entry)) (setq txt "* %?\n %a"))))
  1312. (org-capture-put :template txt :type type)))
  1313. (defun org-capture-goto-target (&optional template-key)
  1314. "Go to the target location of a capture template.
  1315. The user is queried for the template."
  1316. (interactive)
  1317. (let ((entry (org-capture-select-template template-key)))
  1318. (unless entry (error "No capture template selected"))
  1319. (org-capture-set-plist entry)
  1320. (org-capture-set-target-location)
  1321. (pop-to-buffer-same-window (org-capture-get :buffer))
  1322. (goto-char (org-capture-get :pos))))
  1323. (defun org-capture-get-indirect-buffer (&optional buffer prefix)
  1324. "Make an indirect buffer for a capture process.
  1325. Use PREFIX as a prefix for the name of the indirect buffer."
  1326. (setq buffer (or buffer (current-buffer)))
  1327. (let ((n 1) (base (buffer-name buffer)) bname)
  1328. (setq bname (concat prefix "-" base))
  1329. (while (buffer-live-p (get-buffer bname))
  1330. (setq bname (concat prefix "-" (number-to-string (cl-incf n)) "-" base)))
  1331. (condition-case nil
  1332. (make-indirect-buffer buffer bname 'clone)
  1333. (error
  1334. (let ((buf (make-indirect-buffer buffer bname)))
  1335. (with-current-buffer buf (org-mode))
  1336. buf)))))
  1337. (defun org-capture-verify-tree (tree)
  1338. "Throw error if TREE is not a valid tree."
  1339. (unless (org-kill-is-subtree-p tree)
  1340. (error "Template is not a valid Org entry or tree")))
  1341. ;;; The template code
  1342. (defun org-capture-select-template (&optional keys)
  1343. "Select a capture template.
  1344. Lisp programs can force the template by setting KEYS to a string."
  1345. (let ((org-capture-templates
  1346. (or (org-contextualize-keys
  1347. (org-capture-upgrade-templates org-capture-templates)
  1348. org-capture-templates-contexts)
  1349. '(("t" "Task" entry (file+headline "" "Tasks")
  1350. "* TODO %?\n %u\n %a")))))
  1351. (if keys
  1352. (or (assoc keys org-capture-templates)
  1353. (error "No capture template referred to by \"%s\" keys" keys))
  1354. (org-mks org-capture-templates
  1355. "Select a capture template\n========================="
  1356. "Template key: "
  1357. '(("C" "Customize org-capture-templates")
  1358. ("q" "Abort"))))))
  1359. (defvar org-capture--clipboards nil
  1360. "List various clipboards values.")
  1361. (defun org-capture-fill-template (&optional template initial annotation)
  1362. "Fill a template and return the filled template as a string.
  1363. The template may still contain \"%?\" for cursor positioning."
  1364. (let* ((template (or template (org-capture-get :template)))
  1365. (buffer (org-capture-get :buffer))
  1366. (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
  1367. (time (let* ((c (or (org-capture-get :default-time) (current-time)))
  1368. (d (decode-time c)))
  1369. (if (< (nth 2 d) org-extend-today-until)
  1370. (encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d))
  1371. c)))
  1372. (v-t (format-time-string (org-time-stamp-format nil) time))
  1373. (v-T (format-time-string (org-time-stamp-format t) time))
  1374. (v-u (format-time-string (org-time-stamp-format nil t) time))
  1375. (v-U (format-time-string (org-time-stamp-format t t) time))
  1376. (v-c (and kill-ring (current-kill 0)))
  1377. (v-x (or (org-get-x-clipboard 'PRIMARY)
  1378. (org-get-x-clipboard 'CLIPBOARD)
  1379. (org-get-x-clipboard 'SECONDARY)
  1380. "")) ;ensure it is a string
  1381. ;; `initial' and `annotation' might have been passed. But if
  1382. ;; the property list has them, we prefer those values.
  1383. (v-i (or (plist-get org-store-link-plist :initial)
  1384. (and (stringp initial) (org-no-properties initial))
  1385. (org-capture-get :initial)
  1386. ""))
  1387. (v-a
  1388. (let ((a (or (plist-get org-store-link-plist :annotation)
  1389. annotation
  1390. (org-capture-get :annotation)
  1391. "")))
  1392. ;; Is the link empty? Then we do not want it...
  1393. (if (equal a "[[]]") "" a)))
  1394. (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
  1395. (v-A (if (and v-a (string-match l-re v-a))
  1396. (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
  1397. v-a))
  1398. (v-l (if (and v-a (string-match l-re v-a))
  1399. (replace-match "\\1" nil nil v-a)
  1400. v-a))
  1401. (v-n user-full-name)
  1402. (v-k (if (marker-buffer org-clock-marker)
  1403. (org-no-properties org-clock-heading)
  1404. ""))
  1405. (v-K (if (marker-buffer org-clock-marker)
  1406. (org-make-link-string
  1407. (format "%s::*%s"
  1408. (buffer-file-name (marker-buffer org-clock-marker))
  1409. v-k)
  1410. v-k)
  1411. ""))
  1412. (v-f (or (org-capture-get :original-file-nondirectory) ""))
  1413. (v-F (or (org-capture-get :original-file) ""))
  1414. (org-capture--clipboards
  1415. (delq nil
  1416. (list v-i
  1417. (org-get-x-clipboard 'PRIMARY)
  1418. (org-get-x-clipboard 'CLIPBOARD)
  1419. (org-get-x-clipboard 'SECONDARY)
  1420. v-c))))
  1421. (setq org-store-link-plist (plist-put org-store-link-plist :annotation v-a))
  1422. (setq org-store-link-plist (plist-put org-store-link-plist :initial v-i))
  1423. (unless template
  1424. (setq template "")
  1425. (message "no template") (ding)
  1426. (sit-for 1))
  1427. (save-window-excursion
  1428. (org-switch-to-buffer-other-window (get-buffer-create "*Capture*"))
  1429. (erase-buffer)
  1430. (setq buffer-file-name nil)
  1431. (setq mark-active nil)
  1432. (insert template)
  1433. (goto-char (point-min))
  1434. ;; %[] insert contents of a file.
  1435. (save-excursion
  1436. (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
  1437. (let ((filename (expand-file-name (match-string 1)))
  1438. (beg (copy-marker (match-beginning 0)))
  1439. (end (copy-marker (match-end 0))))
  1440. (unless (org-capture-escaped-%)
  1441. (delete-region beg end)
  1442. (set-marker beg nil)
  1443. (set-marker end nil)
  1444. (condition-case error
  1445. (insert-file-contents filename)
  1446. (error
  1447. (insert (format "%%![couldn not insert %s: %s]"
  1448. filename
  1449. error))))))))
  1450. ;; Mark %() embedded elisp for later evaluation.
  1451. (org-capture-expand-embedded-elisp 'mark)
  1452. ;; Expand non-interactive templates.
  1453. (let ((regexp "%\\(:[-a-za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlntTuUx]\\)"))
  1454. (save-excursion
  1455. (while (re-search-forward regexp nil t)
  1456. ;; `org-capture-escaped-%' may modify buffer and cripple
  1457. ;; match-data. Use markers instead. Ditto for other
  1458. ;; templates.
  1459. (let ((pos (copy-marker (match-beginning 0)))
  1460. (end (copy-marker (match-end 0)))
  1461. (value (match-string 1))
  1462. (time-string (match-string 2)))
  1463. (unless (org-capture-escaped-%)
  1464. (delete-region pos end)
  1465. (set-marker pos nil)
  1466. (set-marker end nil)
  1467. (let* ((inside-sexp? (org-capture-inside-embedded-elisp-p))
  1468. (replacement
  1469. (pcase (string-to-char value)
  1470. (?< (format-time-string time-string time))
  1471. (?:
  1472. (or (plist-get org-store-link-plist (intern value))
  1473. ""))
  1474. (?i
  1475. (if inside-sexp? v-i
  1476. ;; Outside embedded Lisp, repeat leading
  1477. ;; characters before initial place holder
  1478. ;; every line.
  1479. (let ((lead (buffer-substring-no-properties
  1480. (line-beginning-position) (point))))
  1481. (replace-regexp-in-string "\n\\(.\\)"
  1482. (concat lead "\\1")
  1483. v-i nil nil 1))))
  1484. (?a v-a)
  1485. (?A v-A)
  1486. (?c v-c)
  1487. (?f v-f)
  1488. (?F v-F)
  1489. (?k v-k)
  1490. (?K v-K)
  1491. (?l v-l)
  1492. (?n v-n)
  1493. (?t v-t)
  1494. (?T v-T)
  1495. (?u v-u)
  1496. (?U v-U)
  1497. (?x v-x))))
  1498. (insert
  1499. (if inside-sexp?
  1500. ;; Escape sensitive characters.
  1501. (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement)
  1502. replacement))))))))
  1503. ;; Expand %() embedded Elisp. Limit to Sexp originally marked.
  1504. (org-capture-expand-embedded-elisp)
  1505. ;; Expand interactive templates. This is the last step so that
  1506. ;; template is mostly expanded when prompting happens. Turn on
  1507. ;; Org mode and set local variables. This is to support
  1508. ;; completion in interactive prompts.
  1509. (let ((org-inhibit-startup t)) (org-mode))
  1510. (org-clone-local-variables buffer "\\`org-")
  1511. (let (strings) ; Stores interactive answers.
  1512. (save-excursion
  1513. (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?"))
  1514. (while (re-search-forward regexp nil t)
  1515. (let* ((items (and (match-end 1)
  1516. (save-match-data
  1517. (split-string (match-string-no-properties 1)
  1518. "|"))))
  1519. (key (match-string 2))
  1520. (beg (copy-marker (match-beginning 0)))
  1521. (end (copy-marker (match-end 0)))
  1522. (prompt (nth 0 items))
  1523. (default (nth 1 items))
  1524. (completions (nthcdr 2 items)))
  1525. (unless (org-capture-escaped-%)
  1526. (delete-region beg end)
  1527. (set-marker beg nil)
  1528. (set-marker end nil)
  1529. (pcase key
  1530. ((or "G" "g")
  1531. (let* ((org-last-tags-completion-table
  1532. (org-global-tags-completion-table
  1533. (cond ((equal key "G") (org-agenda-files))
  1534. (file (list file))
  1535. (t nil))))
  1536. (org-add-colon-after-tag-completion t)
  1537. (ins (mapconcat
  1538. #'identity
  1539. (org-split-string
  1540. (completing-read
  1541. (if prompt (concat prompt ": ") "Tags: ")
  1542. 'org-tags-completion-function nil nil nil
  1543. 'org-tags-history)
  1544. "[^[:alnum:]_@#%]+")
  1545. ":")))
  1546. (when (org-string-nw-p ins)
  1547. (unless (eq (char-before) ?:) (insert ":"))
  1548. (insert ins)
  1549. (unless (eq (char-after) ?:) (insert ":"))
  1550. (when (org-at-heading-p) (org-align-tags)))))
  1551. ((or "C" "L")
  1552. (let ((insert-fun (if (equal key "C") #'insert
  1553. (lambda (s) (org-insert-link 0 s)))))
  1554. (pcase org-capture--clipboards
  1555. (`nil nil)
  1556. (`(,value) (funcall insert-fun value))
  1557. (`(,first-value . ,_)
  1558. (funcall insert-fun
  1559. (read-string "Clipboard/kill value: "
  1560. first-value
  1561. 'org-capture--clipboards
  1562. first-value)))
  1563. (_ (error "Invalid `org-capture--clipboards' value: %S"
  1564. org-capture--clipboards)))))
  1565. ("p"
  1566. ;; We remove file properties inherited from
  1567. ;; target buffer so `org-read-property-value' has
  1568. ;; a chance to find allowed values in sub-trees
  1569. ;; from the target buffer.
  1570. (setq-local org-file-properties nil)
  1571. (let* ((origin (set-marker (make-marker)
  1572. (org-capture-get :pos)
  1573. (org-capture-get :buffer)))
  1574. ;; Find location from where to get allowed
  1575. ;; values. If `:target-entry-p' is
  1576. ;; non-nil, the current headline in the
  1577. ;; target buffer is going to be a parent
  1578. ;; headline, so location is fine.
  1579. ;; Otherwise, find the parent headline in
  1580. ;; the target buffer.
  1581. (pom (if (org-capture-get :target-entry-p) origin
  1582. (let ((level (progn
  1583. (while (org-up-heading-safe))
  1584. (org-current-level))))
  1585. (org-with-point-at origin
  1586. (let ((l (if (org-at-heading-p)
  1587. (org-current-level)
  1588. most-positive-fixnum)))
  1589. (while (and l (>= l level))
  1590. (setq l (org-up-heading-safe)))
  1591. (if l (point-marker)
  1592. (point-min-marker)))))))
  1593. (value (org-read-property-value prompt pom)))
  1594. (org-set-property prompt value)))
  1595. ((or "t" "T" "u" "U")
  1596. ;; These are the date/time related ones.
  1597. (let* ((upcase? (equal (upcase key) key))
  1598. (org-end-time-was-given nil)
  1599. (time (org-read-date upcase? t nil prompt)))
  1600. (org-insert-time-stamp
  1601. time (or org-time-was-given upcase?)
  1602. (member key '("u" "U"))
  1603. nil nil (list org-end-time-was-given))))
  1604. (`nil
  1605. ;; Load history list for current prompt.
  1606. (setq org-capture--prompt-history
  1607. (gethash prompt org-capture--prompt-history-table))
  1608. (push (org-completing-read
  1609. (concat (or prompt "Enter string")
  1610. (and default (format " [%s]" default))
  1611. ": ")
  1612. completions
  1613. nil nil nil 'org-capture--prompt-history default)
  1614. strings)
  1615. (insert (car strings))
  1616. ;; Save updated history list for current prompt.
  1617. (puthash prompt org-capture--prompt-history
  1618. org-capture--prompt-history-table))
  1619. (_
  1620. (error "Unknown template placeholder: \"%%^%s\""
  1621. key))))))))
  1622. ;; Replace %n escapes with nth %^{...} string.
  1623. (setq strings (nreverse strings))
  1624. (save-excursion
  1625. (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
  1626. (unless (org-capture-escaped-%)
  1627. (replace-match
  1628. (nth (1- (string-to-number (match-string 1))) strings)
  1629. nil t)))))
  1630. ;; Make sure there are no empty lines before the text, and that
  1631. ;; it ends with a newline character or it is empty.
  1632. (skip-chars-forward " \t\n")
  1633. (delete-region (point-min) (line-beginning-position))
  1634. (goto-char (point-max))
  1635. (skip-chars-backward " \t\n")
  1636. (delete-region (point) (point-max))
  1637. (unless (bobp) (insert "\n"))
  1638. ;; Return the expanded template and kill the capture buffer.
  1639. (untabify (point-min) (point-max))
  1640. (set-buffer-modified-p nil)
  1641. (prog1 (buffer-substring-no-properties (point-min) (point-max))
  1642. (kill-buffer (current-buffer))))))
  1643. (defun org-capture-escaped-% ()
  1644. "Non-nil if % was escaped.
  1645. If yes, unescape it now. Assume match-data contains the
  1646. placeholder to check."
  1647. (save-excursion
  1648. (goto-char (match-beginning 0))
  1649. (let ((n (abs (skip-chars-backward "\\\\"))))
  1650. (delete-char (/ (1+ n) 2))
  1651. (= (% n 2) 1))))
  1652. (defun org-capture-expand-embedded-elisp (&optional mark)
  1653. "Evaluate embedded elisp %(sexp) and replace with the result.
  1654. When optional MARK argument is non-nil, mark Sexp with a text
  1655. property (`org-embedded-elisp') for later evaluation. Only
  1656. marked Sexp are evaluated when this argument is nil."
  1657. (save-excursion
  1658. (goto-char (point-min))
  1659. (while (re-search-forward "%(" nil t)
  1660. (cond
  1661. ((get-text-property (match-beginning 0) 'org-embedded-elisp)
  1662. (goto-char (match-beginning 0))
  1663. (let ((template-start (point)))
  1664. (forward-char 1)
  1665. (let* ((sexp (read (current-buffer)))
  1666. (result (org-eval
  1667. (org-capture--expand-keyword-in-embedded-elisp
  1668. sexp))))
  1669. (delete-region template-start (point))
  1670. (cond
  1671. ((not result) nil)
  1672. ((stringp result) (insert result))
  1673. (t (error
  1674. "Capture template sexp `%s' must evaluate to string or nil"
  1675. sexp))))))
  1676. ((not mark) nil)
  1677. ;; Only mark valid and non-escaped sexp.
  1678. ((org-capture-escaped-%) nil)
  1679. (t
  1680. (let ((end (with-syntax-table emacs-lisp-mode-syntax-table
  1681. (ignore-errors (scan-sexps (1- (point)) 1)))))
  1682. (when end
  1683. (put-text-property (- (point) 2) end 'org-embedded-elisp t))))))))
  1684. (defun org-capture--expand-keyword-in-embedded-elisp (attr)
  1685. "Recursively replace capture link keywords in ATTR sexp.
  1686. Such keywords are prefixed with \"%:\". See
  1687. `org-capture-template' for more information."
  1688. (cond ((consp attr)
  1689. (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr))
  1690. ((symbolp attr)
  1691. (let* ((attr-symbol (symbol-name attr))
  1692. (key (and (string-match "%\\(:.*\\)" attr-symbol)
  1693. (intern (match-string 1 attr-symbol)))))
  1694. (or (plist-get org-store-link-plist key)
  1695. attr)))
  1696. (t attr)))
  1697. (defun org-capture-inside-embedded-elisp-p ()
  1698. "Non-nil if point is inside of embedded elisp %(sexp).
  1699. Assume sexps have been marked with
  1700. `org-capture-expand-embedded-elisp' beforehand."
  1701. (get-text-property (point) 'org-embedded-elisp))
  1702. ;;;###autoload
  1703. (defun org-capture-import-remember-templates ()
  1704. "Set `org-capture-templates' to be similar to `org-remember-templates'."
  1705. (interactive)
  1706. (when (and (yes-or-no-p
  1707. "Import old remember templates into org-capture-templates? ")
  1708. (yes-or-no-p
  1709. "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
  1710. (require 'org-remember)
  1711. (setq org-capture-templates
  1712. (mapcar
  1713. (lambda (entry)
  1714. (let ((desc (car entry))
  1715. (key (char-to-string (nth 1 entry)))
  1716. (template (nth 2 entry))
  1717. (file (or (nth 3 entry) org-default-notes-file))
  1718. (position (or (nth 4 entry) org-remember-default-headline))
  1719. (type 'entry)
  1720. (prepend org-reverse-note-order)
  1721. immediate target jump-to-captured)
  1722. (cond
  1723. ((member position '(top bottom))
  1724. (setq target (list 'file file)
  1725. prepend (eq position 'top)))
  1726. ((eq position 'date-tree)
  1727. (setq target (list 'file+datetree file)
  1728. prepend nil))
  1729. (t (setq target (list 'file+headline file position))))
  1730. (when (string-match "%!" template)
  1731. (setq template (replace-match "" t t template)
  1732. immediate t))
  1733. (when (string-match "%&" template)
  1734. (setq jump-to-captured t))
  1735. (append (list key desc type target template)
  1736. (and prepend '(:prepend t))
  1737. (and immediate '(:immediate-finish t))
  1738. (and jump-to-captured '(:jump-to-captured t)))))
  1739. org-remember-templates))))
  1740. (provide 'org-capture)
  1741. ;;; org-capture.el ends here