org-capture.el 75 KB

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