org-src.el 36 KB

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