org-src.el 43 KB

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