org-src.el 53 KB

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