org-capture.el 74 KB

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