org-src.el 36 KB

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