org-src.el 49 KB

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