org-src.el 37 KB

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