org-capture.el 76 KB

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