org-capture.el 72 KB

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