org-src.el 47 KB

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