org-src.el 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. ;;; org-src.el --- Source code examples in Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  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. ;; Homepage: 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 'cl-lib)
  30. (require 'org-macs)
  31. (require 'org-compat)
  32. (require 'ob-keys)
  33. (require 'ob-comint)
  34. (declare-function org-base-buffer "org" (buffer))
  35. (declare-function org-do-remove-indentation "org" (&optional n))
  36. (declare-function org-element-at-point "org-element" ())
  37. (declare-function org-element-class "org-element" (datum &optional parent))
  38. (declare-function org-element-context "org-element" (&optional element))
  39. (declare-function org-element-lineage "org-element"
  40. (blob &optional types with-self))
  41. (declare-function org-element-property "org-element" (property element))
  42. (declare-function org-element-type "org-element" (element))
  43. (declare-function org-footnote-goto-definition "org-footnote"
  44. (label &optional location))
  45. (declare-function org-get-indentation "org" (&optional line))
  46. (declare-function org-switch-to-buffer-other-window "org" (&rest args))
  47. (declare-function org-trim "org" (s &optional keep-lead))
  48. (defvar org-inhibit-startup)
  49. (defcustom org-edit-src-turn-on-auto-save nil
  50. "Non-nil means turn `auto-save-mode' on when editing a source block.
  51. This will save the content of the source code editing buffer into
  52. a newly created file, not the base buffer for this source block.
  53. If you want to regularly save the base buffer instead of the source
  54. code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
  55. :group 'org-edit-structure
  56. :version "24.4"
  57. :package-version '(Org . "8.0")
  58. :type 'boolean)
  59. (defcustom org-edit-src-auto-save-idle-delay 0
  60. "Delay before saving a source code buffer back into its base buffer.
  61. When a positive integer N, save after N seconds of idle time.
  62. When 0 (the default), don't auto-save.
  63. If you want to save the source code buffer itself, don't use this.
  64. Check `org-edit-src-turn-on-auto-save' instead."
  65. :group 'org-edit-structure
  66. :version "24.4"
  67. :package-version '(Org . "8.0")
  68. :type 'integer)
  69. (defcustom org-coderef-label-format "(ref:%s)"
  70. "The default coderef format.
  71. This format string will be used to search for coderef labels in literal
  72. examples (EXAMPLE and SRC blocks). The format can be overwritten in
  73. an individual literal example with the -l option, like
  74. #+BEGIN_SRC pascal +n -r -l \"((%s))\"
  75. ...
  76. #+END_SRC
  77. If you want to use this for HTML export, make sure that the format does
  78. not introduce special font-locking, and avoid the HTML special
  79. characters `<', `>', and `&'. The reason for this restriction is that
  80. the labels are searched for only after htmlize has done its job."
  81. :group 'org-edit-structure ; FIXME this is not in the right group
  82. :type 'string)
  83. (defcustom org-edit-fixed-width-region-mode 'artist-mode
  84. "The mode that should be used to edit fixed-width regions.
  85. These are the regions where each line starts with a colon."
  86. :group 'org-edit-structure
  87. :type '(choice
  88. (const artist-mode)
  89. (const picture-mode)
  90. (const fundamental-mode)
  91. (function :tag "Other (specify)")))
  92. (defcustom org-src-preserve-indentation nil
  93. "If non-nil preserve leading whitespace characters on export.
  94. \\<org-mode-map>
  95. If non-nil leading whitespace characters in source code blocks
  96. are preserved on export, and when switching between the org
  97. buffer and the language mode edit buffer.
  98. When this variable is nil, after editing with `\\[org-edit-src-code]',
  99. the minimum (across-lines) number of leading whitespace characters
  100. are removed from all lines, and the code block is uniformly indented
  101. according to the value of `org-edit-src-content-indentation'."
  102. :group 'org-edit-structure
  103. :type 'boolean)
  104. (defcustom org-edit-src-content-indentation 2
  105. "Indentation for the content of a source code block.
  106. This should be the number of spaces added to the indentation of the #+begin
  107. line in order to compute the indentation of the block content after
  108. editing it with `\\[org-edit-src-code]'.
  109. It has no effect if `org-src-preserve-indentation' is non-nil."
  110. :group 'org-edit-structure
  111. :type 'integer
  112. :safe #'wholenump)
  113. (defcustom org-edit-src-persistent-message t
  114. "Non-nil means show persistent exit help message while editing src examples.
  115. The message is shown in the header-line, which will be created in the
  116. first line of the window showing the editing buffer."
  117. :group 'org-edit-structure
  118. :type 'boolean)
  119. (defcustom org-src-ask-before-returning-to-edit-buffer t
  120. "Non-nil means ask before switching to an existing edit buffer.
  121. If nil, when `org-edit-src-code' is used on a block that already
  122. has an active edit buffer, it will switch to that edit buffer
  123. immediately; otherwise it will ask whether you want to return to
  124. the existing edit buffer."
  125. :group 'org-edit-structure
  126. :version "24.4"
  127. :package-version '(Org . "8.0")
  128. :type 'boolean)
  129. (defcustom org-src-window-setup 'reorganize-frame
  130. "How the source code edit buffer should be displayed.
  131. Possible values for this option are:
  132. current-window Show edit buffer in the current window, keeping all other
  133. windows.
  134. other-window Use `switch-to-buffer-other-window' to display edit buffer.
  135. reorganize-frame Show only two windows on the current frame, the current
  136. window and the edit buffer. When exiting the edit buffer,
  137. return to one window.
  138. other-frame Use `switch-to-buffer-other-frame' to display edit buffer.
  139. Also, when exiting the edit buffer, kill that frame."
  140. :group 'org-edit-structure
  141. :type '(choice
  142. (const current-window)
  143. (const other-frame)
  144. (const other-window)
  145. (const reorganize-frame)))
  146. (defvar org-src-mode-hook nil
  147. "Hook run after Org switched a source code snippet to its Emacs mode.
  148. \\<org-mode-map>
  149. This hook will run:
  150. - when editing a source code snippet with `\\[org-edit-special]'
  151. - when formatting a source code snippet for export with htmlize.
  152. You may want to use this hook for example to turn off `outline-minor-mode'
  153. or similar things which you want to have when editing a source code file,
  154. but which mess up the display of a snippet in Org exported files.")
  155. (defcustom org-src-lang-modes
  156. '(("ocaml" . tuareg) ("elisp" . emacs-lisp) ("ditaa" . artist)
  157. ("asymptote" . asy) ("dot" . fundamental) ("sqlite" . sql)
  158. ("calc" . fundamental) ("C" . c) ("cpp" . c++) ("C++" . c++)
  159. ("screen" . shell-script) ("shell" . sh) ("bash" . sh))
  160. "Alist mapping languages to their major mode.
  161. The key is the language name, the value is the string that should
  162. be inserted as the name of the major mode. For many languages this is
  163. simple, but for language where this is not the case, this variable
  164. provides a way to simplify things on the user side.
  165. For example, there is no ocaml-mode in Emacs, but the mode to use is
  166. `tuareg-mode'."
  167. :group 'org-edit-structure
  168. :type '(repeat
  169. (cons
  170. (string "Language name")
  171. (symbol "Major mode"))))
  172. (defcustom org-src-block-faces nil
  173. "Alist of faces to be used for source-block.
  174. Each element is a cell of the format
  175. (\"language\" FACE)
  176. Where FACE is either a defined face or an anonymous face.
  177. For instance, the following value would color the background of
  178. emacs-lisp source blocks and python source blocks in purple and
  179. green, respectability.
  180. \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
  181. (\"python\" (:background \"#e5ffb8\")))"
  182. :group 'org-edit-structure
  183. :type '(repeat (list (string :tag "language")
  184. (choice
  185. (face :tag "Face")
  186. (sexp :tag "Anonymous face"))))
  187. :version "26.1"
  188. :package-version '(Org . "9.0"))
  189. (defcustom org-src-tab-acts-natively nil
  190. "If non-nil, the effect of TAB in a code block is as if it were
  191. issued in the language major mode buffer."
  192. :type 'boolean
  193. :version "24.1"
  194. :group 'org-babel)
  195. ;;; Internal functions and variables
  196. (defvar org-src--allow-write-back t)
  197. (defvar org-src--auto-save-timer nil)
  198. (defvar org-src--babel-info nil)
  199. (defvar org-src--beg-marker nil)
  200. (defvar org-src--block-indentation nil)
  201. (defvar org-src--end-marker nil)
  202. (defvar org-src--from-org-mode nil)
  203. (defvar org-src--overlay nil)
  204. (defvar org-src--preserve-indentation nil)
  205. (defvar org-src--remote nil)
  206. (defvar org-src--saved-temp-window-config nil)
  207. (defvar org-src--source-type nil
  208. "Type of element being edited, as a symbol.")
  209. (defvar org-src--tab-width nil
  210. "Contains `tab-width' value from Org source buffer.
  211. However, if `indent-tabs-mode' is nil in that buffer, its value
  212. is 0.")
  213. (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
  214. "Construct the buffer name for a source editing buffer."
  215. (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
  216. (defun org-src--edit-buffer (beg end)
  217. "Return buffer editing area between BEG and END.
  218. Return nil if there is no such buffer."
  219. (catch 'exit
  220. (dolist (b (buffer-list))
  221. (with-current-buffer b
  222. (and (org-src-edit-buffer-p)
  223. (= beg org-src--beg-marker)
  224. (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
  225. (= end org-src--end-marker)
  226. (eq (marker-buffer end) (marker-buffer org-src--end-marker))
  227. (throw 'exit b))))))
  228. (defun org-src--source-buffer ()
  229. "Return source buffer edited by current buffer."
  230. (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
  231. (or (marker-buffer org-src--beg-marker)
  232. (error "No source buffer available for current editing session")))
  233. (defun org-src--get-lang-mode (lang)
  234. "Return major mode that should be used for LANG.
  235. LANG is a string, and the returned major mode is a symbol."
  236. (intern
  237. (concat
  238. (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
  239. (if (symbolp l) (symbol-name l) l))
  240. "-mode")))
  241. (defun org-src--coordinates (pos beg end)
  242. "Return coordinates of POS relatively to BEG and END.
  243. POS, BEG and END are buffer positions. Return value is either
  244. a cons cell (LINE . COLUMN) or symbol `end'. See also
  245. `org-src--goto-coordinates'."
  246. (if (>= pos end) 'end
  247. (org-with-wide-buffer
  248. (goto-char (max beg pos))
  249. (cons (count-lines beg (line-beginning-position))
  250. ;; Column is relative to the end of line to avoid problems of
  251. ;; comma escaping or colons appended in front of the line.
  252. (- (current-column)
  253. (progn (end-of-line) (current-column)))))))
  254. (defun org-src--goto-coordinates (coord beg end)
  255. "Move to coordinates COORD relatively to BEG and END.
  256. COORD are coordinates, as returned by `org-src--coordinates',
  257. which see. BEG and END are buffer positions."
  258. (goto-char
  259. (if (eq coord 'end) (max (1- end) beg)
  260. ;; If BEG happens to be located outside of the narrowed part of
  261. ;; the buffer, widen it first.
  262. (org-with-wide-buffer
  263. (goto-char beg)
  264. (forward-line (car coord))
  265. (end-of-line)
  266. (org-move-to-column (max (+ (current-column) (cdr coord)) 0))
  267. (point)))))
  268. (defun org-src--contents-area (datum)
  269. "Return contents boundaries of DATUM.
  270. DATUM is an element or object. Return a list (BEG END CONTENTS)
  271. where BEG and END are buffer positions and CONTENTS is a string."
  272. (let ((type (org-element-type datum)))
  273. (org-with-wide-buffer
  274. (cond
  275. ((eq type 'footnote-definition)
  276. (let* ((beg (progn
  277. (goto-char (org-element-property :post-affiliated datum))
  278. (search-forward "]")))
  279. (end (or (org-element-property :contents-end datum) beg)))
  280. (list beg end (buffer-substring-no-properties beg end))))
  281. ((eq type 'inline-src-block)
  282. (let ((beg (progn (goto-char (org-element-property :begin datum))
  283. (search-forward "{" (line-end-position) t)))
  284. (end (progn (goto-char (org-element-property :end datum))
  285. (search-backward "}" (line-beginning-position) t))))
  286. (list beg end (buffer-substring-no-properties beg end))))
  287. ((org-element-property :contents-begin datum)
  288. (let ((beg (org-element-property :contents-begin datum))
  289. (end (org-element-property :contents-end datum)))
  290. (list beg end (buffer-substring-no-properties beg end))))
  291. ((memq type '(example-block export-block src-block))
  292. (list (progn (goto-char (org-element-property :post-affiliated datum))
  293. (line-beginning-position 2))
  294. (progn (goto-char (org-element-property :end datum))
  295. (skip-chars-backward " \r\t\n")
  296. (line-beginning-position 1))
  297. (org-element-property :value datum)))
  298. ((memq type '(fixed-width latex-environment table))
  299. (let ((beg (org-element-property :post-affiliated datum))
  300. (end (progn (goto-char (org-element-property :end datum))
  301. (skip-chars-backward " \r\t\n")
  302. (line-beginning-position 2))))
  303. (list beg
  304. end
  305. (if (eq type 'fixed-width) (org-element-property :value datum)
  306. (buffer-substring-no-properties beg end)))))
  307. (t (error "Unsupported element or object: %s" type))))))
  308. (defun org-src--make-source-overlay (beg end edit-buffer)
  309. "Create overlay between BEG and END positions and return it.
  310. EDIT-BUFFER is the buffer currently editing area between BEG and
  311. END."
  312. (let ((overlay (make-overlay beg end)))
  313. (overlay-put overlay 'face 'secondary-selection)
  314. (overlay-put overlay 'edit-buffer edit-buffer)
  315. (overlay-put overlay 'help-echo
  316. "Click with mouse-1 to switch to buffer editing this segment")
  317. (overlay-put overlay 'face 'secondary-selection)
  318. (overlay-put overlay 'keymap
  319. (let ((map (make-sparse-keymap)))
  320. (define-key map [mouse-1] 'org-edit-src-continue)
  321. map))
  322. (let ((read-only
  323. (list
  324. (lambda (&rest _)
  325. (user-error
  326. "Cannot modify an area being edited in a dedicated buffer")))))
  327. (overlay-put overlay 'modification-hooks read-only)
  328. (overlay-put overlay 'insert-in-front-hooks read-only)
  329. (overlay-put overlay 'insert-behind-hooks read-only))
  330. overlay))
  331. (defun org-src--remove-overlay ()
  332. "Remove overlay from current source buffer."
  333. (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
  334. (defun org-src--on-datum-p (datum)
  335. "Non-nil when point is on DATUM.
  336. DATUM is an element or an object. Consider blank lines or white
  337. spaces after it as being outside."
  338. (and (>= (point) (org-element-property :begin datum))
  339. (<= (point)
  340. (org-with-wide-buffer
  341. (goto-char (org-element-property :end datum))
  342. (skip-chars-backward " \r\t\n")
  343. (if (eq (org-element-class datum) 'element)
  344. (line-end-position)
  345. (point))))))
  346. (defun org-src--contents-for-write-back ()
  347. "Return buffer contents in a format appropriate for write back.
  348. Assume point is in the corresponding edit buffer."
  349. (let ((indentation-offset
  350. (if org-src--preserve-indentation 0
  351. (+ (or org-src--block-indentation 0)
  352. (if (memq org-src--source-type '(example-block src-block))
  353. org-edit-src-content-indentation
  354. 0))))
  355. (use-tabs? (and (> org-src--tab-width 0) t))
  356. (source-tab-width org-src--tab-width)
  357. (contents (org-with-wide-buffer (buffer-string)))
  358. (write-back org-src--allow-write-back))
  359. (with-temp-buffer
  360. ;; Reproduce indentation parameters from source buffer.
  361. (setq-local indent-tabs-mode use-tabs?)
  362. (when (> source-tab-width 0) (setq-local tab-width source-tab-width))
  363. ;; Apply WRITE-BACK function on edit buffer contents.
  364. (insert (org-no-properties contents))
  365. (goto-char (point-min))
  366. (when (functionp write-back) (save-excursion (funcall write-back)))
  367. ;; Add INDENTATION-OFFSET to every non-empty line in buffer,
  368. ;; unless indentation is meant to be preserved.
  369. (when (> indentation-offset 0)
  370. (while (not (eobp))
  371. (skip-chars-forward " \t")
  372. (unless (eolp) ;ignore blank lines
  373. (let ((i (current-column)))
  374. (delete-region (line-beginning-position) (point))
  375. (indent-to (+ i indentation-offset))))
  376. (forward-line)))
  377. (buffer-string))))
  378. (defun org-src--edit-element
  379. (datum name &optional initialize write-back contents remote)
  380. "Edit DATUM contents in a dedicated buffer NAME.
  381. INITIALIZE is a function to call upon creating the buffer.
  382. When WRITE-BACK is non-nil, assume contents will replace original
  383. region. Moreover, if it is a function, apply it in the edit
  384. buffer, from point min, before returning the contents.
  385. When CONTENTS is non-nil, display them in the edit buffer.
  386. Otherwise, show DATUM contents as specified by
  387. `org-src--contents-area'.
  388. When REMOTE is non-nil, do not try to preserve point or mark when
  389. moving from the edit area to the source.
  390. Leave point in edit buffer."
  391. (setq org-src--saved-temp-window-config (current-window-configuration))
  392. (let* ((area (org-src--contents-area datum))
  393. (beg (copy-marker (nth 0 area)))
  394. (end (copy-marker (nth 1 area) t))
  395. (old-edit-buffer (org-src--edit-buffer beg end))
  396. (contents (or contents (nth 2 area))))
  397. (if (and old-edit-buffer
  398. (or (not org-src-ask-before-returning-to-edit-buffer)
  399. (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
  400. ;; Move to existing buffer.
  401. (org-src-switch-to-buffer old-edit-buffer 'return)
  402. ;; Discard old edit buffer.
  403. (when old-edit-buffer
  404. (with-current-buffer old-edit-buffer (org-src--remove-overlay))
  405. (kill-buffer old-edit-buffer))
  406. (let* ((org-mode-p (derived-mode-p 'org-mode))
  407. (source-tab-width (if indent-tabs-mode tab-width 0))
  408. (type (org-element-type datum))
  409. (ind (org-with-wide-buffer
  410. (goto-char (org-element-property :begin datum))
  411. (org-get-indentation)))
  412. (preserve-ind
  413. (and (memq type '(example-block src-block))
  414. (or (org-element-property :preserve-indent datum)
  415. org-src-preserve-indentation)))
  416. ;; Store relative positions of mark (if any) and point
  417. ;; within the edited area.
  418. (point-coordinates (and (not remote)
  419. (org-src--coordinates (point) beg end)))
  420. (mark-coordinates (and (not remote)
  421. (org-region-active-p)
  422. (let ((m (mark)))
  423. (and (>= m beg) (>= end m)
  424. (org-src--coordinates m beg end)))))
  425. ;; Generate a new edit buffer.
  426. (buffer (generate-new-buffer name))
  427. ;; Add an overlay on top of source.
  428. (overlay (org-src--make-source-overlay beg end buffer)))
  429. ;; Switch to edit buffer.
  430. (org-src-switch-to-buffer buffer 'edit)
  431. ;; Insert contents.
  432. (insert contents)
  433. (remove-text-properties (point-min) (point-max)
  434. '(display nil invisible nil intangible nil))
  435. (unless preserve-ind (org-do-remove-indentation))
  436. (set-buffer-modified-p nil)
  437. (setq buffer-file-name nil)
  438. ;; Initialize buffer.
  439. (when (functionp initialize)
  440. (let ((org-inhibit-startup t))
  441. (condition-case e
  442. (funcall initialize)
  443. (error (message "Initialization fails with: %S"
  444. (error-message-string e))))))
  445. ;; Transmit buffer-local variables for exit function. It must
  446. ;; be done after initializing major mode, as this operation
  447. ;; may reset them otherwise.
  448. (setq-local org-src--tab-width source-tab-width)
  449. (setq-local org-src--from-org-mode org-mode-p)
  450. (setq-local org-src--beg-marker beg)
  451. (setq-local org-src--end-marker end)
  452. (setq-local org-src--remote remote)
  453. (setq-local org-src--source-type type)
  454. (setq-local org-src--block-indentation ind)
  455. (setq-local org-src--preserve-indentation preserve-ind)
  456. (setq-local org-src--overlay overlay)
  457. (setq-local org-src--allow-write-back write-back)
  458. ;; Start minor mode.
  459. (org-src-mode)
  460. ;; Move mark and point in edit buffer to the corresponding
  461. ;; location.
  462. (if remote
  463. (progn
  464. ;; Put point at first non read-only character after
  465. ;; leading blank.
  466. (goto-char
  467. (or (text-property-any (point-min) (point-max) 'read-only nil)
  468. (point-max)))
  469. (skip-chars-forward " \r\t\n"))
  470. ;; Set mark and point.
  471. (when mark-coordinates
  472. (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
  473. (push-mark (point) 'no-message t)
  474. (setq deactivate-mark nil))
  475. (org-src--goto-coordinates
  476. point-coordinates (point-min) (point-max)))))))
  477. ;;; Fontification of source blocks
  478. (defun org-src-font-lock-fontify-block (lang start end)
  479. "Fontify code block.
  480. This function is called by emacs automatic fontification, as long
  481. as `org-src-fontify-natively' is non-nil."
  482. (let ((lang-mode (org-src--get-lang-mode lang)))
  483. (when (fboundp lang-mode)
  484. (let ((string (buffer-substring-no-properties start end))
  485. (modified (buffer-modified-p))
  486. (org-buffer (current-buffer)))
  487. (remove-text-properties start end '(face nil))
  488. (with-current-buffer
  489. (get-buffer-create
  490. (format " *org-src-fontification:%s*" lang-mode))
  491. (let ((inhibit-modification-hooks nil))
  492. (erase-buffer)
  493. ;; Add string and a final space to ensure property change.
  494. (insert string " "))
  495. (unless (eq major-mode lang-mode) (funcall lang-mode))
  496. (org-font-lock-ensure)
  497. (let ((pos (point-min)) next)
  498. (while (setq next (next-property-change pos))
  499. ;; Handle additional properties from font-lock, so as to
  500. ;; preserve, e.g., composition.
  501. (dolist (prop (cons 'face font-lock-extra-managed-props))
  502. (let ((new-prop (get-text-property pos prop)))
  503. (put-text-property
  504. (+ start (1- pos)) (1- (+ start next)) prop new-prop
  505. org-buffer)))
  506. (setq pos next))))
  507. ;; Add Org faces.
  508. (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
  509. (when (or (facep src-face) (listp src-face))
  510. (font-lock-append-text-property start end 'face src-face))
  511. (font-lock-append-text-property start end 'face 'org-block))
  512. (add-text-properties
  513. start end
  514. '(font-lock-fontified t fontified t font-lock-multiline t))
  515. (set-buffer-modified-p modified)))))
  516. ;;; Escape contents
  517. (defun org-escape-code-in-region (beg end)
  518. "Escape lines between BEG and END.
  519. Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
  520. \",#+\" by appending a comma to it."
  521. (interactive "r")
  522. (save-excursion
  523. (goto-char end)
  524. (while (re-search-backward "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" beg t)
  525. (save-excursion (replace-match ",\\1" nil nil nil 1)))))
  526. (defun org-escape-code-in-string (s)
  527. "Escape lines in string S.
  528. Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
  529. \",#+\" by appending a comma to it."
  530. (replace-regexp-in-string "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" ",\\1"
  531. s nil nil 1))
  532. (defun org-unescape-code-in-region (beg end)
  533. "Un-escape lines between BEG and END.
  534. Un-escaping happens by removing the first comma on lines starting
  535. with \",*\", \",#+\", \",,*\" and \",,#+\"."
  536. (interactive "r")
  537. (save-excursion
  538. (goto-char end)
  539. (while (re-search-backward "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
  540. (save-excursion (replace-match "" nil nil nil 1)))))
  541. (defun org-unescape-code-in-string (s)
  542. "Un-escape lines in string S.
  543. Un-escaping happens by removing the first comma on lines starting
  544. with \",*\", \",#+\", \",,*\" and \",,#+\"."
  545. (replace-regexp-in-string
  546. "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
  547. ;;; Org src minor mode
  548. (defvar org-src-mode-map
  549. (let ((map (make-sparse-keymap)))
  550. (define-key map "\C-c'" 'org-edit-src-exit)
  551. (define-key map "\C-c\C-k" 'org-edit-src-abort)
  552. (define-key map "\C-x\C-s" 'org-edit-src-save)
  553. map))
  554. (define-minor-mode org-src-mode
  555. "Minor mode for language major mode buffers generated by Org.
  556. \\<org-mode-map>
  557. This minor mode is turned on in two situations:
  558. - when editing a source code snippet with `\\[org-edit-special]'
  559. - when formatting a source code snippet for export with htmlize.
  560. \\{org-src-mode-map}
  561. See also `org-src-mode-hook'."
  562. nil " OrgSrc" nil
  563. (when org-edit-src-persistent-message
  564. (setq-local
  565. header-line-format
  566. (substitute-command-keys
  567. (if org-src--allow-write-back
  568. "Edit, then exit with `\\[org-edit-src-exit]' or abort with \
  569. `\\[org-edit-src-abort]'"
  570. "Exit with `\\[org-edit-src-exit]' or abort with \
  571. `\\[org-edit-src-abort]'"))))
  572. ;; Possibly activate various auto-save features (for the edit buffer
  573. ;; or the source buffer).
  574. (when org-edit-src-turn-on-auto-save
  575. (setq buffer-auto-save-file-name
  576. (concat (make-temp-name "org-src-")
  577. (format-time-string "-%Y-%d-%m")
  578. ".txt")))
  579. (unless (or org-src--auto-save-timer (zerop org-edit-src-auto-save-idle-delay))
  580. (setq org-src--auto-save-timer
  581. (run-with-idle-timer
  582. org-edit-src-auto-save-idle-delay t
  583. (lambda ()
  584. (save-excursion
  585. (let (edit-flag)
  586. (dolist (b (buffer-list))
  587. (with-current-buffer b
  588. (when (org-src-edit-buffer-p)
  589. (unless edit-flag (setq edit-flag t))
  590. (when (buffer-modified-p) (org-edit-src-save)))))
  591. (unless edit-flag
  592. (cancel-timer org-src--auto-save-timer)
  593. (setq org-src--auto-save-timer nil)))))))))
  594. (defun org-src-mode-configure-edit-buffer ()
  595. (when (bound-and-true-p org-src--from-org-mode)
  596. (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
  597. (if (bound-and-true-p org-src--allow-write-back)
  598. (progn
  599. (setq buffer-offer-save t)
  600. (setq buffer-file-name
  601. (concat (buffer-file-name (marker-buffer org-src--beg-marker))
  602. "[" (buffer-name) "]"))
  603. (setq-local write-contents-functions '(org-edit-src-save)))
  604. (setq buffer-read-only t))))
  605. (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
  606. ;;; Babel related functions
  607. (defun org-src-associate-babel-session (info)
  608. "Associate edit buffer with comint session."
  609. (interactive)
  610. (let ((session (cdr (assq :session (nth 2 info)))))
  611. (and session (not (string= session "none"))
  612. (org-babel-comint-buffer-livep session)
  613. (let ((f (intern (format "org-babel-%s-associate-session"
  614. (nth 0 info)))))
  615. (and (fboundp f) (funcall f session))))))
  616. (defun org-src-babel-configure-edit-buffer ()
  617. (when org-src--babel-info
  618. (org-src-associate-babel-session org-src--babel-info)))
  619. (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
  620. ;;; Public API
  621. (defmacro org-src-do-at-code-block (&rest body)
  622. "Execute BODY from an edit buffer in the Org mode buffer."
  623. (declare (debug (body)))
  624. `(let ((beg-marker org-src--beg-marker))
  625. (when beg-marker
  626. (with-current-buffer (marker-buffer beg-marker)
  627. (goto-char beg-marker)
  628. ,@body))))
  629. (defun org-src-do-key-sequence-at-code-block (&optional key)
  630. "Execute key sequence at code block in the source Org buffer.
  631. The command bound to KEY in the Org-babel key map is executed
  632. remotely with point temporarily at the start of the code block in
  633. the Org buffer.
  634. This command is not bound to a key by default, to avoid conflicts
  635. with language major mode bindings. To bind it to C-c @ in all
  636. language major modes, you could use
  637. (add-hook \\='org-src-mode-hook
  638. (lambda () (define-key org-src-mode-map \"\\C-c@\"
  639. \\='org-src-do-key-sequence-at-code-block)))
  640. In that case, for example, C-c @ t issued in code edit buffers
  641. would tangle the current Org code block, C-c @ e would execute
  642. the block and C-c @ h would display the other available
  643. Org-babel commands."
  644. (interactive "kOrg-babel key: ")
  645. (if (equal key (kbd "C-g")) (keyboard-quit)
  646. (org-edit-src-save)
  647. (org-src-do-at-code-block
  648. (call-interactively (lookup-key org-babel-map key)))))
  649. (defun org-src-edit-buffer-p (&optional buffer)
  650. "Non-nil when current buffer is a source editing buffer.
  651. If BUFFER is non-nil, test it instead."
  652. (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
  653. (and (buffer-live-p buffer)
  654. (local-variable-p 'org-src--beg-marker buffer)
  655. (local-variable-p 'org-src--end-marker buffer))))
  656. (defun org-src-switch-to-buffer (buffer context)
  657. (pcase org-src-window-setup
  658. (`current-window (pop-to-buffer-same-window buffer))
  659. (`other-window
  660. (switch-to-buffer-other-window buffer))
  661. (`other-frame
  662. (pcase context
  663. (`exit
  664. (let ((frame (selected-frame)))
  665. (switch-to-buffer-other-frame buffer)
  666. (delete-frame frame)))
  667. (`save
  668. (kill-buffer (current-buffer))
  669. (pop-to-buffer-same-window buffer))
  670. (_ (switch-to-buffer-other-frame buffer))))
  671. (`reorganize-frame
  672. (when (eq context 'edit) (delete-other-windows))
  673. (org-switch-to-buffer-other-window buffer)
  674. (when (eq context 'exit) (delete-other-windows)))
  675. (`switch-invisibly (set-buffer buffer))
  676. (_
  677. (message "Invalid value %s for `org-src-window-setup'"
  678. org-src-window-setup)
  679. (pop-to-buffer-same-window buffer))))
  680. (defun org-src-coderef-format (&optional element)
  681. "Return format string for block at point.
  682. When optional argument ELEMENT is provided, use that block.
  683. Otherwise, assume point is either at a source block, at an
  684. example block.
  685. If point is in an edit buffer, retrieve format string associated
  686. to the remote source block."
  687. (cond
  688. ((and element (org-element-property :label-fmt element)))
  689. ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
  690. ((org-element-property :label-fmt (org-element-at-point)))
  691. (t org-coderef-label-format)))
  692. (defun org-src-coderef-regexp (fmt &optional label)
  693. "Return regexp matching a coderef format string FMT.
  694. When optional argument LABEL is non-nil, match coderef for that
  695. label only.
  696. Match group 1 contains the full coderef string with surrounding
  697. white spaces. Match group 2 contains the same string without any
  698. surrounding space. Match group 3 contains the label.
  699. A coderef format regexp can only match at the end of a line."
  700. (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
  701. (replace-regexp-in-string
  702. "%s"
  703. (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
  704. (regexp-quote fmt)
  705. nil t)))
  706. (defun org-edit-footnote-reference ()
  707. "Edit definition of footnote reference at point."
  708. (interactive)
  709. (let* ((context (org-element-context))
  710. (label (org-element-property :label context)))
  711. (unless (and (eq (org-element-type context) 'footnote-reference)
  712. (org-src--on-datum-p context))
  713. (user-error "Not on a footnote reference"))
  714. (unless label (user-error "Cannot edit remotely anonymous footnotes"))
  715. (let* ((definition (org-with-wide-buffer
  716. (org-footnote-goto-definition label)
  717. (backward-char)
  718. (org-element-context)))
  719. (inline? (eq 'footnote-reference (org-element-type definition)))
  720. (contents
  721. (org-with-wide-buffer
  722. (buffer-substring-no-properties
  723. (or (org-element-property :post-affiliated definition)
  724. (org-element-property :begin definition))
  725. (cond
  726. (inline? (1+ (org-element-property :contents-end definition)))
  727. ((org-element-property :contents-end definition))
  728. (t (goto-char (org-element-property :post-affiliated definition))
  729. (line-end-position)))))))
  730. (add-text-properties
  731. 0
  732. (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
  733. (match-end 0))
  734. '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
  735. contents)
  736. (when inline?
  737. (let ((l (length contents)))
  738. (add-text-properties
  739. (1- l) l
  740. '(read-only "Cannot edit past footnote reference"
  741. front-sticky nil rear-nonsticky nil)
  742. contents)))
  743. (org-src--edit-element
  744. definition
  745. (format "*Edit footnote [%s]*" label)
  746. (let ((source (current-buffer)))
  747. (lambda ()
  748. (org-mode)
  749. (org-clone-local-variables source)))
  750. (lambda ()
  751. (if (not inline?) (delete-region (point) (search-forward "]"))
  752. (delete-region (point) (search-forward ":" nil t 2))
  753. (delete-region (1- (point-max)) (point-max))
  754. (when (re-search-forward "\n[ \t]*\n" nil t)
  755. (user-error "Inline definitions cannot contain blank lines"))
  756. ;; If footnote reference belongs to a table, make sure to
  757. ;; remove any newline characters in order to preserve
  758. ;; table's structure.
  759. (when (org-element-lineage definition '(table-cell))
  760. (while (search-forward "\n" nil t) (replace-match "")))))
  761. contents
  762. 'remote))
  763. ;; Report success.
  764. t))
  765. (defun org-edit-table.el ()
  766. "Edit \"table.el\" table at point.
  767. \\<org-src-mode-map>
  768. A new buffer is created and the table is copied into it. Then
  769. the table is recognized with `table-recognize'. When done
  770. editing, exit with `\\[org-edit-src-exit]'. The edited text will \
  771. then replace
  772. the area in the Org mode buffer.
  773. Throw an error when not at such a table."
  774. (interactive)
  775. (let ((element (org-element-at-point)))
  776. (unless (and (eq (org-element-type element) 'table)
  777. (eq (org-element-property :type element) 'table.el)
  778. (org-src--on-datum-p element))
  779. (user-error "Not in a table.el table"))
  780. (org-src--edit-element
  781. element
  782. (org-src--construct-edit-buffer-name (buffer-name) "Table")
  783. #'text-mode t)
  784. (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
  785. (table-recognize)
  786. t))
  787. (defun org-edit-latex-environment ()
  788. "Edit LaTeX environment at point.
  789. \\<org-src-mode-map>
  790. The LaTeX environment is copied into a new buffer. Major mode is
  791. set to the one associated to \"latex\" in `org-src-lang-modes',
  792. or to `latex-mode' if there is none.
  793. When done, exit with `\\[org-edit-src-exit]'. The edited text \
  794. will then replace
  795. the LaTeX environment in the Org mode buffer."
  796. (interactive)
  797. (let ((element (org-element-at-point)))
  798. (unless (and (eq (org-element-type element) 'latex-environment)
  799. (org-src--on-datum-p element))
  800. (user-error "Not in a LaTeX environment"))
  801. (org-src--edit-element
  802. element
  803. (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
  804. (org-src--get-lang-mode "latex")
  805. t)
  806. t))
  807. (defun org-edit-export-block ()
  808. "Edit export block at point.
  809. \\<org-src-mode-map>
  810. A new buffer is created and the block is copied into it, and the
  811. buffer is switched into an appropriate major mode. See also
  812. `org-src-lang-modes'.
  813. When done, exit with `\\[org-edit-src-exit]'. The edited text \
  814. will then replace
  815. the area in the Org mode buffer.
  816. Throw an error when not at an export block."
  817. (interactive)
  818. (let ((element (org-element-at-point)))
  819. (unless (and (eq (org-element-type element) 'export-block)
  820. (org-src--on-datum-p element))
  821. (user-error "Not in an export block"))
  822. (let* ((type (downcase (or (org-element-property :type element)
  823. ;; Missing export-block type. Fallback
  824. ;; to default mode.
  825. "fundamental")))
  826. (mode (org-src--get-lang-mode type)))
  827. (unless (functionp mode) (error "No such language mode: %s" mode))
  828. (org-src--edit-element
  829. element
  830. (org-src--construct-edit-buffer-name (buffer-name) type)
  831. mode
  832. (lambda () (org-escape-code-in-region (point-min) (point-max)))))
  833. t))
  834. (defun org-edit-src-code (&optional code edit-buffer-name)
  835. "Edit the source or example block at point.
  836. \\<org-src-mode-map>
  837. The code is copied to a separate buffer and the appropriate mode
  838. is turned on. When done, exit with `\\[org-edit-src-exit]'. This \
  839. will remove the
  840. original code in the Org buffer, and replace it with the edited
  841. version. See `org-src-window-setup' to configure the display of
  842. windows containing the Org buffer and the code buffer.
  843. When optional argument CODE is a string, edit it in a dedicated
  844. buffer instead.
  845. When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
  846. name of the sub-editing buffer."
  847. (interactive)
  848. (let* ((element (org-element-at-point))
  849. (type (org-element-type element)))
  850. (unless (and (memq type '(example-block src-block))
  851. (org-src--on-datum-p element))
  852. (user-error "Not in a source or example block"))
  853. (let* ((lang
  854. (if (eq type 'src-block) (org-element-property :language element)
  855. "example"))
  856. (lang-f (and (eq type 'src-block) (org-src--get-lang-mode lang)))
  857. (babel-info (and (eq type 'src-block)
  858. (org-babel-get-src-block-info 'light)))
  859. deactivate-mark)
  860. (when (and (eq type 'src-block) (not (functionp lang-f)))
  861. (error "No such language mode: %s" lang-f))
  862. (org-src--edit-element
  863. element
  864. (or edit-buffer-name
  865. (org-src--construct-edit-buffer-name (buffer-name) lang))
  866. lang-f
  867. (and (null code)
  868. (lambda () (org-escape-code-in-region (point-min) (point-max))))
  869. (and code (org-unescape-code-in-string code)))
  870. ;; Finalize buffer.
  871. (setq-local org-coderef-label-format
  872. (or (org-element-property :label-fmt element)
  873. org-coderef-label-format))
  874. (when (eq type 'src-block)
  875. (setq-local org-src--babel-info babel-info)
  876. (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
  877. (when (fboundp edit-prep-func)
  878. (funcall edit-prep-func babel-info))))
  879. t)))
  880. (defun org-edit-inline-src-code ()
  881. "Edit inline source code at point."
  882. (interactive)
  883. (let ((context (org-element-context)))
  884. (unless (and (eq (org-element-type context) 'inline-src-block)
  885. (org-src--on-datum-p context))
  886. (user-error "Not on inline source code"))
  887. (let* ((lang (org-element-property :language context))
  888. (lang-f (org-src--get-lang-mode lang))
  889. (babel-info (org-babel-get-src-block-info 'light))
  890. deactivate-mark)
  891. (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
  892. (org-src--edit-element
  893. context
  894. (org-src--construct-edit-buffer-name (buffer-name) lang)
  895. lang-f
  896. (lambda ()
  897. ;; Inline src blocks are limited to one line.
  898. (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
  899. ;; Trim contents.
  900. (goto-char (point-min))
  901. (skip-chars-forward " \t")
  902. (delete-region (point-min) (point))
  903. (goto-char (point-max))
  904. (skip-chars-backward " \t")
  905. (delete-region (point) (point-max))))
  906. ;; Finalize buffer.
  907. (setq-local org-src--babel-info babel-info)
  908. (setq-local org-src--preserve-indentation t)
  909. (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
  910. (when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
  911. ;; Return success.
  912. t)))
  913. (defun org-edit-fixed-width-region ()
  914. "Edit the fixed-width ASCII drawing at point.
  915. \\<org-src-mode-map>
  916. This must be a region where each line starts with a colon
  917. followed by a space or a newline character.
  918. A new buffer is created and the fixed-width region is copied into
  919. it, and the buffer is switched into the major mode defined in
  920. `org-edit-fixed-width-region-mode', which see.
  921. When done, exit with `\\[org-edit-src-exit]'. The edited text \
  922. will then replace
  923. the area in the Org mode buffer."
  924. (interactive)
  925. (let ((element (org-element-at-point)))
  926. (unless (and (eq (org-element-type element) 'fixed-width)
  927. (org-src--on-datum-p element))
  928. (user-error "Not in a fixed-width area"))
  929. (org-src--edit-element
  930. element
  931. (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
  932. org-edit-fixed-width-region-mode
  933. (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
  934. ;; Return success.
  935. t))
  936. (defun org-edit-src-abort ()
  937. "Abort editing of the src code and return to the Org buffer."
  938. (interactive)
  939. (let (org-src--allow-write-back) (org-edit-src-exit)))
  940. (defun org-edit-src-continue (e)
  941. "Unconditionally return to buffer editing area under point.
  942. Throw an error if there is no such buffer."
  943. (interactive "e")
  944. (mouse-set-point e)
  945. (let ((buf (get-char-property (point) 'edit-buffer)))
  946. (if buf (org-src-switch-to-buffer buf 'continue)
  947. (user-error "No sub-editing buffer for area at point"))))
  948. (defun org-edit-src-save ()
  949. "Save parent buffer with current state source-code buffer."
  950. (interactive)
  951. (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
  952. (set-buffer-modified-p nil)
  953. (let ((edited-code (org-src--contents-for-write-back))
  954. (beg org-src--beg-marker)
  955. (end org-src--end-marker)
  956. (overlay org-src--overlay))
  957. (with-current-buffer (org-src--source-buffer)
  958. (undo-boundary)
  959. (goto-char beg)
  960. ;; Temporarily disable read-only features of OVERLAY in order to
  961. ;; insert new contents.
  962. (delete-overlay overlay)
  963. (delete-region beg end)
  964. (let ((expecting-bol (bolp)))
  965. (insert edited-code)
  966. (when (and expecting-bol (not (bolp))) (insert "\n")))
  967. (save-buffer)
  968. (move-overlay overlay beg (point))))
  969. ;; `write-contents-functions' requires the function to return
  970. ;; a non-nil value so that other functions are not called.
  971. t)
  972. (defun org-edit-src-exit ()
  973. "Kill current sub-editing buffer and return to source buffer."
  974. (interactive)
  975. (unless (org-src-edit-buffer-p) (error "Not in a sub-editing buffer"))
  976. (let* ((beg org-src--beg-marker)
  977. (end org-src--end-marker)
  978. (write-back org-src--allow-write-back)
  979. (remote org-src--remote)
  980. (coordinates (and (not remote)
  981. (org-src--coordinates (point) 1 (point-max))))
  982. (code (and write-back (org-src--contents-for-write-back))))
  983. (set-buffer-modified-p nil)
  984. ;; Switch to source buffer. Kill sub-editing buffer.
  985. (let ((edit-buffer (current-buffer))
  986. (source-buffer (marker-buffer beg)))
  987. (unless source-buffer (error "Source buffer disappeared. Aborting"))
  988. (org-src-switch-to-buffer source-buffer 'exit)
  989. (kill-buffer edit-buffer))
  990. ;; Insert modified code. Ensure it ends with a newline character.
  991. (org-with-wide-buffer
  992. (when (and write-back (not (equal (buffer-substring beg end) code)))
  993. (undo-boundary)
  994. (goto-char beg)
  995. (delete-region beg end)
  996. (let ((expecting-bol (bolp)))
  997. (insert code)
  998. (when (and expecting-bol (not (bolp))) (insert "\n")))))
  999. ;; If we are to return to source buffer, put point at an
  1000. ;; appropriate location. In particular, if block is hidden, move
  1001. ;; to the beginning of the block opening line.
  1002. (unless remote
  1003. (goto-char beg)
  1004. (cond
  1005. ;; Block is hidden; move at start of block.
  1006. ((cl-some (lambda (o) (eq (overlay-get o 'invisible) 'org-hide-block))
  1007. (overlays-at (point)))
  1008. (beginning-of-line 0))
  1009. (write-back (org-src--goto-coordinates coordinates beg end))))
  1010. ;; Clean up left-over markers and restore window configuration.
  1011. (set-marker beg nil)
  1012. (set-marker end nil)
  1013. (when org-src--saved-temp-window-config
  1014. (set-window-configuration org-src--saved-temp-window-config)
  1015. (setq org-src--saved-temp-window-config nil))))
  1016. (provide 'org-src)
  1017. ;;; org-src.el ends here