config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

org-src.el (58962B)


      1 ;;; org-src.el --- Source code examples in Org       -*- lexical-binding: t; -*-
      2 ;;
      3 ;; Copyright (C) 2004-2024 Free Software Foundation, Inc.
      4 ;;
      5 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
      6 ;;	   Bastien Guerry <bzg@gnu.org>
      7 ;;         Dan Davison <davison at stats dot ox dot ac dot uk>
      8 ;; Keywords: outlines, hypermedia, calendar, text
      9 ;; URL: https://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 
     18 ;; GNU Emacs is distributed in the hope that it will be useful,
     19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
     21 ;; GNU General Public License for more details.
     22 
     23 ;; You should have received a copy of the GNU General Public License
     24 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
     26 ;;
     27 ;;; Commentary:
     28 
     29 ;; This file contains the code dealing with source code examples in
     30 ;; Org mode.
     31 
     32 ;;; Code:
     33 
     34 (require 'org-macs)
     35 (org-assert-version)
     36 
     37 (require 'cl-lib)
     38 (require 'ob-comint)
     39 (require 'org-macs)
     40 (require 'org-compat)
     41 (require 'org-keys)
     42 (require 'sh-script)
     43 
     44 (declare-function org--get-expected-indentation "org" (element contentsp))
     45 (declare-function org-mode "org" ())
     46 (declare-function org--get-expected-indentation "org" (element contentsp))
     47 (declare-function org-fold-region "org-fold" (from to flag &optional spec-or-alias))
     48 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
     49 (declare-function org-element-class "org-element" (datum &optional parent))
     50 (declare-function org-element-context "org-element" (&optional element))
     51 (declare-function org-element-lineage "org-element-ast"
     52 		  (blob &optional types with-self))
     53 (declare-function org-element--parse-paired-brackets "org-element" (char))
     54 (declare-function org-element-property "org-element-ast" (property node))
     55 (declare-function org-element-begin "org-element" (node))
     56 (declare-function org-element-end "org-element" (node))
     57 (declare-function org-element-contents-begin "org-element" (node))
     58 (declare-function org-element-contents-end "org-element" (node))
     59 (declare-function org-element-post-affiliated "org-element" (node))
     60 (declare-function org-element-post-blank "org-element" (node))
     61 (declare-function org-element-parent "org-element-ast" (node))
     62 (declare-function org-element-type "org-element-ast" (node &optional anonymous))
     63 (declare-function org-element-type-p "org-element-ast" (node types))
     64 (declare-function org-footnote-goto-definition "org-footnote"
     65 		  (label &optional location))
     66 
     67 (defvar org-inhibit-startup)
     68 
     69 (defcustom org-edit-src-turn-on-auto-save nil
     70   "Non-nil means turn `auto-save-mode' on when editing a source block.
     71 This will save the content of the source code editing buffer into
     72 a newly created file, not the base buffer for this source block.
     73 
     74 If you want to regularly save the base buffer instead of the source
     75 code editing buffer, see `org-edit-src-auto-save-idle-delay' instead."
     76   :group 'org-edit-structure
     77   :version "24.4"
     78   :package-version '(Org . "8.0")
     79   :type 'boolean)
     80 
     81 (defcustom org-edit-src-auto-save-idle-delay 0
     82   "Delay before saving a source code buffer back into its base buffer.
     83 When a positive integer N, save after N seconds of idle time.
     84 When 0 (the default), don't auto-save.
     85 
     86 If you want to save the source code buffer itself, don't use this.
     87 Check `org-edit-src-turn-on-auto-save' instead."
     88   :group 'org-edit-structure
     89   :version "24.4"
     90   :package-version '(Org . "8.0")
     91   :type 'integer)
     92 
     93 (defcustom org-coderef-label-format "(ref:%s)"
     94   "The default coderef format.
     95 This format string will be used to search for coderef labels in literal
     96 examples (EXAMPLE and SRC blocks).  The format can be overwritten in
     97 an individual literal example with the -l option, like
     98 
     99 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
    100 ...
    101 #+END_SRC
    102 
    103 If you want to use this for HTML export, make sure that the format does
    104 not introduce special font-locking, and avoid the HTML special
    105 characters `<', `>', and `&'.  The reason for this restriction is that
    106 the labels are searched for only after htmlize has done its job."
    107   :group 'org-edit-structure ; FIXME this is not in the right group
    108   :type 'string)
    109 
    110 (defcustom org-edit-fixed-width-region-mode 'artist-mode
    111   "The mode that should be used to edit fixed-width regions.
    112 These are the regions where each line starts with a colon."
    113   :group 'org-edit-structure
    114   :type '(choice
    115 	  (const artist-mode)
    116 	  (const picture-mode)
    117 	  (const fundamental-mode)
    118 	  (function :tag "Other (specify)")))
    119 
    120 (defcustom org-src-preserve-indentation nil
    121   "If non-nil preserve leading whitespace characters on export.
    122 
    123 If non-nil leading whitespace characters in source code blocks are
    124 preserved on export, or adjusted while indenting or when switching
    125 between the org buffer and the language mode edit buffer.
    126 
    127 When this variable is nil, while indenting with `\\[org-indent-block]'
    128 or after editing with `\\[org-edit-src-code]', the minimum (across-lines)
    129 number of leading whitespace characters are removed from all lines,
    130 and the code block is uniformly indented according to the value of
    131 `org-edit-src-content-indentation'."
    132   :group 'org-edit-structure
    133   :type 'boolean)
    134 
    135 (defcustom org-edit-src-content-indentation 2
    136   "Indentation for the content of a source code block.
    137 
    138 This should be the number of spaces added to the indentation of the #+begin
    139 line in order to compute the indentation of the block content after
    140 editing it with `\\[org-edit-src-code]'.
    141 
    142 It has no effect if `org-src-preserve-indentation' is non-nil."
    143   :group 'org-edit-structure
    144   :type 'integer
    145   :safe #'wholenump)
    146 
    147 (defcustom org-edit-src-persistent-message t
    148   "Non-nil means show persistent exit help message while editing src examples.
    149 The message is shown in the header-line, which will be created in the
    150 first line of the window showing the editing buffer."
    151   :group 'org-edit-structure
    152   :type 'boolean)
    153 
    154 (defcustom org-src-ask-before-returning-to-edit-buffer t
    155   "Non-nil means ask before switching to an existing edit buffer.
    156 If nil, when `org-edit-src-code' is used on a block that already
    157 has an active edit buffer, it will switch to that edit buffer
    158 immediately; otherwise it will ask whether you want to return to
    159 the existing edit buffer."
    160   :group 'org-edit-structure
    161   :version "24.4"
    162   :package-version '(Org . "8.0")
    163   :type 'boolean)
    164 
    165 (defcustom org-src-window-setup 'reorganize-frame
    166   "How the source code edit buffer should be displayed.
    167 Possible values for this option are:
    168 
    169 plain              Show edit buffer using `display-buffer'.  Users can
    170                    further control the display behavior by modifying
    171                    `display-buffer-alist' and its relatives.
    172 current-window     Show edit buffer in the current window, keeping all other
    173                    windows.
    174 split-window-below Show edit buffer below the current window, keeping all
    175                    other windows.
    176 split-window-right Show edit buffer to the right of the current window,
    177                    keeping all other windows.
    178 other-window       Use `switch-to-buffer-other-window' to display edit buffer.
    179 reorganize-frame   Show only two windows on the current frame, the current
    180                    window and the edit buffer.
    181 other-frame        Use `switch-to-buffer-other-frame' to display edit buffer.
    182                    Also, when exiting the edit buffer, kill that frame.
    183 
    184 Values that modify the window layout (reorganize-frame, split-window-below,
    185 split-window-right) will restore the layout after exiting the edit buffer."
    186   :group 'org-edit-structure
    187   :type '(choice
    188           (const plain)
    189 	  (const current-window)
    190 	  (const split-window-below)
    191 	  (const split-window-right)
    192 	  (const other-frame)
    193 	  (const other-window)
    194 	  (const reorganize-frame)))
    195 
    196 (defvar org-src-mode-hook nil
    197   "Hook run after Org switched a source code snippet to its Emacs mode.
    198 \\<org-mode-map>
    199 This hook will run:
    200 - when editing a source code snippet with `\\[org-edit-special]'
    201 - when formatting a source code snippet for export with htmlize.
    202 
    203 You may want to use this hook for example to turn off `outline-minor-mode'
    204 or similar things which you want to have when editing a source code file,
    205 but which mess up the display of a snippet in Org exported files.")
    206 
    207 (defun org-src--get-known-shells ()
    208   "List all the shells in `sh-ancestor-alist' for `org-src-lang-modes'.
    209 The shells are associated with `sh-mode'."
    210   (mapcar
    211    (lambda (shell) (cons (symbol-name shell) 'sh))
    212    (delete-dups (org--flatten-tree sh-ancestor-alist))))
    213 
    214 (defcustom org-src-lang-modes
    215   `(("C" . c)
    216     ("C++" . c++)
    217     ("asymptote" . asy)
    218     ("beamer" . latex)
    219     ("calc" . fundamental)
    220     ("cpp" . c++)
    221     ("ditaa" . artist)
    222     ("desktop" . conf-desktop)
    223     ("dot" . fundamental)
    224     ("elisp" . emacs-lisp)
    225     ("ocaml" . tuareg)
    226     ("screen" . shell-script)
    227     ("sqlite" . sql)
    228     ("toml" . conf-toml)
    229     ("shell" . sh)
    230     ,@(org-src--get-known-shells))
    231   "Alist mapping languages to their major mode.
    232 
    233 The key is the language name.  The value is the mode name, as
    234 a string or a symbol, without the \"-mode\" suffix.
    235 
    236 For many languages this is simple, but for language where this is
    237 not the case, this variable provides a way to simplify things on
    238 the user side.  For example, there is no `ocaml-mode' in Emacs,
    239 but the mode to use is `tuareg-mode'."
    240   :group 'org-edit-structure
    241   :package-version '(Org . "9.7")
    242   :type '(repeat
    243 	  (cons
    244 	   (string :tag "Language name")
    245 	   (symbol :tag "Major mode"))))
    246 
    247 (defcustom org-src-block-faces nil
    248   "Alist of faces to be used for source-block.
    249 Each element is a cell of the format
    250 
    251      (\"language\" FACE)
    252 
    253 Where FACE is either a defined face or an anonymous face.  Empty
    254 language string refers to source blocks without specified language.
    255 
    256 For instance, the following would color the background of
    257 emacs-lisp source blocks and python source blocks in purple and
    258 green, respectability.
    259 
    260   (setq org-src-block-faces
    261         \\='((\"emacs-lisp\" (:background \"#EEE2FF\"))
    262           (\"python\" (:background \"#e5ffb8\"))))"
    263   :group 'org-edit-structure
    264   :type '(repeat (list (string :tag "language")
    265                        (choice
    266                         (face :tag "Face")
    267                         (sexp :tag "Anonymous face"))))
    268   :package-version '(Org . "9.0"))
    269 
    270 (defcustom org-src-tab-acts-natively t
    271   "If non-nil, TAB uses the language's major-mode binding in code blocks."
    272   :type 'boolean
    273   :package-version '(Org . "9.4")
    274   :group 'org-babel)
    275 
    276 
    277 
    278 ;;; Internal functions and variables
    279 
    280 (defvar org-src--auto-save-timer nil
    281   "Idle Timer auto-saving remote editing buffers.")
    282 
    283 (defvar-local org-src--allow-write-back t)
    284 (put 'org-src--allow-write-back 'permanent-local t)
    285 
    286 (defvar-local org-src--babel-info nil)
    287 (put 'org-src--babel-info 'permanent-local t)
    288 
    289 (defvar-local org-src--beg-marker nil)
    290 (put 'org-src--beg-marker 'permanent-local t)
    291 
    292 (defvar-local org-src--block-indentation nil)
    293 (put 'org-src--block-indentation 'permanent-local t)
    294 
    295 (defvar-local org-src--content-indentation nil)
    296 (put 'org-src--content-indentation 'permanent-local t)
    297 
    298 (defvar-local org-src--end-marker nil)
    299 (put 'org-src--end-marker 'permanent-local t)
    300 
    301 (defvar-local org-src--from-org-mode nil)
    302 (put 'org-src--from-org-mode 'permanent-local t)
    303 
    304 (defvar-local org-src--overlay nil)
    305 (put 'org-src--overlay 'permanent-local t)
    306 
    307 (defvar-local org-src--preserve-indentation nil)
    308 (put 'org-src--preserve-indentation 'permanent-local t)
    309 
    310 (defvar-local org-src--remote nil)
    311 (put 'org-src--remote 'permanent-local t)
    312 
    313 (defvar-local org-src--saved-temp-window-config nil)
    314 (put 'org-src--saved-temp-window-config 'permanent-local t)
    315 
    316 (defvar-local org-src--source-type nil
    317   "Type of element being edited, as a symbol.")
    318 (put 'org-src--source-type 'permanent-local t)
    319 
    320 (defvar-local org-src--tab-width nil
    321   "Contains `tab-width' value from Org source buffer.
    322 However, if `indent-tabs-mode' is nil in that buffer, its value
    323 is 0.")
    324 (put 'org-src--tab-width 'permanent-local t)
    325 
    326 (defvar-local org-src-source-file-name nil
    327   "File name associated to Org source buffer, or nil.")
    328 (put 'org-src-source-file-name 'permanent-local t)
    329 
    330 (defun org-src--construct-edit-buffer-name (org-buffer-name lang)
    331   "Construct the buffer name for a source editing buffer.
    332 Format is \"*Org Src ORG-BUFFER-NAME[ LANG ]*\"."
    333   (concat "*Org Src " org-buffer-name "[ " lang " ]*"))
    334 
    335 (defun org-src--edit-buffer (beg end)
    336   "Return buffer editing area between BEG and END.
    337 Return nil if there is no such buffer."
    338   (catch 'exit
    339     (dolist (b (buffer-list))
    340       (with-current-buffer b
    341 	(and (org-src-edit-buffer-p)
    342 	     (= beg org-src--beg-marker)
    343 	     (eq (marker-buffer beg) (marker-buffer org-src--beg-marker))
    344 	     (= end org-src--end-marker)
    345 	     (eq (marker-buffer end) (marker-buffer org-src--end-marker))
    346 	     (throw 'exit b))))))
    347 
    348 (defun org-src--coordinates (pos beg end)
    349   "Return coordinates of POS relatively to BEG and END.
    350 POS, BEG and END are buffer positions.  Return value is either
    351 a cons cell (LINE . COLUMN) or symbol `end'.  See also
    352 `org-src--goto-coordinates'."
    353   (if (>= pos end) 'end
    354     (org-with-wide-buffer
    355      (goto-char (max beg pos))
    356      (cons (count-lines (save-excursion (goto-char beg) (line-beginning-position))
    357                         (line-beginning-position))
    358 	   ;; Column is relative to the end of line to avoid problems of
    359 	   ;; comma escaping or colons appended in front of the line.
    360 	   (- (point) (min end (line-end-position)))))))
    361 
    362 (defun org-src--goto-coordinates (coord beg end)
    363   "Move to coordinates COORD relatively to BEG and END.
    364 COORD are coordinates, as returned by `org-src--coordinates',
    365 which see.  BEG and END are buffer positions."
    366   (goto-char
    367    (if (eq coord 'end) (max (1- end) beg)
    368      ;; If BEG happens to be located outside of the narrowed part of
    369      ;; the buffer, widen it first.
    370      (org-with-wide-buffer
    371       (goto-char beg)
    372       (forward-line (car coord))
    373       (max (point)
    374            (+ (min end (line-end-position))
    375               (cdr coord)))))))
    376 
    377 (defun org-src--contents-area (datum)
    378   "Return contents boundaries of DATUM.
    379 DATUM is an element or object.  Return a list (BEG END CONTENTS)
    380 where BEG and END are buffer positions and CONTENTS is a string."
    381   (let ((type (org-element-type datum)))
    382     (org-with-wide-buffer
    383      (cond
    384       ((eq type 'footnote-definition)
    385        (let* ((beg (progn
    386 		     (goto-char (org-element-post-affiliated datum))
    387 		     (search-forward "]")))
    388 	      (end (or (org-element-contents-end datum) beg)))
    389 	 (list beg end (buffer-substring-no-properties beg end))))
    390       ((eq type 'inline-src-block)
    391        (let ((beg (progn (goto-char (org-element-begin datum))
    392 			 (search-forward "{" (line-end-position) t)))
    393 	     (end (progn (goto-char (org-element-end datum))
    394 			 (search-backward "}" (line-beginning-position) t))))
    395 	 (list beg end (buffer-substring-no-properties beg end))))
    396       ((eq type 'latex-fragment)
    397        (let ((beg (org-element-begin datum))
    398 	     (end (org-with-point-at (org-element-end datum)
    399 		    (skip-chars-backward " \t")
    400 		    (point))))
    401 	 (list beg end (buffer-substring-no-properties beg end))))
    402       ((org-element-contents-begin datum)
    403        (let ((beg (org-element-contents-begin datum))
    404 	     (end (org-element-contents-end datum)))
    405 	 (list beg end (buffer-substring-no-properties beg end))))
    406       ((memq type '(example-block export-block src-block comment-block))
    407        (list (progn (goto-char (org-element-post-affiliated datum))
    408 		    (line-beginning-position 2))
    409 	     (progn (goto-char (org-element-end datum))
    410 		    (skip-chars-backward " \r\t\n")
    411 		    (line-beginning-position 1))
    412 	     (org-element-property :value datum)))
    413       ((memq type '(fixed-width latex-environment table))
    414        (let ((beg (org-element-post-affiliated datum))
    415 	     (end (progn (goto-char (org-element-end datum))
    416 			 (skip-chars-backward " \r\t\n")
    417 			 (line-beginning-position 2))))
    418 	 (list beg
    419 	       end
    420 	       (if (eq type 'fixed-width) (org-element-property :value datum)
    421 		 (buffer-substring-no-properties beg end)))))
    422       (t (error "Unsupported element or object: %s" type))))))
    423 
    424 (defun org-src--make-source-overlay (beg end edit-buffer)
    425   "Create overlay between BEG and END positions and return it.
    426 EDIT-BUFFER is the buffer currently editing area between BEG and
    427 END."
    428   (let ((overlay (make-overlay beg end)))
    429     (overlay-put overlay 'face 'secondary-selection)
    430     (overlay-put overlay 'edit-buffer edit-buffer)
    431     (overlay-put overlay 'help-echo
    432 		 "Click with mouse-1 to switch to buffer editing this segment")
    433     (overlay-put overlay 'face 'secondary-selection)
    434     (overlay-put overlay 'keymap
    435 		 (let ((map (make-sparse-keymap)))
    436 		   (define-key map [mouse-1] 'org-edit-src-continue)
    437 		   map))
    438     (let ((read-only
    439 	   (list
    440 	    (lambda (&rest _)
    441 	      (user-error
    442 	       "Cannot modify an area being edited in a dedicated buffer")))))
    443       (overlay-put overlay 'modification-hooks read-only)
    444       (overlay-put overlay 'insert-in-front-hooks read-only)
    445       (overlay-put overlay 'insert-behind-hooks read-only))
    446     overlay))
    447 
    448 (defun org-src--remove-overlay ()
    449   "Remove overlay from current source buffer."
    450   (when (overlayp org-src--overlay) (delete-overlay org-src--overlay)))
    451 
    452 (defun org-src--on-datum-p (datum)
    453   "Non-nil when point is on DATUM.
    454 DATUM is an element or an object.  Consider blank lines or white
    455 spaces after it as being outside."
    456   (and (>= (point) (org-element-begin datum))
    457        (<= (point)
    458 	  (org-with-wide-buffer
    459 	   (goto-char (org-element-end datum))
    460 	   (skip-chars-backward " \r\t\n")
    461 	   (if (eq (org-element-class datum) 'element)
    462 	       (line-end-position)
    463 	     (point))))))
    464 
    465 (defun org-src-preserve-indentation-p (&optional node)
    466   "Non-nil when indentation should be preserved within NODE.
    467 When NODE is not passed, assume element at point."
    468   (let ((node (or node (org-element-at-point))))
    469     (and (org-element-type-p node '(example-block src-block))
    470          (or (org-element-property :preserve-indent node)
    471 	     org-src-preserve-indentation))))
    472 
    473 (defun org-src--contents-for-write-back-1
    474     ( write-back-buf contents
    475       &optional indentation-offset preserve-fl source-tab-width write-back)
    476   "Populate WRITE-BACK-BUF with CONTENTS in the appropriate format.
    477 
    478 INDENTATION-OFFSET, when non-nil is additional indentation to be applied
    479 to all the lines.  PRESERVE-FL means that first line should not be
    480 indented (useful for inline blocks contents that belong to paragraph).
    481 The original indentation, if any, is not altered.
    482 
    483 TAB-WIDTH is `tab-width' to be used when indenting.  The value of 0
    484 means that tabs should not be used.
    485 
    486 WRITE-BACK, when non-nil, is a function to be called with point at
    487 WRITE-BACK-BUF after inserting the original contents, but before
    488 applying extra indentation."
    489   (let ((use-tabs? (and (> source-tab-width 0) t))
    490         indent-str)
    491     (with-current-buffer write-back-buf
    492       ;; Apply WRITE-BACK function on edit buffer contents.
    493       (insert (org-no-properties contents))
    494       (goto-char (point-min))
    495       (when (functionp write-back) (save-excursion (funcall write-back)))
    496       ;; Add INDENTATION-OFFSET to every line in buffer,
    497       ;; unless indentation is meant to be preserved.
    498       (when (and indentation-offset (> indentation-offset 0))
    499         ;; The exact sequence of tabs and spaces used to indent
    500         ;; up to `indentation-offset' in the Org buffer.
    501         (setq indent-str
    502               (with-temp-buffer
    503                 ;; Reproduce indentation parameters.
    504                 (setq indent-tabs-mode use-tabs?)
    505                 (when (> source-tab-width 0)
    506                   (setq tab-width source-tab-width))
    507                 (indent-to indentation-offset)
    508                 (buffer-string)))
    509         ;; LaTeX-fragments are inline. Do not add indentation to their
    510         ;; first line.
    511         (when preserve-fl (forward-line))
    512         (while (not (eobp))
    513           ;; Keep empty src lines empty, even when src block is
    514           ;; indented on Org side.
    515           ;; See https://list.orgmode.org/725763.1632663635@apollo2.minshall.org/T/
    516           (when (not (eolp)) ; not an empty line
    517             (insert indent-str))
    518 	  (forward-line))))))
    519 
    520 (defun org-src--contents-for-write-back (write-back-buf)
    521   "Populate WRITE-BACK-BUF with contents in the appropriate format.
    522 Assume point is in the corresponding edit buffer."
    523   (org-src--contents-for-write-back-1
    524    write-back-buf
    525    ;; CONTENTS
    526    (org-with-wide-buffer (buffer-string))
    527    ;; INDENTATION
    528    (if org-src--preserve-indentation 0
    529      (+ (or org-src--block-indentation 0)
    530 	(if (memq org-src--source-type '(example-block src-block))
    531 	    org-src--content-indentation
    532 	  0)))
    533    ;; PRESERVE-FL
    534    (eq org-src--source-type 'latex-fragment)
    535    ;; TAB-WIDTH
    536    org-src--tab-width
    537    ;; WRITE-BACK
    538    org-src--allow-write-back))
    539 
    540 (defun org-src--edit-element
    541     (datum name &optional initialize write-back contents remote)
    542   "Edit DATUM contents in a dedicated buffer NAME.
    543 
    544 INITIALIZE is a function to call upon creating the buffer.
    545 
    546 When WRITE-BACK is non-nil, assume contents will replace original
    547 region.  Moreover, if it is a function, apply it in the edit
    548 buffer, from point min, before returning the contents.
    549 
    550 When CONTENTS is non-nil, display them in the edit buffer.
    551 Otherwise, show DATUM contents as specified by
    552 `org-src--contents-area'.
    553 
    554 When REMOTE is non-nil, do not try to preserve point or mark when
    555 moving from the edit area to the source.
    556 
    557 Leave point in edit buffer."
    558   (when (memq org-src-window-setup '(reorganize-frame
    559 				     split-window-below
    560 				     split-window-right))
    561     (setq org-src--saved-temp-window-config (current-window-configuration)))
    562   (let* ((area (org-src--contents-area datum))
    563 	 (beg (copy-marker (nth 0 area)))
    564 	 (end (copy-marker (nth 1 area) t))
    565 	 (old-edit-buffer (org-src--edit-buffer beg end))
    566 	 (contents (or contents (nth 2 area))))
    567     (if (and old-edit-buffer
    568 	     (or (not org-src-ask-before-returning-to-edit-buffer)
    569 		 (y-or-n-p "Return to existing edit buffer ([n] will revert changes)? ")))
    570 	;; Move to existing buffer.
    571 	(org-src-switch-to-buffer old-edit-buffer 'return)
    572       ;; Discard old edit buffer.
    573       (when old-edit-buffer
    574 	(with-current-buffer old-edit-buffer (org-src--remove-overlay))
    575 	(kill-buffer old-edit-buffer))
    576       (let* ((org-mode-p (derived-mode-p 'org-mode))
    577 	     (source-file-name (buffer-file-name (buffer-base-buffer)))
    578 	     (source-tab-width (if indent-tabs-mode tab-width 0))
    579 	     (type (org-element-type datum))
    580 	     (block-ind (org-with-point-at (org-element-begin datum)
    581                           (cond
    582                            ((save-excursion (skip-chars-backward " \t") (bolp))
    583 			    (org-current-text-indentation))
    584                            ((org-element-parent datum)
    585                             (org--get-expected-indentation
    586                              (org-element-parent datum) nil))
    587                            (t (org-current-text-indentation)))))
    588 	     (content-ind org-edit-src-content-indentation)
    589 	     (preserve-ind (org-src-preserve-indentation-p datum))
    590 	     ;; Store relative positions of mark (if any) and point
    591 	     ;; within the edited area.
    592 	     (point-coordinates (and (not remote)
    593 				     (org-src--coordinates (point) beg end)))
    594 	     (mark-coordinates (and (not remote)
    595 				    (org-region-active-p)
    596 				    (let ((m (mark)))
    597 				      (and (>= m beg) (>= end m)
    598 					   (org-src--coordinates m beg end)))))
    599 	     ;; Generate a new edit buffer.
    600 	     (buffer (generate-new-buffer name))
    601 	     ;; Add an overlay on top of source.
    602 	     (overlay (org-src--make-source-overlay beg end buffer)))
    603 	;; Switch to edit buffer.
    604 	(org-src-switch-to-buffer buffer 'edit)
    605 	;; Insert contents.
    606 	(insert contents)
    607 	(remove-text-properties (point-min) (point-max)
    608 				'(display nil invisible nil intangible nil))
    609 	(let ((lf (eq type 'latex-fragment)))
    610           (unless preserve-ind (org-do-remove-indentation (and lf block-ind) lf)))
    611 	(set-buffer-modified-p nil)
    612 	(setq buffer-file-name nil)
    613 	;; Initialize buffer.
    614 	(when (functionp initialize)
    615 	  (let ((org-inhibit-startup t))
    616 	    (condition-case-unless-debug e
    617 		(funcall initialize)
    618 	      (error (message "Initialization fails with: %S"
    619 			      (error-message-string e))))))
    620 	;; Transmit buffer-local variables for exit function.  It must
    621 	;; be done after initializing major mode, as this operation
    622 	;; may reset them otherwise.
    623 	(setq org-src--tab-width source-tab-width)
    624 	(setq org-src--from-org-mode org-mode-p)
    625 	(setq org-src--beg-marker beg)
    626 	(setq org-src--end-marker end)
    627 	(setq org-src--remote remote)
    628 	(setq org-src--source-type type)
    629 	(setq org-src--block-indentation block-ind)
    630 	(setq org-src--content-indentation content-ind)
    631 	(setq org-src--preserve-indentation preserve-ind)
    632 	(setq org-src--overlay overlay)
    633 	(setq org-src--allow-write-back write-back)
    634 	(setq org-src-source-file-name source-file-name)
    635 	;; Start minor mode.
    636 	(org-src-mode)
    637 	;; Clear undo information so we cannot undo back to the
    638 	;; initial empty buffer.
    639 	(buffer-disable-undo (current-buffer))
    640 	(buffer-enable-undo)
    641 	;; Move mark and point in edit buffer to the corresponding
    642 	;; location.
    643 	(if remote
    644 	    (progn
    645 	      ;; Put point at first non read-only character after
    646 	      ;; leading blank.
    647 	      (goto-char
    648 	       (or (text-property-any (point-min) (point-max) 'read-only nil)
    649 		   (point-max)))
    650 	      (skip-chars-forward " \r\t\n"))
    651 	  ;; Set mark and point.
    652 	  (when mark-coordinates
    653 	    (org-src--goto-coordinates mark-coordinates (point-min) (point-max))
    654 	    (push-mark (point) 'no-message t)
    655 	    (setq deactivate-mark nil))
    656 	  (org-src--goto-coordinates
    657 	   point-coordinates (point-min) (point-max)))))))
    658 
    659 
    660 
    661 ;;; Fontification of source blocks
    662 
    663 (defvar org-src-fontify-natively) ; Defined in org.el
    664 (defun org-src-font-lock-fontify-block (lang start end)
    665   "Fontify code block between START and END using LANG's syntax.
    666 This function is called by Emacs's automatic fontification, as long
    667 as `org-src-fontify-natively' is non-nil."
    668   (let ((modified (buffer-modified-p)) native-tab-width)
    669     (remove-text-properties start end '(face nil))
    670     (let ((lang-mode (org-src-get-lang-mode lang)))
    671       (when (fboundp lang-mode)
    672         (let ((string (buffer-substring-no-properties start end))
    673 	      (org-buffer (current-buffer)))
    674 	  (with-current-buffer
    675 	      (get-buffer-create
    676 	       (format " *org-src-fontification:%s*" lang-mode))
    677 	    (let ((inhibit-modification-hooks nil))
    678 	      (erase-buffer)
    679 	      ;; Add string and a final space to ensure property change.
    680 	      (insert string " "))
    681 	    (unless (eq major-mode lang-mode) (funcall lang-mode))
    682             (setq native-tab-width tab-width)
    683             (font-lock-ensure)
    684 	    (let ((pos (point-min)) next
    685 	          ;; Difference between positions here and in org-buffer.
    686 	          (offset (- start (point-min))))
    687 	      (while (setq next (next-property-change pos))
    688 	        ;; Handle additional properties from font-lock, so as to
    689 	        ;; preserve, e.g., composition.
    690                 ;; FIXME: We copy 'font-lock-face property explicitly because
    691                 ;; `font-lock-mode' is not enabled in the buffers starting from
    692                 ;; space and the remapping between 'font-lock-face and 'face
    693                 ;; text properties may thus not be set.  See commit
    694                 ;; 453d634bc.
    695 	        (dolist (prop (append '(font-lock-face face) font-lock-extra-managed-props))
    696 		  (let ((new-prop (get-text-property pos prop)))
    697                     (when new-prop
    698                       (if (not (eq prop 'invisible))
    699 		          (put-text-property
    700 		           (+ offset pos) (+ offset next) prop new-prop
    701 		           org-buffer)
    702                         ;; Special case.  `invisible' text property may
    703                         ;; clash with Org folding.  Do not assign
    704                         ;; `invisible' text property directly.  Use
    705                         ;; property alias instead.
    706                         (let ((invisibility-spec
    707                                (or
    708                                 ;; ATOM spec.
    709                                 (and (memq new-prop buffer-invisibility-spec)
    710                                      new-prop)
    711                                 ;; (ATOM . ELLIPSIS) spec.
    712                                 (assq new-prop buffer-invisibility-spec))))
    713                           (with-current-buffer org-buffer
    714                             ;; Add new property alias.
    715                             (unless (memq 'org-src-invisible
    716                                           (cdr (assq 'invisible char-property-alias-alist)))
    717                               (setq-local
    718                                char-property-alias-alist
    719                                (cons (cons 'invisible
    720 			                   (nconc (cdr (assq 'invisible char-property-alias-alist))
    721                                                   '(org-src-invisible)))
    722 		                     (remove (assq 'invisible char-property-alias-alist)
    723 			                     char-property-alias-alist))))
    724                             ;; Carry over the invisibility spec, unless
    725                             ;; already present.  Note that there might
    726                             ;; be conflicting invisibility specs from
    727                             ;; different major modes.  We cannot do much
    728                             ;; about this then.
    729                             (when invisibility-spec
    730                               (add-to-invisibility-spec invisibility-spec))
    731                             (put-text-property
    732 		             (+ offset pos) (+ offset next)
    733                              'org-src-invisible new-prop
    734 		             org-buffer)))))))
    735 	        (setq pos next)))
    736             (set-buffer-modified-p nil)))))
    737     ;; Add Org faces.
    738     (let ((src-face (nth 1 (assoc-string lang org-src-block-faces t))))
    739       (when (or (facep src-face) (listp src-face))
    740         (font-lock-append-text-property start end 'face src-face))
    741       (font-lock-append-text-property start end 'face 'org-block))
    742     ;; Display native tab indentation characters as spaces
    743     (save-excursion
    744       (goto-char start)
    745       (let ((indent-offset
    746 	     (if (org-src-preserve-indentation-p) 0
    747 	       (+ (progn (backward-char)
    748                          (org-current-text-indentation))
    749 	          org-edit-src-content-indentation))))
    750         (while (re-search-forward "^[ ]*\t" end t)
    751           (let* ((b (and (eq indent-offset (move-to-column indent-offset))
    752                          (point)))
    753                  (e (progn (skip-chars-forward "\t") (point)))
    754                  (s (and b (make-string (* (- e b) native-tab-width) ? ))))
    755             (when (and b (< b e)) (add-text-properties b e `(display ,s)))
    756             (forward-char)))))
    757     (add-text-properties
    758      start end
    759      '(font-lock-fontified t fontified t font-lock-multiline t))
    760     (set-buffer-modified-p modified)))
    761 
    762 (defun org-fontify-inline-src-blocks (limit)
    763   "Try to apply `org-fontify-inline-src-blocks-1'."
    764   (condition-case-unless-debug nil
    765       (org-fontify-inline-src-blocks-1 limit)
    766     (error (message "Org mode fontification error in %S at %d"
    767                     (current-buffer)
    768                     (line-number-at-pos)))))
    769 
    770 (defun org-fontify-inline-src-blocks-1 (limit)
    771   "Fontify inline src_LANG blocks, from `point' up to LIMIT."
    772   (let ((case-fold-search t))
    773     ;; The regexp below is copied from `org-element-inline-src-block-parser'.
    774     (while (re-search-forward "\\_<src_\\([^ \t\n[{]+\\)[{[]?" limit t)
    775       (let ((beg (match-beginning 0))
    776             (lang-beg (match-beginning 1))
    777             (lang-end (match-end 1))
    778             pt)
    779         (add-face-text-property beg lang-end 'org-inline-src-block)
    780         (add-face-text-property beg lang-beg 'shadow)
    781         (add-face-text-property lang-beg lang-end 'org-meta-line)
    782         (setq pt (goto-char lang-end))
    783         ;; `org-element--parse-paired-brackets' doesn't take a limit, so to
    784         ;; prevent it searching the entire rest of the buffer we temporarily
    785         ;; narrow the active region.
    786         (save-restriction
    787           (narrow-to-region beg
    788                             (min limit (or (save-excursion
    789                                              (and (search-forward"\n" limit t 2)
    790                                                   (point)))
    791                                            (point-max))))
    792           (when (ignore-errors (org-element--parse-paired-brackets ?\[))
    793             (add-face-text-property pt (point) 'org-inline-src-block)
    794             (setq pt (point)))
    795           (when (ignore-errors (org-element--parse-paired-brackets ?\{))
    796             (remove-text-properties pt (point) '(face nil))
    797             (add-face-text-property pt (1+ pt) '(org-inline-src-block shadow))
    798             (unless (= (1+ pt) (1- (point)))
    799               (if org-src-fontify-natively
    800                   (org-src-font-lock-fontify-block
    801                    (buffer-substring-no-properties lang-beg lang-end)
    802                    (1+ pt) (1- (point)))
    803                 (font-lock-append-text-property
    804                  (1+ pt) (1- (point)) 'face 'org-inline-src-block)))
    805             (add-face-text-property (1- (point)) (point) '(org-inline-src-block shadow))
    806             (setq pt (point)))))
    807       t)))
    808 
    809 
    810 ;;; Escape contents
    811 
    812 (defun org-escape-code-in-region (beg end)
    813   "Escape lines between BEG and END.
    814 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
    815 \",#+\" by appending a comma to it."
    816   (interactive "r")
    817   (save-excursion
    818     (goto-char end)
    819     (while (re-search-backward "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" beg t)
    820       (save-excursion (replace-match ",\\1" nil nil nil 1)))))
    821 
    822 (defun org-escape-code-in-string (s)
    823   "Escape lines in string S.
    824 Escaping happens when a line starts with \"*\", \"#+\", \",*\" or
    825 \",#+\" by appending a comma to it."
    826   (replace-regexp-in-string "^[ \t]*\\(,*\\(?:\\*\\|#\\+\\)\\)" ",\\1"
    827 			    s nil nil 1))
    828 
    829 (defun org-unescape-code-in-region (beg end)
    830   "Un-escape lines between BEG and END.
    831 Un-escaping happens by removing the first comma on lines starting
    832 with \",*\", \",#+\", \",,*\" and \",,#+\"."
    833   (interactive "r")
    834   (save-excursion
    835     (goto-char end)
    836     (while (re-search-backward "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" beg t)
    837       (save-excursion (replace-match "" nil nil nil 1)))))
    838 
    839 (defun org-unescape-code-in-string (s)
    840   "Un-escape lines in string S.
    841 Un-escaping happens by removing the first comma on lines starting
    842 with \",*\", \",#+\", \",,*\" and \",,#+\"."
    843   (replace-regexp-in-string
    844    "^[ \t]*,*\\(,\\)\\(?:\\*\\|#\\+\\)" "" s nil nil 1))
    845 
    846 
    847 
    848 ;;; Org src minor mode
    849 
    850 (defvar org-src-mode-map
    851   (let ((map (make-sparse-keymap)))
    852     (define-key map "\C-c'" 'org-edit-src-exit)
    853     (define-key map "\C-c\C-k" 'org-edit-src-abort)
    854     (define-key map "\C-x\C-s" 'org-edit-src-save)
    855     map))
    856 
    857 (define-minor-mode org-src-mode
    858   "Minor mode for language major mode buffers generated by Org.
    859 \\<org-mode-map>
    860 This minor mode is turned on in two situations:
    861   - when editing a source code snippet with `\\[org-edit-special]'
    862   - when formatting a source code snippet for export with htmlize.
    863 
    864 \\{org-src-mode-map}
    865 
    866 See also `org-src-mode-hook'."
    867   :lighter " OrgSrc"
    868   (when org-edit-src-persistent-message
    869     (setq header-line-format
    870 	  (substitute-command-keys
    871 	   (if org-src--allow-write-back
    872 	       "Edit, then exit with `\\[org-edit-src-exit]' or abort with \
    873 `\\[org-edit-src-abort]'"
    874 	     "Exit with `\\[org-edit-src-exit]' or abort with \
    875 `\\[org-edit-src-abort]'"))))
    876   ;; Possibly activate various auto-save features (for the edit buffer
    877   ;; or the source buffer).
    878   (when org-edit-src-turn-on-auto-save
    879     (setq buffer-auto-save-file-name
    880 	  (concat (make-temp-name "org-src-")
    881 		  (format-time-string "-%Y-%d-%m")
    882 		  ".txt")))
    883   (unless (or org-src--auto-save-timer
    884 	      (= 0 org-edit-src-auto-save-idle-delay))
    885     (setq org-src--auto-save-timer
    886 	  (run-with-idle-timer
    887 	   org-edit-src-auto-save-idle-delay t
    888 	   (lambda ()
    889 	     (save-excursion
    890 	       (let (edit-flag)
    891 		 (dolist (b (buffer-list))
    892 		   (with-current-buffer b
    893 		     (when (org-src-edit-buffer-p)
    894 		       (unless edit-flag (setq edit-flag t))
    895 		       (when (buffer-modified-p) (org-edit-src-save)))))
    896 		 (unless edit-flag
    897 		   (cancel-timer org-src--auto-save-timer)
    898 		   (setq org-src--auto-save-timer nil)))))))))
    899 
    900 (defun org-src-mode-configure-edit-buffer ()
    901   "Configure the src edit buffer."
    902   (when (bound-and-true-p org-src--from-org-mode)
    903     (add-hook 'kill-buffer-hook #'org-src--remove-overlay nil 'local)
    904     (if (bound-and-true-p org-src--allow-write-back)
    905 	(progn
    906 	  (setq buffer-offer-save t)
    907 	  (setq write-contents-functions '(org-edit-src-save)))
    908       (setq buffer-read-only t))))
    909 
    910 (add-hook 'org-src-mode-hook #'org-src-mode-configure-edit-buffer)
    911 
    912 
    913 
    914 ;;; Babel related functions
    915 
    916 (defun org-src-associate-babel-session (info)
    917   "Associate edit buffer with comint session.
    918 INFO should be a list similar in format to the return value of
    919 `org-babel-get-src-block-info'."
    920   (interactive)
    921   (let ((session (cdr (assq :session (nth 2 info)))))
    922     (and session (not (string= session "none"))
    923 	 (let ((f (intern (format "org-babel-%s-associate-session"
    924                                   (nth 0 info)))))
    925            (and (fboundp f) (funcall f session))))))
    926 
    927 (defun org-src-babel-configure-edit-buffer ()
    928   "Configure src editing buffer."
    929   (when org-src--babel-info
    930     (org-src-associate-babel-session org-src--babel-info)))
    931 
    932 (add-hook 'org-src-mode-hook #'org-src-babel-configure-edit-buffer)
    933 
    934 
    935 ;;; Public API
    936 
    937 (defmacro org-src-do-at-code-block (&rest body)
    938   "Execute BODY from an edit buffer in the Org mode buffer."
    939   (declare (debug (body)))
    940   `(let ((beg-marker org-src--beg-marker))
    941      (when beg-marker
    942        (with-current-buffer (marker-buffer beg-marker)
    943 	 (goto-char beg-marker)
    944 	 ,@body))))
    945 
    946 (defun org-src-do-key-sequence-at-code-block (&optional key)
    947   "Execute key sequence at code block in the source Org buffer.
    948 The command bound to KEY in the Org-babel key map is executed
    949 remotely with point temporarily at the start of the code block in
    950 the Org buffer.
    951 
    952 This command is not bound to a key by default, to avoid conflicts
    953 with language major mode bindings.  To bind it to \\`C-c @' in all
    954 language major modes, you could use
    955 
    956   (add-hook \\='org-src-mode-hook
    957             (lambda () (define-key org-src-mode-map \"\\C-c@\"
    958                     \\='org-src-do-key-sequence-at-code-block)))
    959 
    960 In that case, for example, \\`C-c @ t' issued in code edit buffers
    961 would tangle the current Org code block, \\`C-c @ e' would execute
    962 the block and \\`C-c @ h' would display the other available
    963 Org-babel commands."
    964   (interactive "kOrg-babel key: ")
    965   (if (equal key (kbd "C-g")) (keyboard-quit)
    966     (org-edit-src-save)
    967     (org-src-do-at-code-block
    968      (call-interactively (lookup-key org-babel-map key)))))
    969 
    970 (defun org-src-get-lang-mode (lang)
    971   "Return major mode that should be used for LANG.
    972 LANG is a string, and the returned major mode is a symbol."
    973   (intern
    974    (concat
    975     (let ((l (or (cdr (assoc lang org-src-lang-modes)) lang)))
    976       (if (symbolp l) (symbol-name l) l))
    977     "-mode")))
    978 
    979 (defun org-src-edit-buffer-p (&optional buffer)
    980   "Non-nil when current buffer is a source editing buffer.
    981 If BUFFER is non-nil, test it instead."
    982   (let ((buffer (org-base-buffer (or buffer (current-buffer)))))
    983     (and (buffer-live-p buffer)
    984 	 (local-variable-p 'org-src--beg-marker buffer)
    985 	 (local-variable-p 'org-src--end-marker buffer))))
    986 
    987 (defun org-src-source-buffer ()
    988   "Return source buffer edited in current buffer.
    989 Raise an error when current buffer is not a source editing buffer."
    990   (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
    991   (or (marker-buffer org-src--beg-marker)
    992       (error "No source buffer available for current editing session")))
    993 
    994 (defun org-src-source-type ()
    995   "Return type of element edited in current buffer.
    996 Raise an error when current buffer is not a source editing buffer."
    997   (unless (org-src-edit-buffer-p) (error "Not in a source buffer"))
    998   org-src--source-type)
    999 
   1000 (defun org-src-switch-to-buffer (buffer context)
   1001   "Switch to BUFFER considering CONTEXT and `org-src-window-setup'."
   1002   (pcase org-src-window-setup
   1003     (`plain
   1004      (when (eq context 'exit) (quit-restore-window))
   1005      (pop-to-buffer buffer))
   1006     (`current-window (pop-to-buffer-same-window buffer))
   1007     (`other-window
   1008      (let ((cur-win (selected-window)))
   1009        (switch-to-buffer-other-window buffer)
   1010        (when (eq context 'exit) (quit-restore-window cur-win))))
   1011     (`split-window-below
   1012      (if (eq context 'exit)
   1013 	 (delete-window)
   1014        (select-window (split-window-vertically)))
   1015      (pop-to-buffer-same-window buffer))
   1016     (`split-window-right
   1017      (if (eq context 'exit)
   1018 	 (delete-window)
   1019        (select-window (split-window-horizontally)))
   1020      (pop-to-buffer-same-window buffer))
   1021     (`other-frame
   1022      (pcase context
   1023        (`exit
   1024 	(let ((frame (selected-frame)))
   1025 	  (switch-to-buffer-other-frame buffer)
   1026 	  (delete-frame frame)))
   1027        (`save
   1028 	(kill-buffer (current-buffer))
   1029 	(pop-to-buffer-same-window buffer))
   1030        (_ (switch-to-buffer-other-frame buffer))))
   1031     (`reorganize-frame
   1032      (pcase context
   1033        (`edit (pop-to-buffer buffer '(org-display-buffer-split)))
   1034        (`exit (pop-to-buffer buffer '(org-display-buffer-full-frame)))
   1035        (_ (switch-to-buffer-other-window buffer))))
   1036     (`switch-invisibly (set-buffer buffer))
   1037     (_
   1038      (message "Invalid value %s for `org-src-window-setup'"
   1039 	      org-src-window-setup)
   1040      (pop-to-buffer-same-window buffer))))
   1041 
   1042 (defun org-src-coderef-format (&optional element)
   1043   "Return format string for block at point.
   1044 
   1045 When optional argument ELEMENT is provided, use that block.
   1046 Otherwise, assume point is either at a source block, at an
   1047 example block.
   1048 
   1049 If point is in an edit buffer, retrieve format string associated
   1050 to the remote source block."
   1051   (cond
   1052    ((and element (org-element-property :label-fmt element)))
   1053    ((org-src-edit-buffer-p) (org-src-do-at-code-block (org-src-coderef-format)))
   1054    ((org-element-property :label-fmt (org-element-at-point)))
   1055    (t org-coderef-label-format)))
   1056 
   1057 (defun org-src-coderef-regexp (fmt &optional label)
   1058   "Return regexp matching a coderef format string FMT.
   1059 
   1060 When optional argument LABEL is non-nil, match coderef for that
   1061 label only.
   1062 
   1063 Match group 1 contains the full coderef string with surrounding
   1064 white spaces.  Match group 2 contains the same string without any
   1065 surrounding space.  Match group 3 contains the label.
   1066 
   1067 A coderef format regexp can only match at the end of a line."
   1068   (format "\\([ \t]*\\(%s\\)[ \t]*\\)$"
   1069 	  (replace-regexp-in-string
   1070 	   "%s"
   1071 	   (if label (regexp-quote label) "\\([-a-zA-Z0-9_][-a-zA-Z0-9_ ]*\\)")
   1072 	   (regexp-quote fmt)
   1073 	   nil t)))
   1074 
   1075 (defun org-edit-footnote-reference ()
   1076   "Edit definition of footnote reference at point."
   1077   (interactive)
   1078   (let* ((context (org-element-context))
   1079 	 (label (org-element-property :label context)))
   1080     (unless (and (org-element-type-p context 'footnote-reference)
   1081 		 (org-src--on-datum-p context))
   1082       (user-error "Not on a footnote reference"))
   1083     (unless label (user-error "Cannot edit remotely anonymous footnotes"))
   1084     (let* ((definition (org-with-wide-buffer
   1085 			(org-footnote-goto-definition label)
   1086 			(backward-char)
   1087 			(org-element-context)))
   1088 	   (inline? (org-element-type-p definition 'footnote-reference))
   1089 	   (contents
   1090 	    (org-with-wide-buffer
   1091 	     (buffer-substring-no-properties
   1092 	      (or (org-element-post-affiliated definition)
   1093 		  (org-element-begin definition))
   1094 	      (cond
   1095 	       (inline? (1+ (org-element-contents-end definition)))
   1096 	       ((org-element-contents-end definition))
   1097 	       (t (goto-char (org-element-post-affiliated definition))
   1098 		  (line-end-position)))))))
   1099       (add-text-properties
   1100        0
   1101        (progn (string-match (if inline? "\\`\\[fn:.*?:" "\\`.*?\\]") contents)
   1102 	      (match-end 0))
   1103        '(read-only "Cannot edit footnote label" front-sticky t rear-nonsticky t)
   1104        contents)
   1105       (when inline?
   1106 	(let ((l (length contents)))
   1107 	  (add-text-properties
   1108 	   (1- l) l
   1109 	   '(read-only "Cannot edit past footnote reference"
   1110 		       front-sticky nil rear-nonsticky nil)
   1111 	   contents)))
   1112       (org-src--edit-element
   1113        definition
   1114        (format "*Edit footnote [%s]*" label)
   1115        (let ((source (current-buffer)))
   1116 	 (lambda ()
   1117 	   (org-mode)
   1118 	   (org-clone-local-variables source)))
   1119        (lambda ()
   1120 	 (if (not inline?) (delete-region (point) (search-forward "]"))
   1121 	   (delete-region (point) (search-forward ":" nil t 2))
   1122 	   (delete-region (1- (point-max)) (point-max))
   1123 	   (when (re-search-forward "\n[ \t]*\n" nil t)
   1124 	     (user-error "Inline definitions cannot contain blank lines"))
   1125 	   ;; If footnote reference belongs to a table, make sure to
   1126 	   ;; remove any newline characters in order to preserve
   1127 	   ;; table's structure.
   1128 	   (when (org-element-lineage definition 'table-cell)
   1129 	     (while (search-forward "\n" nil t) (replace-match " ")))))
   1130        contents
   1131        'remote))
   1132     ;; Report success.
   1133     t))
   1134 
   1135 (defun org-edit-table.el ()
   1136   "Edit \"table.el\" table at point.
   1137 \\<org-src-mode-map>
   1138 A new buffer is created and the table is copied into it.  Then
   1139 the table is recognized with `table-recognize'.  When done
   1140 editing, exit with `\\[org-edit-src-exit]'.  The edited text will \
   1141 then replace
   1142 the area in the Org mode buffer.
   1143 
   1144 Throw an error when not at such a table."
   1145   (interactive)
   1146   (let ((element (org-element-at-point)))
   1147     (unless (and (org-element-type-p element 'table)
   1148 		 (eq (org-element-property :type element) 'table.el)
   1149 		 (org-src--on-datum-p element))
   1150       (user-error "Not in a table.el table"))
   1151     (org-src--edit-element
   1152      element
   1153      (org-src--construct-edit-buffer-name (buffer-name) "Table")
   1154      #'text-mode t)
   1155     (when (bound-and-true-p flyspell-mode) (flyspell-mode -1))
   1156     (table-recognize)
   1157     t))
   1158 
   1159 (defun org-edit-latex-fragment ()
   1160   "Edit LaTeX fragment at point."
   1161   (interactive)
   1162   (let ((context (org-element-context)))
   1163     (unless (and (org-element-type-p context 'latex-fragment)
   1164 		 (org-src--on-datum-p context))
   1165       (user-error "Not on a LaTeX fragment"))
   1166     (let* ((contents
   1167 	    (buffer-substring-no-properties
   1168 	     (org-element-begin context)
   1169 	     (- (org-element-end context)
   1170 		(org-element-post-blank context))))
   1171 	   (delim-length (if (string-match "\\`\\$[^$]" contents) 1 2)))
   1172       ;; Make the LaTeX deliminators read-only.
   1173       (add-text-properties 0 delim-length
   1174 			   (list 'read-only "Cannot edit LaTeX deliminator"
   1175 				 'front-sticky t
   1176 				 'rear-nonsticky t)
   1177 			   contents)
   1178       (let ((l (length contents)))
   1179 	(add-text-properties (- l delim-length) l
   1180 			     (list 'read-only "Cannot edit LaTeX deliminator"
   1181 				   'front-sticky nil
   1182 				   'rear-nonsticky nil)
   1183 			     contents))
   1184       (org-src--edit-element
   1185        context
   1186        (org-src--construct-edit-buffer-name (buffer-name) "LaTeX fragment")
   1187        (org-src-get-lang-mode "latex")
   1188        (lambda ()
   1189 	 ;; Blank lines break things, replace with a single newline.
   1190 	 (while (re-search-forward "\n[ \t]*\n" nil t) (replace-match "\n"))
   1191 	 ;; If within a table a newline would disrupt the structure,
   1192 	 ;; so remove newlines.
   1193 	 (goto-char (point-min))
   1194 	 (when (org-element-lineage context 'table-cell)
   1195 	   (while (search-forward "\n" nil t) (replace-match " "))))
   1196        contents))
   1197     t))
   1198 
   1199 (defun org-edit-latex-environment ()
   1200   "Edit LaTeX environment at point.
   1201 \\<org-src-mode-map>
   1202 The LaTeX environment is copied into a new buffer.  Major mode is
   1203 set to the one associated to \"latex\" in `org-src-lang-modes',
   1204 or to `latex-mode' if there is none.
   1205 
   1206 When done, exit with `\\[org-edit-src-exit]'.  The edited text \
   1207 will then replace
   1208 the LaTeX environment in the Org mode buffer."
   1209   (interactive)
   1210   (let ((element (org-element-at-point)))
   1211     (unless (and (org-element-type-p element 'latex-environment)
   1212 		 (org-src--on-datum-p element))
   1213       (user-error "Not in a LaTeX environment"))
   1214     (org-src--edit-element
   1215      element
   1216      (org-src--construct-edit-buffer-name (buffer-name) "LaTeX environment")
   1217      (org-src-get-lang-mode "latex")
   1218      t)
   1219     t))
   1220 
   1221 (defun org-edit-export-block ()
   1222   "Edit export block at point.
   1223 \\<org-src-mode-map>
   1224 A new buffer is created and the block is copied into it, and the
   1225 buffer is switched into an appropriate major mode.  See also
   1226 `org-src-lang-modes'.
   1227 
   1228 When done, exit with `\\[org-edit-src-exit]'.  The edited text \
   1229 will then replace
   1230 the area in the Org mode buffer.
   1231 
   1232 Throw an error when not at an export block."
   1233   (interactive)
   1234   (let ((element (org-element-at-point)))
   1235     (unless (and (org-element-type-p element 'export-block)
   1236 		 (org-src--on-datum-p element))
   1237       (user-error "Not in an export block"))
   1238     (let* ((type (downcase (or (org-element-property :type element)
   1239 			       ;; Missing export-block type.  Fallback
   1240 			       ;; to default mode.
   1241 			       "fundamental")))
   1242 	   (mode (org-src-get-lang-mode type)))
   1243       (unless (functionp mode) (error "No such language mode: %s" mode))
   1244       (org-src--edit-element
   1245        element
   1246        (org-src--construct-edit-buffer-name (buffer-name) type)
   1247        mode
   1248        (lambda () (org-escape-code-in-region (point-min) (point-max)))))
   1249     t))
   1250 
   1251 (defun org-edit-comment-block ()
   1252   "Edit comment block at point.
   1253 \\<org-src-mode-map>
   1254 A new buffer is created and the block is copied into it, and the
   1255 buffer is switched into Org mode.
   1256 
   1257 When done, exit with `\\[org-edit-src-exit]'.  The edited text will
   1258 then replace the area in the Org mode buffer.
   1259 
   1260 Throw an error when not at a comment block."
   1261   (interactive)
   1262   (let ((element (org-element-at-point)))
   1263     (unless (and (org-element-type-p element 'comment-block)
   1264 		 (org-src--on-datum-p element))
   1265       (user-error "Not in a comment block"))
   1266     (org-src--edit-element
   1267      element
   1268      (org-src--construct-edit-buffer-name (buffer-name) "org")
   1269      'org-mode
   1270      (lambda () (org-escape-code-in-region (point-min) (point-max)))
   1271      (org-unescape-code-in-string (org-element-property :value element)))
   1272     t))
   1273 
   1274 (defun org-edit-src-code (&optional code edit-buffer-name)
   1275   "Edit the source or example block at point.
   1276 \\<org-src-mode-map>
   1277 The code is copied to a separate buffer and the appropriate mode
   1278 is turned on.  When done, exit with `\\[org-edit-src-exit]'.  This \
   1279 will remove the
   1280 original code in the Org buffer, and replace it with the edited
   1281 version.  See `org-src-window-setup' to configure the display of
   1282 windows containing the Org buffer and the code buffer.
   1283 
   1284 When optional argument CODE is a string, edit it in a dedicated
   1285 buffer instead.
   1286 
   1287 When optional argument EDIT-BUFFER-NAME is non-nil, use it as the
   1288 name of the sub-editing buffer."
   1289   (interactive)
   1290   (let* ((element (org-element-at-point))
   1291 	 (type (org-element-type element)))
   1292     (unless (and (memq type '(example-block src-block))
   1293 		 (org-src--on-datum-p element))
   1294       (user-error "Not in a source or example block"))
   1295     (let* ((lang
   1296 	    (if (eq type 'src-block) (org-element-property :language element)
   1297 	      "example"))
   1298 	   (lang-f (and (eq type 'src-block) (org-src-get-lang-mode lang)))
   1299 	   (babel-info (and (eq type 'src-block)
   1300 			    (org-babel-get-src-block-info 'no-eval)))
   1301 	   deactivate-mark)
   1302       (when (and (eq type 'src-block) (not (functionp lang-f)))
   1303 	(error "No such language mode: %s" lang-f))
   1304       (org-src--edit-element
   1305        element
   1306        (or edit-buffer-name
   1307 	   (org-src--construct-edit-buffer-name (buffer-name) lang))
   1308        (lambda ()
   1309          (when lang-f (funcall lang-f))
   1310          (setq-local org-coderef-label-format
   1311 		     (or (org-element-property :label-fmt element)
   1312 		         org-coderef-label-format))
   1313          (when (eq type 'src-block)
   1314 	   (setq org-src--babel-info babel-info)))
   1315        (and (null code)
   1316 	    (lambda () (org-escape-code-in-region (point-min) (point-max))))
   1317        (and code (org-unescape-code-in-string code)))
   1318       ;; Finalize buffer.
   1319       (when (eq type 'src-block)
   1320 	(let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
   1321 	  (when (fboundp edit-prep-func)
   1322 	    (funcall edit-prep-func babel-info))))
   1323       t)))
   1324 
   1325 (defun org-edit-inline-src-code ()
   1326   "Edit inline source code at point."
   1327   (interactive)
   1328   (let ((context (org-element-context)))
   1329     (unless (and (org-element-type-p context 'inline-src-block)
   1330 		 (org-src--on-datum-p context))
   1331       (user-error "Not on inline source code"))
   1332     (let* ((lang (org-element-property :language context))
   1333 	   (lang-f (org-src-get-lang-mode lang))
   1334 	   (babel-info (org-babel-get-src-block-info 'no-eval))
   1335 	   deactivate-mark)
   1336       (unless (functionp lang-f) (error "No such language mode: %s" lang-f))
   1337       (org-src--edit-element
   1338        context
   1339        (org-src--construct-edit-buffer-name (buffer-name) lang)
   1340        lang-f
   1341        (lambda ()
   1342 	 ;; Inline source blocks are limited to one line.
   1343 	 (while (re-search-forward "\n[ \t]*" nil t) (replace-match " "))
   1344 	 ;; Trim contents.
   1345 	 (goto-char (point-min))
   1346 	 (skip-chars-forward " \t")
   1347 	 (delete-region (point-min) (point))
   1348 	 (goto-char (point-max))
   1349 	 (skip-chars-backward " \t")
   1350 	 (delete-region (point) (point-max))))
   1351       ;; Finalize buffer.
   1352       (setq org-src--babel-info babel-info)
   1353       (setq org-src--preserve-indentation t)
   1354       (let ((edit-prep-func (intern (concat "org-babel-edit-prep:" lang))))
   1355 	(when (fboundp edit-prep-func) (funcall edit-prep-func babel-info)))
   1356       ;; Return success.
   1357       t)))
   1358 
   1359 (defun org-edit-fixed-width-region ()
   1360   "Edit the fixed-width ASCII drawing at point.
   1361 \\<org-src-mode-map>
   1362 This must be a region where each line starts with a colon
   1363 followed by a space or a newline character.
   1364 
   1365 A new buffer is created and the fixed-width region is copied into
   1366 it, and the buffer is switched into the major mode defined in
   1367 `org-edit-fixed-width-region-mode', which see.
   1368 
   1369 When done, exit with `\\[org-edit-src-exit]'.  The edited text \
   1370 will then replace
   1371 the area in the Org mode buffer."
   1372   (interactive)
   1373   (let ((element (org-element-at-point)))
   1374     (unless (and (org-element-type-p element 'fixed-width)
   1375 		 (org-src--on-datum-p element))
   1376       (user-error "Not in a fixed-width area"))
   1377     (org-src--edit-element
   1378      element
   1379      (org-src--construct-edit-buffer-name (buffer-name) "Fixed Width")
   1380      org-edit-fixed-width-region-mode
   1381      (lambda () (while (not (eobp)) (insert ": ") (forward-line))))
   1382     ;; Return success.
   1383     t))
   1384 
   1385 (defun org-edit-src-abort ()
   1386   "Abort editing of the src code and return to the Org buffer."
   1387   (interactive)
   1388   (let (org-src--allow-write-back) (org-edit-src-exit)))
   1389 
   1390 (defun org-edit-src-continue (event)
   1391   "Unconditionally return to buffer editing area under point.
   1392 Throw an error if there is no such buffer.
   1393 EVENT is passed to `mouse-set-point'."
   1394   (interactive "e")
   1395   (mouse-set-point event)
   1396   (let ((buf (get-char-property (point) 'edit-buffer)))
   1397     (if buf (org-src-switch-to-buffer buf 'continue)
   1398       (user-error "No sub-editing buffer for area at point"))))
   1399 
   1400 (defun org-edit-src-save ()
   1401   "Save parent buffer with current state source-code buffer."
   1402   (interactive)
   1403   (unless (org-src-edit-buffer-p) (user-error "Not in a sub-editing buffer"))
   1404   (set-buffer-modified-p nil)
   1405   (let ((write-back-buf (generate-new-buffer "*org-src-write-back*"))
   1406 	(beg org-src--beg-marker)
   1407 	(end org-src--end-marker)
   1408 	(overlay org-src--overlay))
   1409     (org-src--contents-for-write-back write-back-buf)
   1410     (with-current-buffer (org-src-source-buffer)
   1411       (undo-boundary)
   1412       (goto-char beg)
   1413       ;; Temporarily disable read-only features of OVERLAY in order to
   1414       ;; insert new contents.
   1415       (delete-overlay overlay)
   1416       (let ((expecting-bol (bolp)))
   1417 	(if (version< emacs-version "27.1")
   1418 	    (progn (delete-region beg end)
   1419 		   (insert (with-current-buffer write-back-buf (buffer-string))))
   1420 	  (save-restriction
   1421 	    (narrow-to-region beg end)
   1422 	    (org-replace-buffer-contents write-back-buf 0.1 nil)
   1423 	    (goto-char (point-max))))
   1424 	(when (and expecting-bol (not (bolp))) (insert "\n")))
   1425       (kill-buffer write-back-buf)
   1426       (save-buffer)
   1427       (move-overlay overlay beg (point))))
   1428   ;; `write-contents-functions' requires the function to return
   1429   ;; a non-nil value so that other functions are not called.
   1430   t)
   1431 
   1432 (defun org-edit-src-exit ()
   1433   "Kill current sub-editing buffer and return to source buffer."
   1434   (interactive)
   1435   (unless (org-src-edit-buffer-p)
   1436     (error "Not in a sub-editing buffer"))
   1437   (let* ((beg org-src--beg-marker)
   1438 	 (end org-src--end-marker)
   1439 	 (write-back org-src--allow-write-back)
   1440 	 (remote org-src--remote)
   1441 	 (coordinates (and (not remote)
   1442 			   (org-src--coordinates (point) 1 (point-max))))
   1443 	 (write-back-buf
   1444           (and write-back (generate-new-buffer "*org-src-write-back*"))))
   1445     (when write-back (org-src--contents-for-write-back write-back-buf))
   1446     (set-buffer-modified-p nil)
   1447     ;; Switch to source buffer.  Kill sub-editing buffer.
   1448     (let ((edit-buffer (current-buffer))
   1449 	  (source-buffer (marker-buffer beg)))
   1450       (unless source-buffer
   1451         (when write-back-buf (kill-buffer write-back-buf))
   1452         (error "Source buffer disappeared.  Aborting"))
   1453       (org-src-switch-to-buffer source-buffer 'exit)
   1454       (kill-buffer edit-buffer))
   1455     ;; Insert modified code.  Ensure it ends with a newline character.
   1456     (org-with-wide-buffer
   1457      (when (and write-back
   1458                 (not (equal (buffer-substring beg end)
   1459 			    (with-current-buffer write-back-buf
   1460                               (buffer-string)))))
   1461        (undo-boundary)
   1462        (goto-char beg)
   1463        (let ((expecting-bol (bolp)))
   1464 	 (if (version< emacs-version "27.1")
   1465 	     (progn (delete-region beg end)
   1466 		    (insert (with-current-buffer write-back-buf
   1467                               (buffer-string))))
   1468 	   (save-restriction
   1469 	     (narrow-to-region beg end)
   1470 	     (org-replace-buffer-contents write-back-buf 0.1 nil)
   1471 	     (goto-char (point-max))))
   1472 	 (when (and expecting-bol (not (bolp))) (insert "\n")))))
   1473     (when write-back-buf (kill-buffer write-back-buf))
   1474     ;; If we are to return to source buffer, put point at an
   1475     ;; appropriate location.  In particular, if block is hidden, move
   1476     ;; to the beginning of the block opening line.
   1477     (unless remote
   1478       (goto-char beg)
   1479       (cond
   1480        ;; Block is hidden; move at start of block.
   1481        ((org-fold-folded-p nil 'block) (forward-line -1))
   1482        (write-back (org-src--goto-coordinates coordinates beg end))))
   1483     ;; Clean up left-over markers and restore window configuration.
   1484     (set-marker beg nil)
   1485     (set-marker end nil)
   1486     (when org-src--saved-temp-window-config
   1487       (unwind-protect
   1488 	  (set-window-configuration org-src--saved-temp-window-config)
   1489 	(setq org-src--saved-temp-window-config nil)))))
   1490 
   1491 (provide 'org-src)
   1492 
   1493 ;;; org-src.el ends here