org-src.el 40 KB

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