org-src.el 31 KB

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