org-capture.el 75 KB

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