org-src.el 42 KB

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