org-src.el 32 KB

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