org-src.el 36 KB

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