org-src.el 31 KB

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