org-src.el 34 KB

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