org-src.el 31 KB

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