org-src.el 56 KB

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