org-src.el 53 KB

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