org-src.el 43 KB

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