org-capture.el 75 KB

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