org-capture.el 77 KB

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