org-capture.el 75 KB

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