org-capture.el 71 KB

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