org-src.el 40 KB

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