org-src.el 34 KB

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