org-capture.el 78 KB

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