org-src.el 43 KB

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