org-capture.el 76 KB

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