org-src.el 35 KB

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