org-src.el 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. ;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Bastien Guerry <bzg@gnu.org>
  7. ;; Dan Davison <davison at stats dot ox dot ac dot uk>
  8. ;; Keywords: outlines, hypermedia, calendar, wp
  9. ;; URL: https://orgmode.org
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  24. ;;
  25. ;;; Commentary:
  26. ;; This file contains the code dealing with source code examples in
  27. ;; Org mode.
  28. ;;; Code:
  29. (require 'org-macs)
  30. (org-assert-version)
  31. (require 'cl-lib)
  32. (require 'ob-comint)
  33. (require 'org-macs)
  34. (require 'org-compat)
  35. (require 'org-keys)
  36. (declare-function org--get-expected-indentation "org" (element contentsp))
  37. (declare-function org-mode "org" ())
  38. (declare-function org--get-expected-indentation "org" (element contentsp))
  39. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  40. (declare-function org-element-class "org-element" (datum &optional parent))
  41. (declare-function org-element-context "org-element" (&optional element))
  42. (declare-function org-element-lineage "org-element"
  43. (blob &optional types with-self))
  44. (declare-function org-element--parse-paired-brackets "org-element" (char))
  45. (declare-function org-element-property "org-element" (property element))
  46. (declare-function org-element-type "org-element" (element))
  47. (declare-function org-footnote-goto-definition "org-footnote"
  48. (label &optional location))
  49. (defvar org-inhibit-startup)
  50. (defcustom org-edit-src-turn-on-auto-save nil
  51. "Non-nil means turn `auto-save-mode' on when editing a source block.
  52. This will save the content of the source code editing buffer into
  53. a newly created file, not the base buffer for this source block.
  54. If you want to regularly save the base buffer instead of the source
  55. code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
  56. :group 'org-edit-structure
  57. :version "24.4"
  58. :package-version '(Org . "8.0")
  59. :type 'boolean)
  60. (defcustom org-edit-src-auto-save-idle-delay 0
  61. "Delay before saving a source code buffer back into its base buffer.
  62. When a positive integer N, save after N seconds of idle time.
  63. When 0 (the default), don't auto-save.
  64. If you want to save the source code buffer itself, don't use this.
  65. Check `org-edit-src-turn-on-auto-save' instead."
  66. :group 'org-edit-structure
  67. :version "24.4"
  68. :package-version '(Org . "8.0")
  69. :type 'integer)
  70. (defcustom org-coderef-label-format "(ref:%s)"
  71. "The default coderef format.
  72. This format string will be used to search for coderef labels in literal
  73. examples (EXAMPLE and SRC blocks). The format can be overwritten in
  74. an individual literal example with the -l option, like
  75. #+BEGIN_SRC pascal +n -r -l \"((%s))\"
  76. ...
  77. #+END_SRC
  78. If you want to use this for HTML export, make sure that the format does
  79. not introduce special font-locking, and avoid the HTML special
  80. characters `<', `>', and `&'. The reason for this restriction is that
  81. the labels are searched for only after htmlize has done its job."
  82. :group 'org-edit-structure ; FIXME this is not in the right group
  83. :type 'string)
  84. (defcustom org-edit-fixed-width-region-mode 'artist-mode
  85. "The mode that should be used to edit fixed-width regions.
  86. These are the regions where each line starts with a colon."
  87. :group 'org-edit-structure
  88. :type '(choice
  89. (const artist-mode)
  90. (const picture-mode)
  91. (const fundamental-mode)
  92. (function :tag "Other (specify)")))
  93. (defcustom org-src-preserve-indentation nil
  94. "If non-nil preserve leading whitespace characters on export.
  95. \\<org-mode-map>
  96. If non-nil leading whitespace characters in source code blocks
  97. are preserved on export, and when switching between the org
  98. buffer and the language mode edit buffer.
  99. When this variable is nil, after editing with `\\[org-edit-src-code]',
  100. the minimum (across-lines) number of leading whitespace characters
  101. are removed from all lines, and the code block is uniformly indented
  102. according to the value of `org-edit-src-content-indentation'."
  103. :group 'org-edit-structure
  104. :type 'boolean)
  105. (defcustom org-edit-src-content-indentation 2
  106. "Indentation for the content of a source code block.
  107. This should be the number of spaces added to the indentation of the #+begin
  108. line in order to compute the indentation of the block content after
  109. editing it with `\\[org-edit-src-code]'.
  110. It has no effect if `org-src-preserve-indentation' is non-nil."
  111. :group 'org-edit-structure
  112. :type 'integer
  113. :safe #'wholenump)
  114. (defcustom org-edit-src-persistent-message t
  115. "Non-nil means show persistent exit help message while editing src examples.
  116. The message is shown in the header-line, which will be created in the
  117. first line of the window showing the editing buffer."
  118. :group 'org-edit-structure
  119. :type 'boolean)
  120. (defcustom org-src-ask-before-returning-to-edit-buffer t
  121. "Non-nil means ask before switching to an existing edit buffer.
  122. If nil, when `org-edit-src-code' is used on a block that already
  123. has an active edit buffer, it will switch to that edit buffer
  124. immediately; otherwise it will ask whether you want to return to
  125. the existing edit buffer."
  126. :group 'org-edit-structure
  127. :version "24.4"
  128. :package-version '(Org . "8.0")
  129. :type 'boolean)
  130. (defcustom org-src-window-setup 'reorganize-frame
  131. "How the source code edit buffer should be displayed.
  132. Possible values for this option are:
  133. plain Show edit buffer using `display-buffer'. Users can
  134. further control the display behavior by modifying
  135. `display-buffer-alist' and its relatives.
  136. current-window Show edit buffer in the current window, keeping all other
  137. windows.
  138. split-window-below Show edit buffer below the current window, keeping all
  139. other windows.
  140. split-window-right Show edit buffer to the right of the current window,
  141. keeping all other windows.
  142. other-window Use `switch-to-buffer-other-window' to display edit buffer.
  143. reorganize-frame Show only two windows on the current frame, the current
  144. window and the edit buffer.
  145. other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
  146. Also, when exiting the edit buffer, kill that frame.
  147. Values that modify the window layout (reorganize-frame, split-window-below,
  148. split-window-right) will restore the layout after exiting the edit buffer."
  149. :group 'org-edit-structure
  150. :type '(choice
  151. (const plain)
  152. (const current-window)
  153. (const split-window-below)
  154. (const split-window-right)
  155. (const other-frame)
  156. (const other-window)
  157. (const reorganize-frame)))
  158. (defvar org-src-mode-hook nil
  159. "Hook run after Org switched a source code snippet to its Emacs mode.
  160. \\<org-mode-map>
  161. This hook will run:
  162. - when editing a source code snippet with `\\[org-edit-special]'
  163. - when formatting a source code snippet for export with htmlize.
  164. You may want to use this hook for example to turn off `outline-minor-mode'
  165. or similar things which you want to have when editing a source code file,
  166. but which mess up the display of a snippet in Org exported files.")
  167. (defcustom org-src-lang-modes
  168. '(("C" . c)
  169. ("C++" . c++)
  170. ("asymptote" . asy)
  171. ("bash" . sh)
  172. ("beamer" . latex)
  173. ("calc" . fundamental)
  174. ("cpp" . c++)
  175. ("ditaa" . artist)
  176. ("desktop" . conf-desktop)
  177. ("dot" . fundamental)
  178. ("elisp" . emacs-lisp)
  179. ("ocaml" . tuareg)
  180. ("screen" . shell-script)
  181. ("shell" . sh)
  182. ("sqlite" . sql)
  183. ("toml" . conf-toml))
  184. "Alist mapping languages to their major mode.
  185. The key is the language name. The value is the mode name, as
  186. a string or a symbol, without the \"-mode\" suffix.
  187. For many languages this is simple, but for language where this is
  188. not the case, this variable provides a way to simplify things on
  189. the user side. For example, there is no `ocaml-mode' in Emacs,
  190. but the mode to use is `tuareg-mode'."
  191. :group 'org-edit-structure
  192. :type '(repeat
  193. (cons
  194. (string "Language name")
  195. (symbol "Major mode"))))
  196. (defcustom org-src-block-faces nil
  197. "Alist of faces to be used for source-block.
  198. Each element is a cell of the format
  199. (\"language\" FACE)
  200. Where FACE is either a defined face or an anonymous face.
  201. For instance, the following would color the background of
  202. emacs-lisp source blocks and python source blocks in purple and
  203. green, respectability.
  204. (setq org-src-block-faces
  205. \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
  206. (\"python\" (:background \"#e5ffb8\"))))"
  207. :group 'org-edit-structure
  208. :type '(repeat (list (string :tag "language")
  209. (choice
  210. (face :tag "Face")
  211. (sexp :tag "Anonymous face"))))
  212. :version "26.1"
  213. :package-version '(Org . "9.0"))
  214. (defcustom org-src-tab-acts-natively t
  215. "If non-nil, TAB uses the language's major-mode binding in code blocks."
  216. :type 'boolean
  217. :package-version '(Org . "9.4")
  218. :group 'org-babel)
  219. ;;; Internal functions and variables
  220. (defvar org-src--auto-save-timer nil
  221. "Idle Timer auto-saving remote editing buffers.")
  222. (defvar-local org-src--allow-write-back t)
  223. (put 'org-src--allow-write-back 'permanent-local t)
  224. (defvar-local org-src--babel-info nil)
  225. (put 'org-src--babel-info 'permanent-local t)
  226. (defvar-local org-src--beg-marker nil)
  227. (put 'org-src--beg-marker 'permanent-local t)
  228. (defvar-local org-src--block-indentation nil)
  229. (put 'org-src--block-indentation 'permanent-local t)
  230. (defvar-local org-src--content-indentation nil)
  231. (put 'org-src--content-indentation 'permanent-local t)
  232. (defvar-local org-src--end-marker nil)
  233. (put 'org-src--end-marker 'permanent-local t)
  234. (defvar-local org-src--from-org-mode nil)
  235. (put 'org-src--from-org-mode 'permanent-local t)
  236. (defvar-local org-src--overlay nil)
  237. (put 'org-src--overlay 'permanent-local t)
  238. (defvar-local org-src--preserve-indentation nil)
  239. (put 'org-src--preserve-indentation 'permanent-local t)
  240. (defvar-local org-src--remote nil)
  241. (put 'org-src--remote 'permanent-local t)
  242. (defvar-local org-src--saved-temp-window-config nil)
  243. (put 'org-src--saved-temp-window-config 'permanent-local t)
  244. (defvar-local org-src--source-type nil
  245. "Type of element being edited, as a symbol.")
  246. (put 'org-src--source-type 'permanent-local t)
  247. (defvar-local org-src--tab-width nil
  248. "Contains `tab-width' value from Org source buffer.
  249. However, if `indent-tabs-mode' is nil in that buffer, its value
  250. is 0.")
  251. (put 'org-src--tab-width 'permanent-local t)
  252. (defvar-local org-src-source-file-name nil
  253. "File name associated to Org source buffer, or nil.")
  254. (put 'org-src-source-file-name 'permanent-local t)
  255. (defvar-local org-src--preserve-blank-line nil)
  256. (put 'org-src--preserve-blank-line 'permanent-local t)
  257. (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
  258. "Construct the buffer name for a source editing buffer.
  259. Format is \"*Org Src ORG-BUFFER-NAME [ LANG ]*\"."
  260. (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
  261. (defun org-src--edit-buffer (beg end)
  262. "Return buffer editing area between BEG and END.
  263. Return nil if there is no such buffer."
  264. (catch 'exit
  265. (dolist (b (buffer-list))
  266. (with-current-buffer b
  267. (and (org-src-edit-buffer-p)
  268. (= beg org-src--beg-marker)
  269. (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
  270. (= end org-src--end-marker)
  271. (eq (marker-buffer end) (marker-buffer org-src--end-marker))
  272. (throw 'exit b))))))
  273. (defun org-src--coordinates (pos beg end)
  274. "Return coordinates of POS relatively to BEG and END.
  275. POS, BEG and END are buffer positions. Return value is either
  276. a cons cell (LINE . COLUMN) or symbol `end'. See also
  277. `org-src--goto-coordinates'."
  278. (if (>= pos end) 'end
  279. (org-with-wide-buffer
  280. (goto-char (max beg pos))
  281. (cons (count-lines (save-excursion (goto-char beg) (line-beginning-position))
  282. (line-beginning-position))
  283. ;; Column is relative to the end of line to avoid problems of
  284. ;; comma escaping or colons appended in front of the line.
  285. (- (point) (min end (line-end-position)))))))
  286. (defun org-src--goto-coordinates (coord beg end)
  287. "Move to coordinates COORD relatively to BEG and END.
  288. COORD are coordinates, as returned by `org-src--coordinates',
  289. which see. BEG and END are buffer positions."
  290. (goto-char
  291. (if (eq coord 'end) (max (1- end) beg)
  292. ;; If BEG happens to be located outside of the narrowed part of
  293. ;; the buffer, widen it first.
  294. (org-with-wide-buffer
  295. (goto-char beg)
  296. (forward-line (car coord))
  297. (max (point)
  298. (+ (min end (line-end-position))
  299. (cdr coord)))))))
  300. (defun org-src--contents-area (datum)
  301. "Return contents boundaries of DATUM.
  302. DATUM is an element or object. Return a list (BEG END CONTENTS)
  303. where BEG and END are buffer positions and CONTENTS is a string."
  304. (let ((type (org-element-type datum)))
  305. (org-with-wide-buffer
  306. (cond
  307. ((eq type 'footnote-definition)
  308. (let* ((beg (progn
  309. (goto-char (org-element-property :post-affiliated datum))
  310. (search-forward "]")))
  311. (end (or (org-element-property :contents-end datum) beg)))
  312. (list beg end (buffer-substring-no-properties beg end))))
  313. ((eq type 'inline-src-block)
  314. (let ((beg (progn (goto-char (org-element-property :begin datum))
  315. (search-forward "{" (line-end-position) t)))
  316. (end (progn (goto-char (org-element-property :end datum))
  317. (search-backward "}" (line-beginning-position) t))))
  318. (list beg end (buffer-substring-no-properties beg end))))
  319. ((eq type 'latex-fragment)
  320. (let ((beg (org-element-property :begin datum))
  321. (end (org-with-point-at (org-element-property :end datum)
  322. (skip-chars-backward " \t")
  323. (point))))
  324. (list beg end (buffer-substring-no-properties beg end))))
  325. ((org-element-property :contents-begin datum)
  326. (let ((beg (org-element-property :contents-begin datum))
  327. (end (org-element-property :contents-end datum)))
  328. (list beg end (buffer-substring-no-properties beg end))))
  329. ((memq type '(example-block export-block src-block comment-block))
  330. (list (progn (goto-char (org-element-property :post-affiliated datum))
  331. (line-beginning-position 2))
  332. (progn (goto-char (org-element-property :end datum))
  333. (skip-chars-backward " \r\t\n")
  334. (line-beginning-position 1))
  335. (org-element-property :value datum)))
  336. ((memq type '(fixed-width latex-environment table))
  337. (let ((beg (org-element-property :post-affiliated datum))
  338. (end (progn (goto-char (org-element-property :end datum))
  339. (skip-chars-backward " \r\t\n")
  340. (line-beginning-position 2))))
  341. (list beg
  342. end
  343. (if (eq type 'fixed-width) (org-element-property :value datum)
  344. (buffer-substring-no-properties beg end)))))
  345. (t (error "Unsupported element or object: %s" type))))))
  346. (defun org-src--make-source-overlay (beg end edit-buffer)
  347. "Create overlay between BEG and END positions and return it.
  348. EDIT-BUFFER is the buffer currently editing area between BEG and
  349. END."
  350. (let ((overlay (make-overlay beg end)))
  351. (overlay-put overlay 'face 'secondary-selection)
  352. (overlay-put overlay 'edit-buffer edit-buffer)
  353. (overlay-put overlay 'help-echo
  354. "Click with mouse-1 to switch to buffer editing this segment")
  355. (overlay-put overlay 'face 'secondary-selection)
  356. (overlay-put overlay 'keymap
  357. (let ((map (make-sparse-keymap)))
  358. (define-key map [mouse-1] 'org-edit-src-continue)
  359. map))
  360. (let ((read-only
  361. (list
  362. (lambda (&rest _)
  363. (user-error
  364. "Cannot modify an area being edited in a dedicated buffer")))))
  365. (overlay-put overlay 'modification-hooks read-only)
  366. (overlay-put overlay 'insert-in-front-hooks read-only)
  367. (overlay-put overlay 'insert-behind-hooks read-only))
  368. overlay))
  369. (defun org-src--remove-overlay ()
  370. "Remove overlay from current source buffer."
  371. (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
  372. (defun org-src--on-datum-p (datum)
  373. "Non-nil when point is on DATUM.
  374. DATUM is an element or an object. Consider blank lines or white
  375. spaces after it as being outside."
  376. (and (>= (point) (org-element-property :begin datum))
  377. (<= (point)
  378. (org-with-wide-buffer
  379. (goto-char (org-element-property :end datum))
  380. (skip-chars-backward " \r\t\n")
  381. (if (eq (org-element-class datum) 'element)
  382. (line-end-position)
  383. (point))))))
  384. (defun org-src--contents-for-write-back (write-back-buf)
  385. "Populate WRITE-BACK-BUF with contents in the appropriate format.
  386. Assume point is in the corresponding edit buffer."
  387. (let ((indentation-offset
  388. (if org-src--preserve-indentation 0
  389. (+ (or org-src--block-indentation 0)
  390. (if (memq org-src--source-type '(example-block src-block))
  391. org-src--content-indentation
  392. 0))))
  393. (use-tabs? (and (> org-src--tab-width 0) t))
  394. (preserve-fl (eq org-src--source-type 'latex-fragment))
  395. (source-tab-width org-src--tab-width)
  396. (contents (org-with-wide-buffer
  397. (let ((eol (line-end-position)))
  398. (list (buffer-substring (point-min) eol)
  399. (buffer-substring eol (point-max))))))
  400. (write-back org-src--allow-write-back)
  401. (preserve-blank-line org-src--preserve-blank-line)
  402. marker)
  403. (with-current-buffer write-back-buf
  404. ;; Reproduce indentation parameters from source buffer.
  405. (setq indent-tabs-mode use-tabs?)
  406. (when (> source-tab-width 0) (setq tab-width source-tab-width))
  407. ;; Apply WRITE-BACK function on edit buffer contents.
  408. (insert (org-no-properties (car contents)))
  409. (setq marker (point-marker))
  410. (insert (org-no-properties (car (cdr contents))))
  411. (goto-char (point-min))
  412. (when (functionp write-back) (save-excursion (funcall write-back)))
  413. ;; Add INDENTATION-OFFSET to every line in buffer,
  414. ;; unless indentation is meant to be preserved.
  415. (when (> indentation-offset 0)
  416. (when preserve-fl (forward-line))
  417. (while (not (eobp))
  418. (skip-chars-forward " \t")
  419. (when (or (not (eolp)) ; not a blank line
  420. (and (eq (point) (marker-position marker)) ; current line
  421. preserve-blank-line))
  422. (let ((i (current-column)))
  423. (delete-region (line-beginning-position) (point))
  424. (indent-to (+ i indentation-offset))))
  425. (forward-line)))
  426. (set-marker marker nil))))
  427. (defun org-src--edit-element
  428. (datum name &optional initialize write-back contents remote)
  429. "Edit DATUM contents in a dedicated buffer NAME.
  430. INITIALIZE is a function to call upon creating the buffer.
  431. When WRITE-BACK is non-nil, assume contents will replace original
  432. region. Moreover, if it is a function, apply it in the edit
  433. buffer, from point min, before returning the contents.
  434. When CONTENTS is non-nil, display them in the edit buffer.
  435. Otherwise, show DATUM contents as specified by
  436. `org-src--contents-area'.
  437. When REMOTE is non-nil, do not try to preserve point or mark when
  438. moving from the edit area to the source.
  439. Leave point in edit buffer."
  440. (when (memq org-src-window-setup '(reorganize-frame
  441. split-window-below
  442. split-window-right))
  443. (setq org-src--saved-temp-window-config (current-window-configuration)))
  444. (let* ((area (org-src--contents-area datum))
  445. (beg (copy-marker (nth 0 area)))
  446. (end (copy-marker (nth 1 area) t))
  447. (old-edit-buffer (org-src--edit-buffer beg end))
  448. (contents (or contents (nth 2 area))))
  449. (if (and old-edit-buffer
  450. (or (not org-src-ask-before-returning-to-edit-buffer)
  451. (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
  452. ;; Move to existing buffer.
  453. (org-src-switch-to-buffer old-edit-buffer 'return)
  454. ;; Discard old edit buffer.
  455. (when old-edit-buffer
  456. (with-current-buffer old-edit-buffer (org-src--remove-overlay))
  457. (kill-buffer old-edit-buffer))
  458. (let* ((org-mode-p (derived-mode-p 'org-mode))
  459. (source-file-name (buffer-file-name (buffer-base-buffer)))
  460. (source-tab-width (if indent-tabs-mode tab-width 0))
  461. (type (org-element-type datum))
  462. (block-ind (org-with-point-at (org-element-property :begin datum)
  463. (cond
  464. ((save-excursion (skip-chars-backward " \t") (bolp))
  465. (org-current-text-indentation))
  466. ((org-element-property :parent datum)
  467. (org--get-expected-indentation
  468. (org-element-property :parent datum) nil))
  469. (t (org-current-text-indentation)))))
  470. (content-ind org-edit-src-content-indentation)
  471. (blank-line (save-excursion (beginning-of-line)
  472. (looking-at-p "^[[:space:]]*$")))
  473. (empty-line (and blank-line (looking-at-p "^$")))
  474. (preserve-blank-line (or (and blank-line (not empty-line))
  475. (and empty-line (= (+ block-ind content-ind) 0))))
  476. (preserve-ind
  477. (and (memq type '(example-block src-block))
  478. (or (org-element-property :preserve-indent datum)
  479. org-src-preserve-indentation)))
  480. ;; Store relative positions of mark (if any) and point
  481. ;; within the edited area.
  482. (point-coordinates (and (not remote)
  483. (org-src--coordinates (point) beg end)))
  484. (mark-coordinates (and (not remote)
  485. (org-region-active-p)
  486. (let ((m (mark)))
  487. (and (>= m beg) (>= end m)
  488. (org-src--coordinates m beg end)))))
  489. ;; Generate a new edit buffer.
  490. (buffer (generate-new-buffer name))
  491. ;; Add an overlay on top of source.
  492. (overlay (org-src--make-source-overlay beg end buffer)))
  493. ;; Switch to edit buffer.
  494. (org-src-switch-to-buffer buffer 'edit)
  495. ;; Insert contents.
  496. (insert contents)
  497. (remove-text-properties (point-min) (point-max)
  498. '(display nil invisible nil intangible nil))
  499. (let ((lf (eq type 'latex-fragment)))
  500. (unless preserve-ind (org-do-remove-indentation (and lf block-ind) lf)))
  501. (set-buffer-modified-p nil)
  502. (setq buffer-file-name nil)
  503. ;; Initialize buffer.
  504. (when (functionp initialize)
  505. (let ((org-inhibit-startup t))
  506. (condition-case e
  507. (funcall initialize)
  508. (error (message "Initialization fails with: %S"
  509. (error-message-string e))))))
  510. ;; Transmit buffer-local variables for exit function. It must
  511. ;; be done after initializing major mode, as this operation
  512. ;; may reset them otherwise.
  513. (setq org-src--tab-width source-tab-width)
  514. (setq org-src--from-org-mode org-mode-p)
  515. (setq org-src--beg-marker beg)
  516. (setq org-src--end-marker end)
  517. (setq org-src--remote remote)
  518. (setq org-src--source-type type)
  519. (setq org-src--block-indentation block-ind)
  520. (setq org-src--content-indentation content-ind)
  521. (setq org-src--preserve-indentation preserve-ind)
  522. (setq org-src--overlay overlay)
  523. (setq org-src--allow-write-back write-back)
  524. (setq org-src-source-file-name source-file-name)
  525. (setq org-src--preserve-blank-line preserve-blank-line)
  526. ;; Start minor mode.
  527. (org-src-mode)
  528. ;; Clear undo information so we cannot undo back to the
  529. ;; initial empty buffer.
  530. (buffer-disable-undo (current-buffer))
  531. (buffer-enable-undo)
  532. ;; Move mark and point in edit buffer to the corresponding
  533. ;; location.
  534. (if remote
  535. (progn
  536. ;; Put point at first non read-only character after
  537. ;; leading blank.
  538. (goto-char
  539. (or (text-property-any (point-min) (point-max) 'read-only nil)
  540. (point-max)))
  541. (skip-chars-forward " \r\t\n"))
  542. ;; Set mark and point.
  543. (when mark-coordinates
  544. (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
  545. (push-mark (point) 'no-message t)
  546. (setq deactivate-mark nil))
  547. (org-src--goto-coordinates
  548. point-coordinates (point-min) (point-max)))))))
  549. ;;; Fontification of source blocks
  550. (defvar org-src-fontify-natively) ; Defined in org.el
  551. (defun org-src-font-lock-fontify-block (lang start end)
  552. "Fontify code block between START and END using LANG's syntax.
  553. This function is called by Emacs' automatic fontification, as long
  554. as `org-src-fontify-natively' is non-nil."
  555. (let ((lang-mode (org-src-get-lang-mode lang)))
  556. (when (fboundp lang-mode)
  557. (let ((string (buffer-substring-no-properties start end))
  558. (modified (buffer-modified-p))
  559. (org-buffer (current-buffer)))
  560. (remove-text-properties start end '(face nil))
  561. (with-current-buffer
  562. (get-buffer-create
  563. (format " *org-src-fontification:%s*" lang-mode))
  564. (let ((inhibit-modification-hooks nil))
  565. (erase-buffer)
  566. ;; Add string and a final space to ensure property change.
  567. (insert string " "))
  568. (unless (eq major-mode lang-mode) (funcall lang-mode))
  569. (font-lock-ensure)
  570. (let ((pos (point-min)) next)
  571. (while (setq next (next-property-change pos))
  572. ;; Handle additional properties from font-lock, so as to
  573. ;; preserve, e.g., composition.
  574. ;; FIXME: We copy 'font-lock-face property explicitly because
  575. ;; `font-lock-mode' is not enabled in the buffers starting from
  576. ;; space and the remapping between 'font-lock-face and 'face
  577. ;; text properties may thus not be set. See commit
  578. ;; 453d634bc.
  579. (dolist (prop (append '(font-lock-face face) font-lock-extra-managed-props))
  580. (let ((new-prop (get-text-property pos prop)))
  581. (when new-prop
  582. (if (not (eq prop 'invisible))
  583. (put-text-property
  584. (+ start (1- pos)) (1- (+ start next)) prop new-prop
  585. org-buffer)
  586. ;; Special case. `invisible' text property may
  587. ;; clash with Org folding. Do not assign
  588. ;; `invisible' text property directly. Use
  589. ;; property alias instead.
  590. (let ((invisibility-spec
  591. (or
  592. ;; ATOM spec.
  593. (and (memq new-prop buffer-invisibility-spec)
  594. new-prop)
  595. ;; (ATOM . ELLIPSIS) spec.
  596. (assq new-prop buffer-invisibility-spec))))
  597. (with-current-buffer org-buffer
  598. ;; Add new property alias.
  599. (unless (memq 'org-src-invisible
  600. (cdr (assq 'invisible char-property-alias-alist)))
  601. (setq-local
  602. char-property-alias-alist
  603. (cons (cons 'invisible
  604. (nconc (cdr (assq 'invisible char-property-alias-alist))
  605. '(org-src-invisible)))
  606. (remove (assq 'invisible char-property-alias-alist)
  607. char-property-alias-alist))))
  608. ;; Carry over the invisibility spec, unless
  609. ;; already present. Note that there might
  610. ;; be conflicting invisibility specs from
  611. ;; different major modes. We cannot do much
  612. ;; about this then.
  613. (when invisibility-spec
  614. (add-to-invisibility-spec invisibility-spec))
  615. (put-text-property
  616. (+ start (1- pos)) (1- (+ start next))
  617. 'org-src-invisible new-prop
  618. org-buffer)))))))
  619. (setq pos next)))
  620. (set-buffer-modified-p nil))
  621. ;; Add Org faces.
  622. (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
  623. (when (or (facep src-face) (listp src-face))
  624. (font-lock-append-text-property start end 'face src-face))
  625. (font-lock-append-text-property start end 'face 'org-block))
  626. (add-text-properties
  627. start end
  628. '(font-lock-fontified t fontified t font-lock-multiline t))
  629. (set-buffer-modified-p modified)))))
  630. (defun org-fontify-inline-src-blocks (limit)
  631. "Try to apply `org-fontify-inline-src-blocks-1'."
  632. (condition-case nil
  633. (org-fontify-inline-src-blocks-1 limit)
  634. (error (message "Org mode fontification error in %S at %d"
  635. (current-buffer)
  636. (line-number-at-pos)))))
  637. (defun org-fontify-inline-src-blocks-1 (limit)
  638. "Fontify inline src_LANG blocks, from `point' up to LIMIT."
  639. (let ((case-fold-search t))
  640. ;; The regexp below is copied from `org-element-inline-src-block-parser'.
  641. (while (re-search-forward "\\_<src_\\([^ \t\n[{]+\\)[{[]?" limit t)
  642. (let ((beg (match-beginning 0))
  643. (lang-beg (match-beginning 1))
  644. (lang-end (match-end 1))
  645. pt)
  646. (font-lock-append-text-property
  647. lang-beg lang-end 'face 'org-meta-line)
  648. (font-lock-append-text-property
  649. beg lang-beg 'face 'shadow)
  650. (font-lock-append-text-property
  651. beg lang-end 'face 'org-inline-src-block)
  652. (setq pt (goto-char lang-end))
  653. ;; `org-element--parse-paired-brackets' doesn't take a limit, so to
  654. ;; prevent it searching the entire rest of the buffer we temporarily
  655. ;; narrow the active region.
  656. (save-restriction
  657. (narrow-to-region beg
  658. (min limit (or (save-excursion
  659. (and (search-forward"\n" limit t 2)
  660. (point)))
  661. (point-max))))
  662. (when (ignore-errors (org-element--parse-paired-brackets ?\[))
  663. (font-lock-append-text-property
  664. pt (point) 'face 'org-inline-src-block)
  665. (setq pt (point)))
  666. (when (ignore-errors (org-element--parse-paired-brackets ?\{))
  667. (remove-text-properties pt (point) '(face nil))
  668. (font-lock-append-text-property
  669. pt (1+ pt) 'face '(org-inline-src-block shadow))
  670. (unless (= (1+ pt) (1- (point)))
  671. (if org-src-fontify-natively
  672. (org-src-font-lock-fontify-block
  673. (buffer-substring-no-properties lang-beg lang-end)
  674. (1+ pt) (1- (point)))
  675. (font-lock-append-text-property
  676. (1+ pt) (1- (point)) 'face 'org-inline-src-block)))
  677. (font-lock-append-text-property
  678. (1- (point)) (point) 'face '(org-inline-src-block shadow))
  679. (setq pt (point)))))
  680. t)))
  681. ;;; Escape contents
  682. (defun org-escape-code-in-region (beg end)
  683. "Escape lines between BEG and END.
  684. Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
  685. \",#+\" by appending a comma to it."
  686. (interactive "r")
  687. (save-excursion
  688. (goto-char end)
  689. (while (re-search-backward "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" beg t)
  690. (save-excursion (replace-match ",\\1" nil nil nil 1)))))
  691. (defun org-escape-code-in-string (s)
  692. "Escape lines in string S.
  693. Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
  694. \",#+\" by appending a comma to it."
  695. (replace-regexp-in-string "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" ",\\1"
  696. s nil nil 1))
  697. (defun org-unescape-code-in-region (beg end)
  698. "Un-escape lines between BEG and END.
  699. Un-escaping happens by removing the first comma on lines starting
  700. with \",*\", \",#+\", \",,*\" and \",,#+\"."
  701. (interactive "r")
  702. (save-excursion
  703. (goto-char end)
  704. (while (re-search-backward "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
  705. (save-excursion (replace-match "" nil nil nil 1)))))
  706. (defun org-unescape-code-in-string (s)
  707. "Un-escape lines in string S.
  708. Un-escaping happens by removing the first comma on lines starting
  709. with \",*\", \",#+\", \",,*\" and \",,#+\"."
  710. (replace-regexp-in-string
  711. "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
  712. ;;; Org src minor mode
  713. (defvar org-src-mode-map
  714. (let ((map (make-sparse-keymap)))
  715. (define-key map "\C-c'" 'org-edit-src-exit)
  716. (define-key map "\C-c\C-k" 'org-edit-src-abort)
  717. (define-key map "\C-x\C-s" 'org-edit-src-save)
  718. map))
  719. (define-minor-mode org-src-mode
  720. "Minor mode for language major mode buffers generated by Org.
  721. \\<org-mode-map>
  722. This minor mode is turned on in two situations:
  723. - when editing a source code snippet with `\\[org-edit-special]'
  724. - when formatting a source code snippet for export with htmlize.
  725. \\{org-src-mode-map}
  726. See also `org-src-mode-hook'."
  727. :lighter " OrgSrc"
  728. (when org-edit-src-persistent-message
  729. (setq header-line-format
  730. (substitute-command-keys
  731. (if org-src--allow-write-back
  732. "Edit, then exit with `\\[org-edit-src-exit]' or abort with \
  733. `\\[org-edit-src-abort]'"
  734. "Exit with `\\[org-edit-src-exit]' or abort with \
  735. `\\[org-edit-src-abort]'"))))
  736. ;; Possibly activate various auto-save features (for the edit buffer
  737. ;; or the source buffer).
  738. (when org-edit-src-turn-on-auto-save
  739. (setq buffer-auto-save-file-name
  740. (concat (make-temp-name "org-src-")
  741. (format-time-string "-%Y-%d-%m")
  742. ".txt")))
  743. (unless (or org-src--auto-save-timer
  744. (= 0 org-edit-src-auto-save-idle-delay))
  745. (setq org-src--auto-save-timer
  746. (run-with-idle-timer
  747. org-edit-src-auto-save-idle-delay t
  748. (lambda ()
  749. (save-excursion
  750. (let (edit-flag)
  751. (dolist (b (buffer-list))
  752. (with-current-buffer b
  753. (when (org-src-edit-buffer-p)
  754. (unless edit-flag (setq edit-flag t))
  755. (when (buffer-modified-p) (org-edit-src-save)))))
  756. (unless edit-flag
  757. (cancel-timer org-src--auto-save-timer)
  758. (setq org-src--auto-save-timer nil)))))))))
  759. (defun org-src-mode-configure-edit-buffer ()
  760. "Configure the src edit buffer."
  761. (when (bound-and-true-p org-src--from-org-mode)
  762. (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
  763. (if (bound-and-true-p org-src--allow-write-back)
  764. (progn
  765. (setq buffer-offer-save t)
  766. (setq write-contents-functions '(org-edit-src-save)))
  767. (setq buffer-read-only t))))
  768. (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
  769. ;;; Babel related functions
  770. (defun org-src-associate-babel-session (info)
  771. "Associate edit buffer with comint session.
  772. INFO should be a list similar in format to the return value of
  773. `org-babel-get-src-block-info'."
  774. (interactive)
  775. (let ((session (cdr (assq :session (nth 2 info)))))
  776. (and session (not (string= session "none"))
  777. (org-babel-comint-buffer-livep session)
  778. (let ((f (intern (format "org-babel-%s-associate-session"
  779. (nth 0 info)))))
  780. (and (fboundp f) (funcall f session))))))
  781. (defun org-src-babel-configure-edit-buffer ()
  782. "Configure src editing buffer."
  783. (when org-src--babel-info
  784. (org-src-associate-babel-session org-src--babel-info)))
  785. (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
  786. ;;; Public API
  787. (defmacro org-src-do-at-code-block (&rest body)
  788. "Execute BODY from an edit buffer in the Org mode buffer."
  789. (declare (debug (body)))
  790. `(let ((beg-marker org-src--beg-marker))
  791. (when beg-marker
  792. (with-current-buffer (marker-buffer beg-marker)
  793. (goto-char beg-marker)
  794. ,@body))))
  795. (defun org-src-do-key-sequence-at-code-block (&optional key)
  796. "Execute key sequence at code block in the source Org buffer.
  797. The command bound to KEY in the Org-babel key map is executed
  798. remotely with point temporarily at the start of the code block in
  799. the Org buffer.
  800. This command is not bound to a key by default, to avoid conflicts
  801. with language major mode bindings. To bind it to C-c @ in all
  802. language major modes, you could use
  803. (add-hook \\='org-src-mode-hook
  804. (lambda () (define-key org-src-mode-map \"\\C-c@\"
  805. \\='org-src-do-key-sequence-at-code-block)))
  806. In that case, for example, C-c @ t issued in code edit buffers
  807. would tangle the current Org code block, C-c @ e would execute
  808. the block and C-c @ h would display the other available
  809. Org-babel commands."
  810. (interactive "kOrg-babel key: ")
  811. (if (equal key (kbd "C-g")) (keyboard-quit)
  812. (org-edit-src-save)
  813. (org-src-do-at-code-block
  814. (call-interactively (lookup-key org-babel-map key)))))
  815. (defun org-src-get-lang-mode (lang)
  816. "Return major mode that should be used for LANG.
  817. LANG is a string, and the returned major mode is a symbol."
  818. (intern
  819. (concat
  820. (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
  821. (if (symbolp l) (symbol-name l) l))
  822. "-mode")))
  823. (defun org-src-edit-buffer-p (&optional buffer)
  824. "Non-nil when current buffer is a source editing buffer.
  825. If BUFFER is non-nil, test it instead."
  826. (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
  827. (and (buffer-live-p buffer)
  828. (local-variable-p 'org-src--beg-marker buffer)
  829. (local-variable-p 'org-src--end-marker buffer))))
  830. (defun org-src-source-buffer ()
  831. "Return source buffer edited in current buffer.
  832. Raise an error when current buffer is not a source editing buffer."
  833. (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
  834. (or (marker-buffer org-src--beg-marker)
  835. (error "No source buffer available for current editing session")))
  836. (defun org-src-source-type ()
  837. "Return type of element edited in current buffer.
  838. Raise an error when current buffer is not a source editing buffer."
  839. (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
  840. org-src--source-type)
  841. (defun org-src-switch-to-buffer (buffer context)
  842. "Switch to BUFFER considering CONTEXT and `org-src-window-setup'."
  843. (pcase org-src-window-setup
  844. (`plain
  845. (when (eq context 'exit) (quit-restore-window))
  846. (pop-to-buffer buffer))
  847. (`current-window (pop-to-buffer-same-window buffer))
  848. (`other-window
  849. (let ((cur-win (selected-window)))
  850. (org-switch-to-buffer-other-window buffer)
  851. (when (eq context 'exit) (quit-restore-window cur-win))))
  852. (`split-window-below
  853. (if (eq context 'exit)
  854. (delete-window)
  855. (select-window (split-window-vertically)))
  856. (pop-to-buffer-same-window buffer))
  857. (`split-window-right
  858. (if (eq context 'exit)
  859. (delete-window)
  860. (select-window (split-window-horizontally)))
  861. (pop-to-buffer-same-window buffer))
  862. (`other-frame
  863. (pcase context
  864. (`exit
  865. (let ((frame (selected-frame)))
  866. (switch-to-buffer-other-frame buffer)
  867. (delete-frame frame)))
  868. (`save
  869. (kill-buffer (current-buffer))
  870. (pop-to-buffer-same-window buffer))
  871. (_ (switch-to-buffer-other-frame buffer))))
  872. (`reorganize-frame
  873. (when (eq context 'edit) (delete-other-windows))
  874. (org-switch-to-buffer-other-window buffer)
  875. (when (eq context 'exit) (delete-other-windows)))
  876. (`switch-invisibly (set-buffer buffer))
  877. (_
  878. (message "Invalid value %s for `org-src-window-setup'"
  879. org-src-window-setup)
  880. (pop-to-buffer-same-window buffer))))
  881. (defun org-src-coderef-format (&optional element)
  882. "Return format string for block at point.
  883. When optional argument ELEMENT is provided, use that block.
  884. Otherwise, assume point is either at a source block, at an
  885. example block.
  886. If point is in an edit buffer, retrieve format string associated
  887. to the remote source block."
  888. (cond
  889. ((and element (org-element-property :label-fmt element)))
  890. ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
  891. ((org-element-property :label-fmt (org-element-at-point)))
  892. (t org-coderef-label-format)))
  893. (defun org-src-coderef-regexp (fmt &optional label)
  894. "Return regexp matching a coderef format string FMT.
  895. When optional argument LABEL is non-nil, match coderef for that
  896. label only.
  897. Match group 1 contains the full coderef string with surrounding
  898. white spaces. Match group 2 contains the same string without any
  899. surrounding space. Match group 3 contains the label.
  900. A coderef format regexp can only match at the end of a line."
  901. (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
  902. (replace-regexp-in-string
  903. "%s"
  904. (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
  905. (regexp-quote fmt)
  906. nil t)))
  907. (defun org-edit-footnote-reference ()
  908. "Edit definition of footnote reference at point."
  909. (interactive)
  910. (let* ((context (org-element-context))
  911. (label (org-element-property :label context)))
  912. (unless (and (eq (org-element-type context) 'footnote-reference)
  913. (org-src--on-datum-p context))
  914. (user-error "Not on a footnote reference"))
  915. (unless label (user-error "Cannot edit remotely anonymous footnotes"))
  916. (let* ((definition (org-with-wide-buffer
  917. (org-footnote-goto-definition label)
  918. (backward-char)
  919. (org-element-context)))
  920. (inline? (eq 'footnote-reference (org-element-type definition)))
  921. (contents
  922. (org-with-wide-buffer
  923. (buffer-substring-no-properties
  924. (or (org-element-property :post-affiliated definition)
  925. (org-element-property :begin definition))
  926. (cond
  927. (inline? (1+ (org-element-property :contents-end definition)))
  928. ((org-element-property :contents-end definition))
  929. (t (goto-char (org-element-property :post-affiliated definition))
  930. (line-end-position)))))))
  931. (add-text-properties
  932. 0
  933. (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
  934. (match-end 0))
  935. '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
  936. contents)
  937. (when inline?
  938. (let ((l (length contents)))
  939. (add-text-properties
  940. (1- l) l
  941. '(read-only "Cannot edit past footnote reference"
  942. front-sticky nil rear-nonsticky nil)
  943. contents)))
  944. (org-src--edit-element
  945. definition
  946. (format "*Edit footnote [%s]*" label)
  947. (let ((source (current-buffer)))
  948. (lambda ()
  949. (org-mode)
  950. (org-clone-local-variables source)))
  951. (lambda ()
  952. (if (not inline?) (delete-region (point) (search-forward "]"))
  953. (delete-region (point) (search-forward ":" nil t 2))
  954. (delete-region (1- (point-max)) (point-max))
  955. (when (re-search-forward "\n[ \t]*\n" nil t)
  956. (user-error "Inline definitions cannot contain blank lines"))
  957. ;; If footnote reference belongs to a table, make sure to
  958. ;; remove any newline characters in order to preserve
  959. ;; table's structure.
  960. (when (org-element-lineage definition '(table-cell))
  961. (while (search-forward "\n" nil t) (replace-match " ")))))
  962. contents
  963. 'remote))
  964. ;; Report success.
  965. t))
  966. (defun org-edit-table.el ()
  967. "Edit \"table.el\" table at point.
  968. \\<org-src-mode-map>
  969. A new buffer is created and the table is copied into it. Then
  970. the table is recognized with `table-recognize'. When done
  971. editing, exit with `\\[org-edit-src-exit]'. The edited text will \
  972. then replace
  973. the area in the Org mode buffer.
  974. Throw an error when not at such a table."
  975. (interactive)
  976. (let ((element (org-element-at-point)))
  977. (unless (and (eq (org-element-type element) 'table)
  978. (eq (org-element-property :type element) 'table.el)
  979. (org-src--on-datum-p element))
  980. (user-error "Not in a table.el table"))
  981. (org-src--edit-element
  982. element
  983. (org-src--construct-edit-buffer-name (buffer-name) "Table")
  984. #'text-mode t)
  985. (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
  986. (table-recognize)
  987. t))
  988. (defun org-edit-latex-fragment ()
  989. "Edit LaTeX fragment at point."
  990. (interactive)
  991. (let ((context (org-element-context)))
  992. (unless (and (eq 'latex-fragment (org-element-type context))
  993. (org-src--on-datum-p context))
  994. (user-error "Not on a LaTeX fragment"))
  995. (let* ((contents
  996. (buffer-substring-no-properties
  997. (org-element-property :begin context)
  998. (- (org-element-property :end context)
  999. (org-element-property :post-blank context))))
  1000. (delim-length (if (string-match "\\`\\$[^$]" contents) 1 2)))
  1001. ;; Make the LaTeX deliminators read-only.
  1002. (add-text-properties 0 delim-length
  1003. (list 'read-only "Cannot edit LaTeX deliminator"
  1004. 'front-sticky t
  1005. 'rear-nonsticky t)
  1006. contents)
  1007. (let ((l (length contents)))
  1008. (add-text-properties (- l delim-length) l
  1009. (list 'read-only "Cannot edit LaTeX deliminator"
  1010. 'front-sticky nil
  1011. 'rear-nonsticky nil)
  1012. contents))
  1013. (org-src--edit-element
  1014. context
  1015. (org-src--construct-edit-buffer-name (buffer-name) "LaTeX fragment")
  1016. (org-src-get-lang-mode "latex")
  1017. (lambda ()
  1018. ;; Blank lines break things, replace with a single newline.
  1019. (while (re-search-forward "\n[ \t]*\n" nil t) (replace-match "\n"))
  1020. ;; If within a table a newline would disrupt the structure,
  1021. ;; so remove newlines.
  1022. (goto-char (point-min))
  1023. (when (org-element-lineage context '(table-cell))
  1024. (while (search-forward "\n" nil t) (replace-match " "))))
  1025. contents))
  1026. t))
  1027. (defun org-edit-latex-environment ()
  1028. "Edit LaTeX environment at point.
  1029. \\<org-src-mode-map>
  1030. The LaTeX environment is copied into a new buffer. Major mode is
  1031. set to the one associated to \"latex\" in `org-src-lang-modes',
  1032. or to `latex-mode' if there is none.
  1033. When done, exit with `\\[org-edit-src-exit]'. The edited text \
  1034. will then replace
  1035. the LaTeX environment in the Org mode buffer."
  1036. (interactive)
  1037. (let ((element (org-element-at-point)))
  1038. (unless (and (eq (org-element-type element) 'latex-environment)
  1039. (org-src--on-datum-p element))
  1040. (user-error "Not in a LaTeX environment"))
  1041. (org-src--edit-element
  1042. element
  1043. (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
  1044. (org-src-get-lang-mode "latex")
  1045. t)
  1046. t))
  1047. (defun org-edit-export-block ()
  1048. "Edit export block at point.
  1049. \\<org-src-mode-map>
  1050. A new buffer is created and the block is copied into it, and the
  1051. buffer is switched into an appropriate major mode. See also
  1052. `org-src-lang-modes'.
  1053. When done, exit with `\\[org-edit-src-exit]'. The edited text \
  1054. will then replace
  1055. the area in the Org mode buffer.
  1056. Throw an error when not at an export block."
  1057. (interactive)
  1058. (let ((element (org-element-at-point)))
  1059. (unless (and (eq (org-element-type element) 'export-block)
  1060. (org-src--on-datum-p element))
  1061. (user-error "Not in an export block"))
  1062. (let* ((type (downcase (or (org-element-property :type element)
  1063. ;; Missing export-block type. Fallback
  1064. ;; to default mode.
  1065. "fundamental")))
  1066. (mode (org-src-get-lang-mode type)))
  1067. (unless (functionp mode) (error "No such language mode: %s" mode))
  1068. (org-src--edit-element
  1069. element
  1070. (org-src--construct-edit-buffer-name (buffer-name) type)
  1071. mode
  1072. (lambda () (org-escape-code-in-region (point-min) (point-max)))))
  1073. t))
  1074. (defun org-edit-comment-block ()
  1075. "Edit comment block at point.
  1076. \\<org-src-mode-map>
  1077. A new buffer is created and the block is copied into it, and the
  1078. buffer is switched into Org mode.
  1079. When done, exit with `\\[org-edit-src-exit]'. The edited text will
  1080. then replace the area in the Org mode buffer.
  1081. Throw an error when not at a comment block."
  1082. (interactive)
  1083. (let ((element (org-element-at-point)))
  1084. (unless (and (eq (org-element-type element) 'comment-block)
  1085. (org-src--on-datum-p element))
  1086. (user-error "Not in a comment block"))
  1087. (org-src--edit-element
  1088. element
  1089. (org-src--construct-edit-buffer-name (buffer-name) "org")
  1090. 'org-mode
  1091. (lambda () (org-escape-code-in-region (point-min) (point-max)))
  1092. (org-unescape-code-in-string (org-element-property :value element)))
  1093. t))
  1094. (defun org-edit-src-code (&optional code edit-buffer-name)
  1095. "Edit the source or example block at point.
  1096. \\<org-src-mode-map>
  1097. The code is copied to a separate buffer and the appropriate mode
  1098. is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
  1099. will remove the
  1100. original code in the Org buffer, and replace it with the edited
  1101. version. See `org-src-window-setup' to configure the display of
  1102. windows containing the Org buffer and the code buffer.
  1103. When optional argument CODE is a string, edit it in a dedicated
  1104. buffer instead.
  1105. When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
  1106. name of the sub-editing buffer."
  1107. (interactive)
  1108. (let* ((element (org-element-at-point))
  1109. (type (org-element-type element)))
  1110. (unless (and (memq type '(example-block src-block))
  1111. (org-src--on-datum-p element))
  1112. (user-error "Not in a source or example block"))
  1113. (let* ((lang
  1114. (if (eq type 'src-block) (org-element-property :language element)
  1115. "example"))
  1116. (lang-f (and (eq type 'src-block) (org-src-get-lang-mode lang)))
  1117. (babel-info (and (eq type 'src-block)
  1118. (org-babel-get-src-block-info 'light)))
  1119. deactivate-mark)
  1120. (when (and (eq type 'src-block) (not (functionp lang-f)))
  1121. (error "No such language mode: %s" lang-f))
  1122. (org-src--edit-element
  1123. element
  1124. (or edit-buffer-name
  1125. (org-src--construct-edit-buffer-name (buffer-name) lang))
  1126. lang-f
  1127. (and (null code)
  1128. (lambda () (org-escape-code-in-region (point-min) (point-max))))
  1129. (and code (org-unescape-code-in-string code)))
  1130. ;; Finalize buffer.
  1131. (setq-local org-coderef-label-format
  1132. (or (org-element-property :label-fmt element)
  1133. org-coderef-label-format))
  1134. (when (eq type 'src-block)
  1135. (setq org-src--babel-info babel-info)
  1136. (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
  1137. (when (fboundp edit-prep-func)
  1138. (funcall edit-prep-func babel-info))))
  1139. t)))
  1140. (defun org-edit-inline-src-code ()
  1141. "Edit inline source code at point."
  1142. (interactive)
  1143. (let ((context (org-element-context)))
  1144. (unless (and (eq (org-element-type context) 'inline-src-block)
  1145. (org-src--on-datum-p context))
  1146. (user-error "Not on inline source code"))
  1147. (let* ((lang (org-element-property :language context))
  1148. (lang-f (org-src-get-lang-mode lang))
  1149. (babel-info (org-babel-get-src-block-info 'light))
  1150. deactivate-mark)
  1151. (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
  1152. (org-src--edit-element
  1153. context
  1154. (org-src--construct-edit-buffer-name (buffer-name) lang)
  1155. lang-f
  1156. (lambda ()
  1157. ;; Inline source blocks are limited to one line.
  1158. (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
  1159. ;; Trim contents.
  1160. (goto-char (point-min))
  1161. (skip-chars-forward " \t")
  1162. (delete-region (point-min) (point))
  1163. (goto-char (point-max))
  1164. (skip-chars-backward " \t")
  1165. (delete-region (point) (point-max))))
  1166. ;; Finalize buffer.
  1167. (setq org-src--babel-info babel-info)
  1168. (setq org-src--preserve-indentation t)
  1169. (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
  1170. (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
  1171. ;; Return success.
  1172. t)))
  1173. (defun org-edit-fixed-width-region ()
  1174. "Edit the fixed-width ASCII drawing at point.
  1175. \\<org-src-mode-map>
  1176. This must be a region where each line starts with a colon
  1177. followed by a space or a newline character.
  1178. A new buffer is created and the fixed-width region is copied into
  1179. it, and the buffer is switched into the major mode defined in
  1180. `org-edit-fixed-width-region-mode', which see.
  1181. When done, exit with `\\[org-edit-src-exit]'. The edited text \
  1182. will then replace
  1183. the area in the Org mode buffer."
  1184. (interactive)
  1185. (let ((element (org-element-at-point)))
  1186. (unless (and (eq (org-element-type element) 'fixed-width)
  1187. (org-src--on-datum-p element))
  1188. (user-error "Not in a fixed-width area"))
  1189. (org-src--edit-element
  1190. element
  1191. (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
  1192. org-edit-fixed-width-region-mode
  1193. (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
  1194. ;; Return success.
  1195. t))
  1196. (defun org-edit-src-abort ()
  1197. "Abort editing of the src code and return to the Org buffer."
  1198. (interactive)
  1199. (let (org-src--allow-write-back) (org-edit-src-exit)))
  1200. (defun org-edit-src-continue (event)
  1201. "Unconditionally return to buffer editing area under point.
  1202. Throw an error if there is no such buffer.
  1203. EVENT is passed to `mouse-set-point'."
  1204. (interactive "e")
  1205. (mouse-set-point event)
  1206. (let ((buf (get-char-property (point) 'edit-buffer)))
  1207. (if buf (org-src-switch-to-buffer buf 'continue)
  1208. (user-error "No sub-editing buffer for area at point"))))
  1209. (defun org-edit-src-save ()
  1210. "Save parent buffer with current state source-code buffer."
  1211. (interactive)
  1212. (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
  1213. (set-buffer-modified-p nil)
  1214. (let ((write-back-buf (generate-new-buffer "*org-src-write-back*"))
  1215. (beg org-src--beg-marker)
  1216. (end org-src--end-marker)
  1217. (overlay org-src--overlay))
  1218. (org-src--contents-for-write-back write-back-buf)
  1219. (with-current-buffer (org-src-source-buffer)
  1220. (undo-boundary)
  1221. (goto-char beg)
  1222. ;; Temporarily disable read-only features of OVERLAY in order to
  1223. ;; insert new contents.
  1224. (delete-overlay overlay)
  1225. (let ((expecting-bol (bolp)))
  1226. (if (version< emacs-version "27.1")
  1227. (progn (delete-region beg end)
  1228. (insert (with-current-buffer write-back-buf (buffer-string))))
  1229. (save-restriction
  1230. (narrow-to-region beg end)
  1231. (org-replace-buffer-contents write-back-buf 0.1 nil)
  1232. (goto-char (point-max))))
  1233. (when (and expecting-bol (not (bolp))) (insert "\n")))
  1234. (kill-buffer write-back-buf)
  1235. (save-buffer)
  1236. (move-overlay overlay beg (point))))
  1237. ;; `write-contents-functions' requires the function to return
  1238. ;; a non-nil value so that other functions are not called.
  1239. t)
  1240. (defun org-edit-src-exit ()
  1241. "Kill current sub-editing buffer and return to source buffer."
  1242. (interactive)
  1243. (unless (org-src-edit-buffer-p)
  1244. (error "Not in a sub-editing buffer"))
  1245. (let* ((beg org-src--beg-marker)
  1246. (end org-src--end-marker)
  1247. (write-back org-src--allow-write-back)
  1248. (remote org-src--remote)
  1249. (coordinates (and (not remote)
  1250. (org-src--coordinates (point) 1 (point-max))))
  1251. (write-back-buf
  1252. (and write-back (generate-new-buffer "*org-src-write-back*"))))
  1253. (when write-back (org-src--contents-for-write-back write-back-buf))
  1254. (set-buffer-modified-p nil)
  1255. ;; Switch to source buffer. Kill sub-editing buffer.
  1256. (let ((edit-buffer (current-buffer))
  1257. (source-buffer (marker-buffer beg)))
  1258. (unless source-buffer
  1259. (when write-back-buf (kill-buffer write-back-buf))
  1260. (error "Source buffer disappeared. Aborting"))
  1261. (org-src-switch-to-buffer source-buffer 'exit)
  1262. (kill-buffer edit-buffer))
  1263. ;; Insert modified code. Ensure it ends with a newline character.
  1264. (org-with-wide-buffer
  1265. (when (and write-back
  1266. (not (equal (buffer-substring beg end)
  1267. (with-current-buffer write-back-buf
  1268. (buffer-string)))))
  1269. (undo-boundary)
  1270. (goto-char beg)
  1271. (let ((expecting-bol (bolp)))
  1272. (if (version< emacs-version "27.1")
  1273. (progn (delete-region beg end)
  1274. (insert (with-current-buffer write-back-buf
  1275. (buffer-string))))
  1276. (save-restriction
  1277. (narrow-to-region beg end)
  1278. (org-replace-buffer-contents write-back-buf 0.1 nil)
  1279. (goto-char (point-max))))
  1280. (when (and expecting-bol (not (bolp))) (insert "\n")))))
  1281. (when write-back-buf (kill-buffer write-back-buf))
  1282. ;; If we are to return to source buffer, put point at an
  1283. ;; appropriate location. In particular, if block is hidden, move
  1284. ;; to the beginning of the block opening line.
  1285. (unless remote
  1286. (goto-char beg)
  1287. (cond
  1288. ;; Block is hidden; move at start of block.
  1289. ((if (eq org-fold-core-style 'text-properties)
  1290. (org-fold-folded-p nil 'block)
  1291. (cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
  1292. (overlays-at (point))))
  1293. (beginning-of-line 0))
  1294. (write-back (org-src--goto-coordinates coordinates beg end))))
  1295. ;; Clean up left-over markers and restore window configuration.
  1296. (set-marker beg nil)
  1297. (set-marker end nil)
  1298. (when org-src--saved-temp-window-config
  1299. (unwind-protect
  1300. (set-window-configuration org-src--saved-temp-window-config)
  1301. (setq org-src--saved-temp-window-config nil)))))
  1302. (provide 'org-src)
  1303. ;;; org-src.el ends here