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