org-src.el 37 KB

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