org-capture.el 77 KB

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