org-src.el 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 0
  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. (when auto-save-default
  326. (setq buffer-auto-save-file-name
  327. (concat (make-temp-name "org-src-")
  328. (format-time-string "-%Y-%d-%m") ".txt")))
  329. (and org-edit-src-persistent-message
  330. (org-set-local 'header-line-format msg))
  331. (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
  332. (when (fboundp edit-prep-func)
  333. (funcall edit-prep-func full-info)))
  334. (or org-edit-src-code-timer
  335. (setq org-edit-src-code-timer
  336. (unless (zerop org-edit-src-auto-save-idle-delay)
  337. (run-with-idle-timer
  338. org-edit-src-auto-save-idle-delay t
  339. (lambda ()
  340. (cond
  341. ((and (string-match "\*Org Src" (buffer-name))
  342. (buffer-modified-p))
  343. (org-edit-src-save))
  344. ((not
  345. (delq nil (mapcar
  346. (lambda (b)
  347. (string-match "\*Org Src" (buffer-name b)))
  348. (buffer-list))))
  349. (cancel-timer org-edit-src-code-timer)
  350. (setq org-edit-src-code-timer)))))))))
  351. t)))
  352. (defun org-edit-src-continue (e)
  353. "Continue editing source blocks." ;; Fixme: be more accurate
  354. (interactive "e")
  355. (mouse-set-point e)
  356. (let ((buf (get-char-property (point) 'edit-buffer)))
  357. (if buf (org-src-switch-to-buffer buf 'continue)
  358. (error "Something is wrong here"))))
  359. (defun org-src-switch-to-buffer (buffer context)
  360. (case org-src-window-setup
  361. ('current-window
  362. (org-pop-to-buffer-same-window buffer))
  363. ('other-window
  364. (switch-to-buffer-other-window buffer))
  365. ('other-frame
  366. (case context
  367. ('exit
  368. (let ((frame (selected-frame)))
  369. (switch-to-buffer-other-frame buffer)
  370. (delete-frame frame)))
  371. ('save
  372. (kill-buffer (current-buffer))
  373. (org-pop-to-buffer-same-window buffer))
  374. (t
  375. (switch-to-buffer-other-frame buffer))))
  376. ('reorganize-frame
  377. (if (eq context 'edit) (delete-other-windows))
  378. (org-switch-to-buffer-other-window buffer)
  379. (if (eq context 'exit) (delete-other-windows)))
  380. ('switch-invisibly
  381. (set-buffer buffer))
  382. (t
  383. (message "Invalid value %s for org-src-window-setup"
  384. (symbol-name org-src-window-setup))
  385. (org-pop-to-buffer-same-window buffer))))
  386. (defun org-src-construct-edit-buffer-name (org-buffer-name lang)
  387. "Construct the buffer name for a source editing buffer."
  388. (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
  389. (defun org-src-edit-buffer-p (&optional buffer)
  390. "Test whether BUFFER (or the current buffer if BUFFER is nil)
  391. is a source block editing buffer."
  392. (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
  393. (and (buffer-name buffer)
  394. (string-match "\\`*Org Src " (buffer-name buffer))
  395. (local-variable-p 'org-edit-src-beg-marker buffer)
  396. (local-variable-p 'org-edit-src-end-marker buffer))))
  397. (defun org-edit-src-find-buffer (beg end)
  398. "Find a source editing buffer that is already editing the region BEG to END."
  399. (catch 'exit
  400. (mapc
  401. (lambda (b)
  402. (with-current-buffer b
  403. (if (and (string-match "\\`*Org Src " (buffer-name))
  404. (local-variable-p 'org-edit-src-beg-marker (current-buffer))
  405. (local-variable-p 'org-edit-src-end-marker (current-buffer))
  406. (equal beg org-edit-src-beg-marker)
  407. (equal end org-edit-src-end-marker))
  408. (throw 'exit (current-buffer)))))
  409. (buffer-list))
  410. nil))
  411. (defun org-edit-fixed-width-region ()
  412. "Edit the fixed-width ascii drawing at point.
  413. This must be a region where each line starts with a colon followed by
  414. a space character.
  415. An new buffer is created and the fixed-width region is copied into it,
  416. and the buffer is switched into `artist-mode' for editing. When done,
  417. exit with \\[org-edit-src-exit]. The edited text will then replace
  418. the fragment in the Org-mode buffer."
  419. (interactive)
  420. (let ((line (org-current-line))
  421. (col (current-column))
  422. (case-fold-search t)
  423. (msg (substitute-command-keys
  424. "Edit, then exit with C-c ' (C-c and single quote) -- C-c C-k to abort"))
  425. (org-mode-p (derived-mode-p 'org-mode))
  426. (beg (make-marker))
  427. (end (make-marker))
  428. (preserve-indentation org-src-preserve-indentation)
  429. block-nindent ovl beg1 end1 code begline buffer)
  430. (beginning-of-line 1)
  431. (if (looking-at "[ \t]*[^:\n \t]")
  432. nil
  433. (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
  434. (setq beg1 (point) end1 beg1)
  435. (save-excursion
  436. (if (re-search-backward "^[ \t]*[^: \t]" nil 'move)
  437. (setq beg1 (point-at-bol 2))
  438. (setq beg1 (point))))
  439. (save-excursion
  440. (if (re-search-forward "^[ \t]*[^: \t]" nil 'move)
  441. (setq end1 (1- (match-beginning 0)))
  442. (setq end1 (point))))
  443. (org-goto-line line))
  444. (setq beg (move-marker beg beg1)
  445. end (move-marker end end1)
  446. code (buffer-substring-no-properties beg end)
  447. begline (save-excursion (goto-char beg) (org-current-line)))
  448. (if (and (setq buffer (org-edit-src-find-buffer beg end))
  449. (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? "))
  450. (org-pop-to-buffer-same-window buffer)
  451. (when buffer
  452. (with-current-buffer buffer
  453. (if (boundp 'org-edit-src-overlay)
  454. (delete-overlay org-edit-src-overlay)))
  455. (kill-buffer buffer))
  456. (setq buffer (generate-new-buffer
  457. (org-src-construct-edit-buffer-name
  458. (buffer-name) "Fixed Width")))
  459. (setq ovl (make-overlay beg end))
  460. (overlay-put ovl 'face 'secondary-selection)
  461. (overlay-put ovl 'edit-buffer buffer)
  462. (overlay-put ovl 'help-echo "Click with mouse-1 to switch to buffer editing this segment")
  463. (overlay-put ovl 'face 'secondary-selection)
  464. (overlay-put ovl
  465. 'keymap
  466. (let ((map (make-sparse-keymap)))
  467. (define-key map [mouse-1] 'org-edit-src-continue)
  468. map))
  469. (overlay-put ovl :read-only "Leave me alone")
  470. (org-pop-to-buffer-same-window buffer)
  471. (insert code)
  472. (remove-text-properties (point-min) (point-max)
  473. '(display nil invisible nil intangible nil))
  474. (setq block-nindent (or (org-do-remove-indentation) 0))
  475. (cond
  476. ((eq org-edit-fixed-width-region-mode 'artist-mode)
  477. (fundamental-mode)
  478. (artist-mode 1))
  479. (t (funcall org-edit-fixed-width-region-mode)))
  480. (set (make-local-variable 'org-edit-src-force-single-line) nil)
  481. (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
  482. (set (make-local-variable 'org-edit-src-picture) t)
  483. (goto-char (point-min))
  484. (while (re-search-forward "^[ \t]*: ?" nil t)
  485. (replace-match ""))
  486. (org-goto-line (1+ (- line begline)))
  487. (org-move-to-column (max 0 (- col block-nindent 2)))
  488. (org-set-local 'org-edit-src-beg-marker beg)
  489. (org-set-local 'org-edit-src-end-marker end)
  490. (org-set-local 'org-edit-src-overlay ovl)
  491. (org-set-local 'org-edit-src-block-indentation block-nindent)
  492. (org-set-local 'org-edit-src-content-indentation 0)
  493. (org-set-local 'org-src-preserve-indentation nil)
  494. (org-src-mode)
  495. (set-buffer-modified-p nil)
  496. (and org-edit-src-persistent-message
  497. (org-set-local 'header-line-format msg)))
  498. (message "%s" msg)
  499. t)))
  500. (defun org-edit-src-find-region-and-lang ()
  501. "Find the region and language for a local edit.
  502. Return a list with beginning and end of the region, a string representing
  503. the language, a switch telling if the content should be in a single line."
  504. (let ((re-list
  505. (append
  506. org-edit-src-region-extra
  507. '(
  508. ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
  509. ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
  510. ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
  511. ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
  512. ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
  513. ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
  514. ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
  515. ("^[ \t]*#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n[ \t]*#\\+end_src" 2)
  516. ("^[ \t]*#\\+begin_example.*\n" "\n[ \t]*#\\+end_example" "fundamental")
  517. ("^[ \t]*#\\+html:" "\n" "html" single-line)
  518. ("^[ \t]*#\\+begin_html.*\n" "\n[ \t]*#\\+end_html" "html")
  519. ("^[ \t]*#\\+latex:" "\n" "latex" single-line)
  520. ("^[ \t]*#\\+begin_latex.*\n" "\n[ \t]*#\\+end_latex" "latex")
  521. ("^[ \t]*#\\+ascii:" "\n" "fundamental" single-line)
  522. ("^[ \t]*#\\+begin_ascii.*\n" "\n[ \t]*#\\+end_ascii" "fundamental")
  523. ("^[ \t]*#\\+macro:[ \t]+\\S-+\\( \\|$\\)"
  524. "\n" "fundamental" macro-definition)
  525. )))
  526. (pos (point))
  527. re1 re2 single beg end lang lfmt match-re1 ind entry)
  528. (catch 'exit
  529. (when (org-at-table.el-p)
  530. (re-search-backward "^[\t]*[^ \t|\\+]" nil t)
  531. (setq beg (1+ (point-at-eol)))
  532. (goto-char beg)
  533. (or (re-search-forward "^[\t]*[^ \t|\\+]" nil t)
  534. (progn (goto-char (point-max)) (newline)))
  535. (setq end (1- (point-at-bol)))
  536. (throw 'exit (list beg end 'table.el nil nil 0)))
  537. (while (setq entry (pop re-list))
  538. (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
  539. single (nth 3 entry))
  540. (save-excursion
  541. (if (or (looking-at re1)
  542. (re-search-backward re1 nil t))
  543. (progn
  544. (setq match-re1 (match-string 0))
  545. (setq beg (match-end 0)
  546. lang (org-edit-src-get-lang lang)
  547. lfmt (org-edit-src-get-label-format match-re1)
  548. ind (org-edit-src-get-indentation (match-beginning 0)))
  549. (if (and (re-search-forward re2 nil t)
  550. (>= (match-end 0) pos))
  551. (throw 'exit (list beg (match-beginning 0)
  552. lang single lfmt ind))))
  553. (if (or (looking-at re2)
  554. (re-search-forward re2 nil t))
  555. (progn
  556. (setq end (match-beginning 0))
  557. (if (and (re-search-backward re1 nil t)
  558. (<= (match-beginning 0) pos))
  559. (progn
  560. (setq lfmt (org-edit-src-get-label-format
  561. (match-string 0))
  562. ind (org-edit-src-get-indentation
  563. (match-beginning 0)))
  564. (throw 'exit
  565. (list (match-end 0) end
  566. (org-edit-src-get-lang lang)
  567. single lfmt ind))))))))))))
  568. (defun org-edit-src-get-lang (lang)
  569. "Extract the src language."
  570. (let ((m (match-string 0)))
  571. (cond
  572. ((stringp lang) lang)
  573. ((integerp lang) (match-string lang))
  574. ((and (eq lang 'lang)
  575. (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
  576. (match-string 1 m))
  577. ((and (eq lang 'style)
  578. (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
  579. (match-string 1 m))
  580. (t "fundamental"))))
  581. (defun org-edit-src-get-label-format (s)
  582. "Extract the label format."
  583. (save-match-data
  584. (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
  585. (match-string 1 s))))
  586. (defun org-edit-src-get-indentation (pos)
  587. "Count leading whitespace characters on line."
  588. (save-match-data
  589. (goto-char pos)
  590. (org-get-indentation)))
  591. (defun org-escape-code-in-region (beg end)
  592. "Escape lines between BEG and END.
  593. Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
  594. \",#+\" by appending a comma to it."
  595. (interactive "r")
  596. (save-excursion
  597. (goto-char beg)
  598. (while (re-search-forward "^[ \t]*,?\\(\\*\\|#\\+\\)" end t)
  599. (replace-match ",\\1" nil nil nil 1))))
  600. (defun org-escape-code-in-string (s)
  601. "Escape lines in string S.
  602. Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
  603. \",#+\" by appending a comma to it."
  604. (replace-regexp-in-string "^[ \t]*,?\\(\\*\\|#\\+\\)" ",\\1" s nil nil 1))
  605. (defun org-unescape-code-in-region (beg end)
  606. "Un-escape lines between BEG and END.
  607. Un-escaping happens by removing the first comma on lines starting
  608. with \",*\", \",#+\", \",,*\" and \",,#+\"."
  609. (interactive "r")
  610. (save-excursion
  611. (goto-char beg)
  612. (while (re-search-forward "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" end t)
  613. (replace-match "" nil nil nil 1))))
  614. (defun org-unescape-code-in-string (s)
  615. "Un-escape lines in string S.
  616. Un-escaping happens by removing the first comma on lines starting
  617. with \",*\", \",#+\", \",,*\" and \",,#+\"."
  618. (replace-regexp-in-string
  619. "^[ \t]*,?\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
  620. (defun org-edit-src-exit (&optional context)
  621. "Exit special edit and protect problematic lines."
  622. (interactive)
  623. (unless (org-bound-and-true-p org-edit-src-from-org-mode)
  624. (error "This is not a sub-editing buffer, something is wrong"))
  625. (widen)
  626. (let* ((fixed-width-p (string-match "Fixed Width" (buffer-name)))
  627. (beg org-edit-src-beg-marker)
  628. (end org-edit-src-end-marker)
  629. (ovl org-edit-src-overlay)
  630. (bufstr (buffer-string))
  631. (buffer (current-buffer))
  632. (single (org-bound-and-true-p org-edit-src-force-single-line))
  633. (macro (eq single 'macro-definition))
  634. (total-nindent (+ (or org-edit-src-block-indentation 0)
  635. org-edit-src-content-indentation))
  636. (preserve-indentation org-src-preserve-indentation)
  637. (allow-write-back-p (org-bound-and-true-p org-edit-src-allow-write-back-p))
  638. (delta 0) code line col indent)
  639. (when allow-write-back-p
  640. (unless preserve-indentation (untabify (point-min) (point-max)))
  641. (if org-src-strip-leading-and-trailing-blank-lines
  642. (save-excursion
  643. (goto-char (point-min))
  644. (if (looking-at "[ \t\n]*\n") (replace-match ""))
  645. (unless macro
  646. (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))))))
  647. (setq line (if (org-bound-and-true-p org-edit-src-force-single-line)
  648. 1
  649. (org-current-line))
  650. col (current-column))
  651. (when allow-write-back-p
  652. (when single
  653. (goto-char (point-min))
  654. (if (re-search-forward "\\s-+\\'" nil t) (replace-match ""))
  655. (goto-char (point-min))
  656. (let ((cnt 0))
  657. (while (re-search-forward "\n" nil t)
  658. (setq cnt (1+ cnt))
  659. (replace-match (if macro "\\n" " ") t t))
  660. (when (and macro (> cnt 0))
  661. (goto-char (point-max)) (insert "\\n")))
  662. (goto-char (point-min))
  663. (if (looking-at "\\s-*") (replace-match " ")))
  664. (when (and (org-bound-and-true-p org-edit-src-from-org-mode)
  665. (not fixed-width-p))
  666. (org-escape-code-in-region (point-min) (point-max))
  667. (setq delta (+ delta
  668. (save-excursion
  669. (org-goto-line line)
  670. (if (looking-at "[ \t]*\\(,,\\)?\\(\\*\\|#+\\)") 1
  671. 0)))))
  672. (when (org-bound-and-true-p org-edit-src-picture)
  673. (setq preserve-indentation nil)
  674. (untabify (point-min) (point-max))
  675. (goto-char (point-min))
  676. (while (re-search-forward "^" nil t)
  677. (replace-match ": ")))
  678. (unless (or single preserve-indentation (= total-nindent 0))
  679. (setq indent (make-string total-nindent ?\ ))
  680. (goto-char (point-min))
  681. (while (re-search-forward "^" nil t)
  682. (replace-match indent)))
  683. (if (org-bound-and-true-p org-edit-src-picture)
  684. (setq total-nindent (+ total-nindent 2)))
  685. (setq code (buffer-string))
  686. (when (eq context 'save)
  687. (erase-buffer)
  688. (insert bufstr))
  689. (set-buffer-modified-p nil))
  690. (org-src-switch-to-buffer (marker-buffer beg) (or context 'exit))
  691. (if (eq context 'save) (save-buffer)
  692. (with-current-buffer buffer
  693. (set-buffer-modified-p nil))
  694. (kill-buffer buffer))
  695. (goto-char beg)
  696. (when allow-write-back-p
  697. (let ((buffer-undo-list t))
  698. (delete-region beg (max beg end))
  699. (unless (string-match "\\`[ \t]*\\'" code)
  700. (insert code))
  701. (goto-char beg)
  702. (if single (just-one-space))))
  703. (if (memq t (mapcar (lambda (overlay)
  704. (eq (overlay-get overlay 'invisible)
  705. 'org-hide-block))
  706. (overlays-at (point))))
  707. ;; Block is hidden; put point at start of block
  708. (beginning-of-line 0)
  709. ;; Block is visible, put point where it was in the code buffer
  710. (when allow-write-back-p
  711. (org-goto-line (1- (+ (org-current-line) line)))
  712. (org-move-to-column (if preserve-indentation col (+ col total-nindent delta)))))
  713. (unless (eq context 'save)
  714. (move-marker beg nil)
  715. (move-marker end nil)))
  716. (when org-edit-src-code-timer
  717. (cancel-timer org-edit-src-code-timer)
  718. (setq org-edit-src-code-timer nil))
  719. (unless (eq context 'save)
  720. (when org-edit-src-saved-temp-window-config
  721. (set-window-configuration org-edit-src-saved-temp-window-config)
  722. (setq org-edit-src-saved-temp-window-config nil))))
  723. (defun org-edit-src-abort ()
  724. "Abort editing of the src code and return to the Org buffer."
  725. (interactive)
  726. (let (org-edit-src-allow-write-back-p)
  727. (org-edit-src-exit 'exit)))
  728. (defmacro org-src-in-org-buffer (&rest body)
  729. `(let ((p (point)) (m (mark)) (ul buffer-undo-list) msg)
  730. (save-window-excursion
  731. (org-edit-src-exit 'save)
  732. ,@body
  733. (setq msg (current-message))
  734. (if (eq org-src-window-setup 'other-frame)
  735. (let ((org-src-window-setup 'current-window))
  736. (org-edit-src-code 'save))
  737. (org-edit-src-code 'save)))
  738. (setq buffer-undo-list ul)
  739. (push-mark m 'nomessage)
  740. (goto-char (min p (point-max)))
  741. (message (or msg ""))))
  742. (def-edebug-spec org-src-in-org-buffer (body))
  743. (defun org-edit-src-save ()
  744. "Save parent buffer with current state source-code buffer."
  745. (interactive)
  746. (if (string-match "Fixed Width" (buffer-name))
  747. (user-error "Use C-c ' to save and exit, C-c C-k to abort editing")
  748. (org-src-in-org-buffer (save-buffer))))
  749. (declare-function org-babel-tangle "ob-tangle" (&optional arg target-file lang))
  750. (defun org-src-tangle (arg)
  751. "Tangle the parent buffer."
  752. (interactive)
  753. (org-src-in-org-buffer (org-babel-tangle arg)))
  754. (defun org-src-mode-configure-edit-buffer ()
  755. (when (org-bound-and-true-p org-edit-src-from-org-mode)
  756. (org-add-hook 'kill-buffer-hook
  757. #'(lambda () (delete-overlay org-edit-src-overlay)) nil 'local)
  758. (if (org-bound-and-true-p org-edit-src-allow-write-back-p)
  759. (progn
  760. (setq buffer-offer-save t)
  761. (setq buffer-file-name
  762. (concat (buffer-file-name (marker-buffer org-edit-src-beg-marker))
  763. "[" (buffer-name) "]"))
  764. (if (featurep 'xemacs)
  765. (progn
  766. (make-variable-buffer-local 'write-contents-hooks) ; needed only for 21.4
  767. (setq write-contents-hooks '(org-edit-src-save)))
  768. (setq write-contents-functions '(org-edit-src-save))))
  769. (setq buffer-read-only t))))
  770. (org-add-hook 'org-src-mode-hook 'org-src-mode-configure-edit-buffer)
  771. (defun org-src-associate-babel-session (info)
  772. "Associate edit buffer with comint session."
  773. (interactive)
  774. (let ((session (cdr (assoc :session (nth 2 info)))))
  775. (and session (not (string= session "none"))
  776. (org-babel-comint-buffer-livep session)
  777. ((lambda (f) (and (fboundp f) (funcall f session)))
  778. (intern (format "org-babel-%s-associate-session" (nth 0 info)))))))
  779. (defun org-src-babel-configure-edit-buffer ()
  780. (when org-src-babel-info
  781. (org-src-associate-babel-session org-src-babel-info)))
  782. (org-add-hook 'org-src-mode-hook 'org-src-babel-configure-edit-buffer)
  783. (defmacro org-src-do-at-code-block (&rest body)
  784. "Execute a command from an edit buffer in the Org-mode buffer."
  785. `(let ((beg-marker org-edit-src-beg-marker))
  786. (if beg-marker
  787. (with-current-buffer (marker-buffer beg-marker)
  788. (goto-char (marker-position beg-marker))
  789. ,@body))))
  790. (def-edebug-spec org-src-do-at-code-block (body))
  791. (defun org-src-do-key-sequence-at-code-block (&optional key)
  792. "Execute key sequence at code block in the source Org buffer.
  793. The command bound to KEY in the Org-babel key map is executed
  794. remotely with point temporarily at the start of the code block in
  795. the Org buffer.
  796. This command is not bound to a key by default, to avoid conflicts
  797. with language major mode bindings. To bind it to C-c @ in all
  798. language major modes, you could use
  799. (add-hook 'org-src-mode-hook
  800. (lambda () (define-key org-src-mode-map \"\\C-c@\"
  801. 'org-src-do-key-sequence-at-code-block)))
  802. In that case, for example, C-c @ t issued in code edit buffers
  803. would tangle the current Org code block, C-c @ e would execute
  804. the block and C-c @ h would display the other available
  805. Org-babel commands."
  806. (interactive "kOrg-babel key: ")
  807. (if (equal key (kbd "C-g")) (keyboard-quit)
  808. (org-edit-src-save)
  809. (org-src-do-at-code-block
  810. (call-interactively
  811. (lookup-key org-babel-map key)))))
  812. (defcustom org-src-tab-acts-natively nil
  813. "If non-nil, the effect of TAB in a code block is as if it were
  814. issued in the language major mode buffer."
  815. :type 'boolean
  816. :version "24.1"
  817. :group 'org-babel)
  818. (defun org-src-native-tab-command-maybe ()
  819. "Perform language-specific TAB action.
  820. Alter code block according to what TAB does in the language major mode."
  821. (and org-src-tab-acts-natively
  822. (org-in-src-block-p)
  823. (not (equal this-command 'org-shifttab))
  824. (let ((org-src-strip-leading-and-trailing-blank-lines nil))
  825. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))))
  826. (add-hook 'org-tab-first-hook 'org-src-native-tab-command-maybe)
  827. (defun org-src-font-lock-fontify-block (lang start end)
  828. "Fontify code block.
  829. This function is called by emacs automatic fontification, as long
  830. as `org-src-fontify-natively' is non-nil. For manual
  831. fontification of code blocks see `org-src-fontify-block' and
  832. `org-src-fontify-buffer'"
  833. (let ((lang-mode (org-src-get-lang-mode lang)))
  834. (if (fboundp lang-mode)
  835. (let ((string (buffer-substring-no-properties start end))
  836. (modified (buffer-modified-p))
  837. (org-buffer (current-buffer)) pos next)
  838. (remove-text-properties start end '(face nil))
  839. (with-current-buffer
  840. (get-buffer-create
  841. (concat " org-src-fontification:" (symbol-name lang-mode)))
  842. (delete-region (point-min) (point-max))
  843. (insert string " ") ;; so there's a final property change
  844. (unless (eq major-mode lang-mode) (funcall lang-mode))
  845. (font-lock-fontify-buffer)
  846. (setq pos (point-min))
  847. (while (setq next (next-single-property-change pos 'face))
  848. (put-text-property
  849. (+ start (1- pos)) (1- (+ start next)) 'face
  850. (get-text-property pos 'face) org-buffer)
  851. (setq pos next)))
  852. (add-text-properties
  853. start end
  854. '(font-lock-fontified t fontified t font-lock-multiline t))
  855. (set-buffer-modified-p modified)))))
  856. (defun org-src-fontify-block ()
  857. "Fontify code block at point."
  858. (interactive)
  859. (save-excursion
  860. (let ((org-src-fontify-natively t)
  861. (info (org-edit-src-find-region-and-lang)))
  862. (font-lock-fontify-region (nth 0 info) (nth 1 info)))))
  863. (defun org-src-fontify-buffer ()
  864. "Fontify all code blocks in the current buffer."
  865. (interactive)
  866. (org-babel-map-src-blocks nil
  867. (org-src-fontify-block)))
  868. (defun org-src-get-lang-mode (lang)
  869. "Return major mode that should be used for LANG.
  870. LANG is a string, and the returned major mode is a symbol."
  871. (intern
  872. (concat
  873. ((lambda (l) (if (symbolp l) (symbol-name l) l))
  874. (or (cdr (assoc lang org-src-lang-modes)) lang)) "-mode")))
  875. (provide 'org-src)
  876. ;;; org-src.el ends here