org-src.el 46 KB

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