org-capture.el 71 KB

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