org-src.el 34 KB

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