org-capture.el 75 KB

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