org-capture.el 77 KB

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