org-capture.el 71 KB

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