org-src.el 36 KB

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