org-src.el 32 KB

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