org-capture.el 71 KB

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