org-src.el 36 KB

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