diff --git a/README.org b/README.org index 5ca7385ff..aa7bbc28b 100644 --- a/README.org +++ b/README.org @@ -65,7 +65,6 @@ - [[#network-is-blocked][Network is blocked]] - [[#email][Email]] - [[#cannot-download-packages][Cannot download packages?]] - - [[#installing-missing-packages-by-using-gnu-elpa][Installing missing packages by using GNU ELPA]] - [[#use-flycheck-to-syntax-check-code][Use flycheck to syntax check code]] - [[#disable-vim-key-bindings][Disable Vim key bindings]] - [[#evil-setup][Evil setup]] @@ -588,17 +587,6 @@ If you use Gnus for email, check =init-gnus.el= and read [[https://github.com/re Some package cannot be downloaded automatically because of network problem. Run =M-x package-refresh-content=, restart Emacs, reinstall package. -** Installing missing packages by using [[https://elpa.gnu.org/][GNU ELPA]] -The GNU ELPA repository contains FSF-sanctioned Emacs packages. It is the default repository used by =package.el=. - -GNU ELPA are *deactivated* in this setup. - -GNU ELPA is deactivated for below reasons, -- 99% packages can be found from other repositories like MELPA -- "~/.emacs.d/localelpa/" contains GNU ELPA packages required by this setup - -To re-activate GNU ELPA, please search the line "uncomment below line if you need use GNU ELPA" in =init-elpa.el= . - ** Use flycheck to syntax check code If you prefer =flycheck= instead the default syntax check solution =lazyflymake= built into this configuration. diff --git a/lisp/init-elpa.el b/lisp/init-elpa.el index b0eaa1733..cfe925aad 100644 --- a/lisp/init-elpa.el +++ b/lisp/init-elpa.el @@ -160,8 +160,7 @@ ;; dependency on 3rd party web site. (setq package-archives '( - ;; uncomment below line if you need use GNU ELPA - ;; ("gnu" . "https://elpa.gnu.org/packages/") + ("gnu" . "https://elpa.gnu.org/packages/") ("melpa" . "https://melpa.org/packages/") ("melpa-stable" . "https://stable.melpa.org/packages/") @@ -169,14 +168,14 @@ ;; is slow or shutdown. ;; ;; {{ Option 1: 163 mirror repository: - ;; ;; ("gnu" . "https://mirrors.163.com/elpa/gnu/") + ;; ("gnu" . "https://mirrors.163.com/elpa/gnu/") ;; ("melpa" . "https://mirrors.163.com/elpa/melpa/") ;; ("melpa-stable" . "https://mirrors.163.com/elpa/stable-melpa/") ;; ;; }} ;; ;; {{ Option 2: tsinghua mirror repository ;; ;; @see https://mirror.tuna.tsinghua.edu.cn/help/elpa/ on usage: - ;; ;; ("gnu" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/gnu/") + ;; ("gnu" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/gnu/") ;; ("melpa" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/melpa/") ;; ("melpa-stable" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/stable-melpa/") ;; }} @@ -195,9 +194,6 @@ You still need modify `package-archives' in \"init-elpa.el\" to PERMANENTLY use ;; Un-comment below line if you follow "Install stable version in easiest way" ;; (setq package-archives '(("myelpa" . "~/myelpa/"))) -;; my local repository is always needed. -(push (cons "localelpa" (concat my-emacs-d "localelpa/")) package-archives) - (defun my-package-generate-autoloads-hack (pkg-desc pkg-dir) "Stop package.el from leaving open autoload files lying around." (let* ((path (expand-file-name (concat @@ -520,3 +516,4 @@ If NO-REFRESH is nil, `package-refresh-contents' is called." (setq kill-buffer-query-functions (delq 'process-kill-buffer-query-function kill-buffer-query-functions)) (provide 'init-elpa) +;;; init-elpa.el ends here diff --git a/localelpa/archive-contents b/localelpa/archive-contents deleted file mode 100644 index 3e5706b12..000000000 --- a/localelpa/archive-contents +++ /dev/null @@ -1,12 +0,0 @@ -(1 - (csv-mode . [(1 10) nil "" single]) - (eldoc . [(1 15 0) nil "" tar]) - (spinner . [(1 7 3) nil "" single]) - (nadvice . [(0 3) nil "" single]) - (xr . [(1 14) nil "" single]) - (undo-tree . [(0 7 4) nil "Treat undo history as a tree" single]) - (let-alist . [(1 0 6) nil "Easily let-bind values of an assoc-list by their names" single]) - (gnu-elpa-keyring-update . [(2022 12) nil "Update Emacs's GPG keyring for GNU ELPA " tar]) - (compat . [(29 1 4 5) nil "" tar]) - (seq . [(2 24) nil "Sequence manipulation functions" tar]) -) diff --git a/localelpa/compat-29.1.4.5.tar b/localelpa/compat-29.1.4.5.tar deleted file mode 100644 index 5ddb4cbdd..000000000 Binary files a/localelpa/compat-29.1.4.5.tar and /dev/null differ diff --git a/localelpa/csv-mode-1.10.el b/localelpa/csv-mode-1.10.el deleted file mode 100644 index f837f6adf..000000000 --- a/localelpa/csv-mode-1.10.el +++ /dev/null @@ -1,1949 +0,0 @@ -;;; csv-mode.el --- Major mode for editing comma/char separated values -*- lexical-binding: t -*- - -;; Copyright (C) 2003, 2004, 2012-2019 Free Software Foundation, Inc - -;; Author: "Francis J. Wright" -;; Maintainer: emacs-devel@gnu.org -;; Version: 1.10 -;; Package-Requires: ((emacs "24.1") (cl-lib "0.5")) -;; Keywords: convenience - -;; This package is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation; either version 3, or (at your option) -;; any later version. - -;; This package is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with GNU Emacs. If not, see . - -;;; Commentary: - -;; This package implements CSV mode, a major mode for editing records -;; in a generalized CSV (character-separated values) format. It binds -;; files with prefix ".csv" to `csv-mode' (and ".tsv" to `tsv-mode') in -;; `auto-mode-alist'. - -;; In CSV mode, the following commands are available: - -;; - C-c C-s (`csv-sort-fields') and C-c C-n (`csv-sort-numeric-fields') -;; respectively sort lexicographically and numerically on a -;; specified field or column. - -;; - C-c C-r (`csv-reverse-region') reverses the order. (These -;; commands are based closely on, and use, code in `sort.el'.) - -;; - C-c C-k (`csv-kill-fields') and C-c C-y (`csv-yank-fields') kill -;; and yank fields or columns, although they do not use the normal -;; kill ring. C-c C-k can kill more than one field at once, but -;; multiple killed fields can be yanked only as a fixed group -;; equivalent to a single field. - -;; - `csv-align-mode' keeps fields visually aligned, on-the-fly. -;; It truncates fields to a maximum width that can be changed per-column -;; with `csv-align-set-column-width'. -;; Alternatively, C-c C-a (`csv-align-fields') aligns fields into columns -;; and C-c C-u (`csv-unalign-fields') undoes such alignment; -;; separators can be hidden within aligned records (controlled by -;; `csv-invisibility-default' and `csv-toggle-invisibility'). - -;; - C-c C-t (`csv-transpose') interchanges rows and columns. For -;; details, see the documentation for the individual commands. - -;; CSV mode can recognize fields separated by any of several single -;; characters, specified by the value of the customizable user option -;; `csv-separators'. CSV data fields can be delimited by quote -;; characters (and must if they contain separator characters). This -;; implementation supports quoted fields, where the quote characters -;; allowed are specified by the value of the customizable user option -;; `csv-field-quotes'. By default, the both commas and tabs are considered -;; as separators and the only field quote is a double quote. -;; These user options can be changed ONLY by customizing them, e.g. via M-x -;; customize-variable. - -;; CSV mode commands ignore blank lines and comment lines beginning -;; with the value of the buffer local variable `csv-comment-start', -;; which by default is #. The user interface is similar to that of -;; the standard commands `sort-fields' and `sort-numeric-fields', but -;; see the major mode documentation below. - -;; The global minor mode `csv-field-index-mode' provides display of -;; the current field index in the mode line, cf. `line-number-mode' -;; and `column-number-mode'. It is on by default. - -;;; Installation: - -;; Put this file somewhere that Emacs can find it (i.e. in one of the -;; directories in your `load-path' such as `site-lisp'), optionally -;; byte-compile it (recommended), and put this in your .emacs file: -;; -;; (add-to-list 'auto-mode-alist '("\\.[Cc][Ss][Vv]\\'" . csv-mode)) -;; (autoload 'csv-mode "csv-mode" -;; "Major mode for editing comma-separated value files." t) - -;;; History: - -;; Begun on 15 November 2003 to provide lexicographic sorting of -;; simple CSV data by field and released as csv.el. Facilities to -;; kill multiple fields and customize separator added on 9 April 2004. -;; Converted to a major mode and renamed csv-mode.el on 10 April 2004, -;; partly at the suggestion of Stefan Monnier to avoid conflict with csv.el by Ulf Jasper. -;; Field alignment, comment support and CSV mode customization group -;; added on 1 May 2004. Support for index ranges added on 6 June -;; 2004. Multiple field separators added on 12 June 2004. -;; Transposition added on 22 June 2004. Separator invisibility added -;; on 23 June 2004. - -;;; See also: - -;; the standard GNU Emacs 21 packages align.el, which will align -;; columns within a region, and delim-col.el, which helps to prettify -;; columns in a text region or rectangle; - -;; csv.el by Ulf Jasper , which provides -;; functions for reading/parsing comma-separated value files and is -;; available at http://de.geocities.com/ulf_jasper/emacs.html (and in -;; the gnu.emacs.sources archives). - -;;; To do (maybe): - -;; Make separators and quotes buffer-local and locally settable. -;; Support (La)TeX tables: set separator and comment; support record -;; end string. -;; Convert comma-separated to space- or tab-separated. - -;;; Code: - -(eval-when-compile (require 'cl-lib)) - -(defgroup CSV nil - "Major mode for editing files of comma-separated value type." - :group 'convenience) - -(defvar csv-separator-chars nil - "Field separators as a list of character. -Set by customizing `csv-separators' -- do not set directly!") - -(defvar csv-separator-regexp nil - "Regexp to match a field separator. -Set by customizing `csv-separators' -- do not set directly!") - -(defvar csv--skip-chars nil - "Char set used by `skip-chars-forward' etc. to skip fields. -Set by customizing `csv-separators' -- do not set directly!") - -(defvar csv-font-lock-keywords nil - "Font lock keywords to highlight the field separators in CSV mode. -Set by customizing `csv-separators' -- do not set directly!") - -(defcustom csv-separators '("," "\t") - "Field separators: a list of *single-character* strings. -For example: (\",\"), the default, or (\",\" \";\" \":\"). -Neighbouring fields may be separated by any one of these characters. -The first is used when inserting a field separator into the buffer. -All must be different from the field quote characters, `csv-field-quotes'." - ;; Suggested by Eckhard Neber - :type '(repeat string) - ;; FIXME: Character would be better, but in Emacs 21.3 does not display - ;; correctly in a customization buffer. - :set (lambda (variable value) - (mapc (lambda (x) - (if (/= (length x) 1) - (error "Non-single-char string %S" x)) - (if (and (boundp 'csv-field-quotes) - (member x csv-field-quotes)) - (error "%S is already a quote" x))) - value) - (custom-set-default variable value) - (setq csv-separator-chars (mapcar #'string-to-char value) - csv--skip-chars (apply #'concat "^\n" csv-separators) - csv-separator-regexp (apply #'concat `("[" ,@value "]")) - csv-font-lock-keywords - ;; NB: csv-separator-face variable evaluates to itself. - `((,csv-separator-regexp (0 'csv-separator-face)))))) - -(defcustom csv-field-quotes '("\"") - "Field quotes: a list of *single-character* strings. -For example: (\"\\\"\"), the default, or (\"\\\"\" \"\\='\" \"\\=`\"). -A field can be delimited by a pair of any of these characters. -All must be different from the field separators, `csv-separators'." - :type '(repeat string) - ;; Character would be better, but in Emacs 21 does not display - ;; correctly in a customization buffer. - :set (lambda (variable value) - (mapc (lambda (x) - (if (/= (length x) 1) - (error "Non-single-char string %S" x)) - (if (member x csv-separators) - (error "%S is already a separator" x))) - value) - (when (boundp 'csv-mode-syntax-table) - ;; FIRST remove old quote syntax: - (with-syntax-table text-mode-syntax-table - (mapc (lambda (x) - (modify-syntax-entry - (string-to-char x) - (string (char-syntax (string-to-char x))) - ;; symbol-value to avoid compiler warning: - (symbol-value 'csv-mode-syntax-table))) - csv-field-quotes)) - ;; THEN set new quote syntax: - (csv-set-quote-syntax value)) - ;; BEFORE setting new value of `csv-field-quotes': - (custom-set-default variable value))) - -(defun csv-set-quote-syntax (field-quotes) - "Set syntax for field quote characters FIELD-QUOTES to be \"string\". -FIELD-QUOTES should be a list of single-character strings." - (mapc (lambda (x) - (modify-syntax-entry - (string-to-char x) "\"" - ;; symbol-value to avoid compiler warning: - (symbol-value 'csv-mode-syntax-table))) - field-quotes)) - -(defvar csv-comment-start nil - "String that starts a comment line, or nil if no comment syntax. -Such comment lines are ignored by CSV mode commands. -This variable is buffer local\; its default value is that of -`csv-comment-start-default'. It is set by the function -`csv-set-comment-start' -- do not set it directly!") - -(make-variable-buffer-local 'csv-comment-start) - -(defcustom csv-comment-start-default "#" - "String that starts a comment line, or nil if no comment syntax. -Such comment lines are ignored by CSV mode commands. -Default value of buffer-local variable `csv-comment-start'. -Changing this variable does not affect any existing CSV mode buffer." - :type '(choice (const :tag "None" nil) string) - :set (lambda (variable value) - (custom-set-default variable value) - (setq-default csv-comment-start value))) - -(defcustom csv-align-style 'left - "Aligned field style: one of `left', `centre', `right' or `auto'. -Alignment style used by `csv-align-mode' and `csv-align-fields'. -Auto-alignment means left align text and right align numbers." - :type '(choice (const left) (const centre) - (const right) (const auto))) - -(defcustom csv-align-padding 1 - "Aligned field spacing: must be a positive integer. -Number of spaces used by `csv-align-mode' and `csv-align-fields' after separators." - :type 'integer) - -(defcustom csv-header-lines 0 - "Header lines to skip when setting region automatically." - :type 'integer) - -(defcustom csv-invisibility-default t - "If non-nil, make separators in aligned records invisible." - :type 'boolean) - -(defface csv-separator-face - '((t :inherit escape-glyph)) - "CSV mode face used to highlight separators.") - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Mode definition, key bindings and menu -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - - -(defconst csv-mode-line-format - '(csv-field-index-string ("" csv-field-index-string)) - "Mode line format string for CSV mode.") - -(defvar csv-mode-map - (let ((map (make-sparse-keymap))) - (define-key map [(control ?c) (control ?v)] 'csv-toggle-invisibility) - (define-key map [(control ?c) (control ?t)] 'csv-transpose) - (define-key map [(control ?c) (control ?c)] 'csv-set-comment-start) - (define-key map [(control ?c) (control ?u)] 'csv-unalign-fields) - (define-key map [(control ?c) (control ?a)] 'csv-align-fields) - (define-key map [(control ?c) (control ?z)] 'csv-yank-as-new-table) - (define-key map [(control ?c) (control ?y)] 'csv-yank-fields) - (define-key map [(control ?c) (control ?k)] 'csv-kill-fields) - (define-key map [(control ?c) (control ?d)] 'csv-toggle-descending) - (define-key map [(control ?c) (control ?r)] 'csv-reverse-region) - (define-key map [(control ?c) (control ?n)] 'csv-sort-numeric-fields) - (define-key map [(control ?c) (control ?s)] 'csv-sort-fields) - map)) - -;;;###autoload -(define-derived-mode csv-mode text-mode "CSV" - "Major mode for editing files of comma-separated value type. - -CSV mode is derived from `text-mode', and runs `text-mode-hook' before -running `csv-mode-hook'. It turns `auto-fill-mode' off by default. -CSV mode can be customized by user options in the CSV customization -group. The separators are specified by the value of `csv-separators'. - -CSV mode commands ignore blank lines and comment lines beginning with -the value of `csv-comment-start', which delimit \"paragraphs\". -\"Sexp\" is re-interpreted to mean \"field\", so that `forward-sexp' -\(\\[forward-sexp]), `kill-sexp' (\\[kill-sexp]), etc. all apply to fields. -Standard comment commands apply, such as `comment-dwim' (\\[comment-dwim]). - -If `font-lock-mode' is enabled then separators, quoted values and -comment lines are highlighted using respectively `csv-separator-face', -`font-lock-string-face' and `font-lock-comment-face'. - -The user interface (UI) for CSV mode commands is similar to that of -the standard commands `sort-fields' and `sort-numeric-fields', except -that if there is no prefix argument then the UI prompts for the field -index or indices. In `transient-mark-mode' only: if the region is not -set then the UI attempts to set it to include all consecutive CSV -records around point, and prompts for confirmation; if there is no -prefix argument then the UI prompts for it, offering as a default the -index of the field containing point if the region was not set -explicitly. The region set automatically is delimited by blank lines -and comment lines, and the number of header lines at the beginning of -the region given by the value of `csv-header-lines' are skipped. - -Sort order is controlled by `csv-descending'. - -CSV mode provides the following specific keyboard key bindings: - -\\{csv-mode-map}" - :group 'CSV - ;; We used to `turn-off-auto-fill' here instead, but that's not very - ;; effective since text-mode-hook is run afterwards anyway! - (setq-local normal-auto-fill-function nil) - ;; Set syntax for field quotes: - (csv-set-quote-syntax csv-field-quotes) - ;; Make sexp functions apply to fields: - (set (make-local-variable 'forward-sexp-function) #'csv-forward-field) - (csv-set-comment-start csv-comment-start) - ;; Font locking -- separator plus syntactic: - (setq font-lock-defaults '(csv-font-lock-keywords)) - (setq-local jit-lock-contextually nil) ;Each line should be independent. - (if csv-invisibility-default (add-to-invisibility-spec 'csv)) - ;; Mode line to support `csv-field-index-mode': - (set (make-local-variable 'mode-line-position) - (pcase mode-line-position - (`(,(or (pred consp) (pred stringp)) . ,_) - `(,@mode-line-position ,csv-mode-line-format)) - (_ `("" ,mode-line-position ,csv-mode-line-format)))) - (set (make-local-variable 'truncate-lines) t) - ;; Enable or disable `csv-field-index-mode' (could probably do this - ;; a bit more efficiently): - (csv-field-index-mode (symbol-value 'csv-field-index-mode))) - -(defun csv-set-comment-start (string) - "Set comment start for this CSV mode buffer to STRING. -It must be either a string or nil." - (interactive - (list (edit-and-eval-command - "Comment start (string or nil): " csv-comment-start))) - ;; Paragraph means a group of contiguous records: - (set (make-local-variable 'paragraph-separate) "[:space:]*$") ; White space. - (set (make-local-variable 'paragraph-start) "\n");Must include \n explicitly! - ;; Remove old comment-start/end if available - (with-syntax-table text-mode-syntax-table - (when comment-start - (modify-syntax-entry (string-to-char comment-start) - (string (char-syntax (string-to-char comment-start))) - csv-mode-syntax-table)) - (modify-syntax-entry ?\n - (string (char-syntax ?\n)) - csv-mode-syntax-table)) - (when string - (setq paragraph-separate (concat paragraph-separate "\\|" string) - paragraph-start (concat paragraph-start "\\|" string)) - (set (make-local-variable 'comment-start) string) - (modify-syntax-entry - (string-to-char string) "<" csv-mode-syntax-table) - (modify-syntax-entry ?\n ">" csv-mode-syntax-table)) - (setq csv-comment-start string)) - -;;;###autoload -(add-to-list 'auto-mode-alist '("\\.[Cc][Ss][Vv]\\'" . csv-mode)) - -(defvar csv-descending nil - "If non-nil, CSV mode sort functions sort in order of descending sort key. -Usually they sort in order of ascending sort key.") - -(defun csv-toggle-descending () - "Toggle `csv-descending'." - (interactive) - (setq csv-descending (not csv-descending)) - (message "Sort order is %sscending" (if csv-descending "de" "a"))) - -(defun csv-toggle-invisibility () - ;; FIXME: Make it into a proper minor mode? - "Toggle `buffer-invisibility-spec'." - (interactive) - (if (memq 'csv buffer-invisibility-spec) - (remove-from-invisibility-spec 'csv) - (add-to-invisibility-spec 'csv)) - (message "Separators in aligned records will be %svisible \ -\(after re-aligning if soft\)" - (if (memq 'csv buffer-invisibility-spec) "in" "")) - (redraw-frame (selected-frame))) - -(easy-menu-define - csv-menu - csv-mode-map - "CSV major mode menu keymap" - '("CSV" - ["Sort By Field Lexicographically" csv-sort-fields :active t - :help "Sort lines in region lexicographically by the specified field"] - ["Sort By Field Numerically" csv-sort-numeric-fields :active t - :help "Sort lines in region numerically by the specified field"] - ["Reverse Order of Lines" csv-reverse-region :active t - :help "Reverse the order of the lines in the region"] - ["Use Descending Sort Order" csv-toggle-descending :active t - :style toggle :selected csv-descending - :help "If selected, use descending order when sorting"] - "--" - ["Kill Fields (Columns)" csv-kill-fields :active t - :help "Kill specified fields of each line in the region"] - ["Yank Fields (Columns)" csv-yank-fields :active t - :help "Yank killed fields as specified field of each line in region"] - ["Yank As New Table" csv-yank-as-new-table :active t - :help "Yank killed fields as a new table at point"] - ["Align Fields into Columns" csv-align-fields :active t - :help "Align the start of every field of each line in the region"] - ["Unalign Columns into Fields" csv-unalign-fields :active t - :help "Undo soft alignment and optionally remove redundant white space"] - ["Transpose Rows and Columns" csv-transpose :active t - :help "Rewrite rows (which may have different lengths) as columns"] - "--" - ["Forward Field" forward-sexp :active t - :help "Move forward across one field; with ARG, do it that many times"] - ["Backward Field" backward-sexp :active t - :help "Move backward across one field; with ARG, do it that many times"] - ["Kill Field Forward" kill-sexp :active t - :help "Kill field following cursor; with ARG, do it that many times"] - ["Kill Field Backward" backward-kill-sexp :active t - :help "Kill field preceding cursor; with ARG, do it that many times"] - "--" - ("Alignment Style" - ["Left" (setq csv-align-style 'left) :active t - :style radio :selected (eq csv-align-style 'left) - :help "If selected, `csv-align' left aligns fields"] - ["Centre" (setq csv-align-style 'centre) :active t - :style radio :selected (eq csv-align-style 'centre) - :help "If selected, `csv-align' centres fields"] - ["Right" (setq csv-align-style 'right) :active t - :style radio :selected (eq csv-align-style 'right) - :help "If selected, `csv-align' right aligns fields"] - ["Auto" (setq csv-align-style 'auto) :active t - :style radio :selected (eq csv-align-style 'auto) - :help "\ -If selected, `csv-align' left aligns text and right aligns numbers"] - ) - ["Set header line" csv-header-line :active t] - ["Auto-(re)align fields" csv-align-mode - :style toggle :selected csv-align-mode] - ["Show Current Field Index" csv-field-index-mode :active t - :style toggle :selected csv-field-index-mode - :help "If selected, display current field index in mode line"] - ["Make Separators Invisible" csv-toggle-invisibility :active t - :style toggle :selected (memq 'csv buffer-invisibility-spec) - :visible (not (tsv--mode-p)) - :help "If selected, separators in aligned records are invisible"] - ["Set Buffer's Comment Start" csv-set-comment-start :active t - :help "Set comment start string for this buffer"] - ["Customize CSV Mode" (customize-group 'CSV) :active t - :help "Open a customization buffer to change CSV mode options"] - )) - -(require 'sort) - -(defsubst csv-not-looking-at-record () - "Return t if looking at blank or comment line, nil otherwise. -Assumes point is at beginning of line." - (looking-at paragraph-separate)) - -(defun csv-interactive-args (&optional type) - "Get arg or field(s) and region interactively, offering sensible defaults. -Signal an error if the buffer is read-only. -If TYPE is noarg then return a list (beg end). -Otherwise, return a list (arg beg end), where arg is: - the raw prefix argument by default\; - a single field index if TYPE is single\; - a list of field indices or index ranges if TYPE is multiple. -Field defaults to the current prefix arg\; if not set, prompt user. - -A field index list consists of positive or negative integers or ranges, -separated by any non-integer characters. A range has the form m-n, -where m and n are positive or negative integers, m < n, and n defaults -to the last field index if omitted. - -In transient mark mode, if the mark is not active then automatically -select and highlight CSV records around point, and query user. -The default field when read interactively is the current field." - ;; Must be run interactively to activate mark! - (let* ((arg current-prefix-arg) (default-field 1) - (region - (if (not (use-region-p)) - ;; Set region automatically: - (save-excursion - (if arg - (beginning-of-line) - (let ((lbp (line-beginning-position))) - (while (re-search-backward csv-separator-regexp lbp 1) - ;; Move as far as possible, i.e. to beginning of line. - (setq default-field (1+ default-field))))) - (if (csv-not-looking-at-record) - (error "Point must be within CSV records")) - (let ((startline (point))) - ;; Set mark at beginning of region: - (while (not (or (bobp) (csv-not-looking-at-record))) - (forward-line -1)) - (if (csv-not-looking-at-record) (forward-line 1)) - ;; Skip header lines: - (forward-line csv-header-lines) - (set-mark (point)) ; OK since in save-excursion - ;; Move point to end of region: - (goto-char startline) - (beginning-of-line) - (while (not (or (eobp) (csv-not-looking-at-record))) - (forward-line 1)) - ;; Show mark briefly if necessary: - (unless (and (pos-visible-in-window-p) - (pos-visible-in-window-p (mark))) - (exchange-point-and-mark) - (sit-for 1) - (exchange-point-and-mark)) - (or (y-or-n-p "Region OK? ") - (error "Action aborted by user")) - (message nil) ; clear y-or-n-p message - (list (region-beginning) (region-end)))) - ;; Use region set by user: - (list (region-beginning) (region-end))))) - (setq default-field (number-to-string default-field)) - (cond - ((eq type 'multiple) - (if arg - ;; Ensure that field is a list: - (or (consp arg) - (setq arg (list (prefix-numeric-value arg)))) - ;; Read field interactively, ignoring non-integers: - (setq arg - (mapcar - (lambda (x) - (if (string-match "-" x 1) ; not first character - ;; Return a range as a pair - the cdr may be nil: - (let ((m (substring x 0 (match-beginning 0))) - (n (substring x (match-end 0)))) - (cons (car (read-from-string m)) - (and (not (string= n "")) - (car (read-from-string n))))) - ;; Return a number as a number: - (car (read-from-string x)))) - (split-string - (read-string - "Fields (sequence of integers or ranges): " default-field) - "[^-+0-9]+"))))) - ((eq type 'single) - (if arg - (setq arg (prefix-numeric-value arg)) - (while (not (integerp arg)) - (setq arg (eval-minibuffer "Field (integer): " default-field)))))) - (if (eq type 'noarg) region (cons arg region)))) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Sorting by field -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -(defun csv-nextrecfun () - "Called by `csv-sort-fields-1' with point at end of previous record. -It moves point to the start of the next record. -It should move point to the end of the buffer if there are no more records." - (forward-line) - (while (and (not (eobp)) (csv-not-looking-at-record)) - (forward-line))) - -(defun csv-sort-fields-1 (field beg end startkeyfun endkeyfun) - "Modified version of `sort-fields-1' that skips blank or comment lines. - -FIELD is a single field index, and BEG and END specify the region to -sort. - -STARTKEYFUN moves from the start of the record to the start of the key. -It may return either a non-nil value to be used as the key, or -else the key is the substring between the values of point after -STARTKEYFUN and ENDKEYFUN are called. If STARTKEYFUN is nil, the key -starts at the beginning of the record. - -ENDKEYFUN moves from the start of the sort key to the end of the sort key. -ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the -same as ENDRECFUN." - (let ((tbl (syntax-table))) - (if (zerop field) (setq field 1)) - (unwind-protect - (save-excursion - (save-restriction - (narrow-to-region beg end) - (goto-char (point-min)) - (set-syntax-table sort-fields-syntax-table) - (sort-subr csv-descending - 'csv-nextrecfun 'end-of-line - startkeyfun endkeyfun))) - (set-syntax-table tbl)))) - -(defun csv-sort-fields (field beg end) - "Sort lines in region lexicographically by the ARGth field of each line. -If not set, the region defaults to the CSV records around point. -Fields are separated by `csv-separators' and null fields are allowed anywhere. -Field indices increase from 1 on the left or decrease from -1 on the right. -A prefix argument specifies a single field, otherwise prompt for field index. -Ignore blank and comment lines. The variable `sort-fold-case' -determines whether alphabetic case affects the sort order. -When called non-interactively, FIELD is a single field index\; -BEG and END specify the region to sort." - ;; (interactive "*P\nr") - (interactive (csv-interactive-args 'single)) - (barf-if-buffer-read-only) - (csv-sort-fields-1 field beg end - (lambda () (csv-sort-skip-fields field) nil) - (lambda () (skip-chars-forward csv--skip-chars)))) - -(defun csv-sort-numeric-fields (field beg end) - "Sort lines in region numerically by the ARGth field of each line. -If not set, the region defaults to the CSV records around point. -Fields are separated by `csv-separators'. -Null fields are allowed anywhere and sort as zeros. -Field indices increase from 1 on the left or decrease from -1 on the right. -A prefix argument specifies a single field, otherwise prompt for field index. -Specified non-null field must contain a number in each line of the region, -which may begin with \"0x\" or \"0\" for hexadecimal and octal values. -Otherwise, the number is interpreted according to sort-numeric-base. -Ignore blank and comment lines. -When called non-interactively, FIELD is a single field index\; -BEG and END specify the region to sort." - ;; (interactive "*P\nr") - (interactive (csv-interactive-args 'single)) - (barf-if-buffer-read-only) - (csv-sort-fields-1 field beg end - (lambda () - (csv-sort-skip-fields field) - (let* ((case-fold-search t) - (base - (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]") - (cond ((match-beginning 1) - (goto-char (match-end 1)) - 16) - ((match-beginning 2) - (goto-char (match-end 2)) - 8) - (t nil))))) - (string-to-number (buffer-substring (point) - (save-excursion - (forward-sexp 1) - (point))) - (or base sort-numeric-base)))) - nil)) - -(defun csv-reverse-region (beg end) - "Reverse the order of the lines in the region. -This is just a CSV-mode style interface to `reverse-region', which is -the function that should be used non-interactively. It takes two -point or marker arguments, BEG and END, delimiting the region." - ;; (interactive "*P\nr") - (interactive (csv-interactive-args 'noarg)) - (barf-if-buffer-read-only) - (reverse-region beg end)) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Moving by field -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -(defsubst csv-end-of-field () - "Skip forward over one field." - (skip-chars-forward " ") - (if (eq (char-syntax (following-char)) ?\") - (goto-char (scan-sexps (point) 1))) - (skip-chars-forward csv--skip-chars)) - -(defsubst csv-beginning-of-field () - "Skip backward over one field." - (skip-syntax-backward " ") - (if (eq (char-syntax (preceding-char)) ?\") - (goto-char (scan-sexps (point) -1))) - (skip-chars-backward csv--skip-chars)) - -(defun csv-forward-field (arg) - "Move forward across one field, cf. `forward-sexp'. -With ARG, do it that many times. Negative arg -N means -move backward across N fields." - (interactive "p") - (if (< arg 0) - (csv-backward-field (- arg)) - (while (>= (setq arg (1- arg)) 0) - (if (or (bolp) - (when (and (not (eobp)) (eolp)) (forward-char) t)) - (while (and (not (eobp)) (csv-not-looking-at-record)) - (forward-line 1))) - (if (memq (following-char) csv-separator-chars) (forward-char)) - (csv-end-of-field)))) - -(defun csv-backward-field (arg) - "Move backward across one field, cf. `backward-sexp'. -With ARG, do it that many times. Negative arg -N means -move forward across N fields." - (interactive "p") - (if (< arg 0) - (csv-forward-field (- arg)) - (while (>= (setq arg (1- arg)) 0) - (when (or (eolp) - (when (and (not (bobp)) (bolp)) (backward-char) t)) - (while (progn - (beginning-of-line) - (csv-not-looking-at-record)) - (backward-char)) - (end-of-line)) - (if (memq (preceding-char) csv-separator-chars) (backward-char)) - (csv-beginning-of-field)))) - -(defun csv-sort-skip-fields (n &optional yank) - "Position point at the beginning of field N on the current line. -Fields are separated by `csv-separators'\; null terminal field allowed. -Assumes point is initially at the beginning of the line. -YANK non-nil allows N to be greater than the number of fields, in -which case extend the record as necessary." - (if (> n 0) - ;; Skip across N - 1 fields. - (let ((i (1- n))) - (while (> i 0) - (csv-end-of-field) - (if (eolp) - (if yank - (if (> i 1) (insert (car csv-separators))) - (error "Line has too few fields: %s" - (buffer-substring - (save-excursion (beginning-of-line) (point)) - (save-excursion (end-of-line) (point))))) - (forward-char)) ; skip separator - (setq i (1- i)))) - (end-of-line) - ;; Skip back across -N - 1 fields. - (let ((i (1- (- n)))) - (while (> i 0) - (csv-beginning-of-field) - (if (bolp) - (error "Line has too few fields: %s" - (buffer-substring - (save-excursion (beginning-of-line) (point)) - (save-excursion (end-of-line) (point))))) - (backward-char) ; skip separator - (setq i (1- i))) - ;; Position at the front of the field - ;; even if moving backwards. - (csv-beginning-of-field)))) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Field index mode -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -;; Based partly on paren.el - -(defcustom csv-field-index-delay 0.125 - "Time in seconds to delay before updating field index display." - :type '(number :tag "seconds")) - -(defvar csv-field-index-idle-timer nil) - -(defvar csv-field-index-string nil) -(make-variable-buffer-local 'csv-field-index-string) - -(defvar csv-field-index-old nil) -(make-variable-buffer-local 'csv-field-index-old) - -(define-minor-mode csv-field-index-mode - "Toggle CSV-Field-Index mode. -With prefix ARG, turn CSV-Field-Index mode on if and only if ARG is positive. -Returns the new status of CSV-Field-Index mode (non-nil means on). -When CSV-Field-Index mode is enabled, the current field index appears in -the mode line after `csv-field-index-delay' seconds of Emacs idle time." - :global t - :init-value t ; for documentation, since default is t - ;; This macro generates a function that first sets the mode - ;; variable, then runs the following code, runs the mode hooks, - ;; displays a message if interactive, updates the mode line and - ;; finally returns the variable value. - - ;; First, always disable the mechanism (to avoid having two timers): - (when csv-field-index-idle-timer - (cancel-timer csv-field-index-idle-timer) - (setq csv-field-index-idle-timer nil)) - ;; Now, if the mode is on and any buffer is in CSV mode then - ;; re-initialize and enable the mechanism by setting up a new timer: - (if csv-field-index-mode - (if (memq t (mapcar (lambda (buffer) - (with-current-buffer buffer - (when (derived-mode-p 'csv-mode) - (setq csv-field-index-string nil - csv-field-index-old nil) - t))) - (buffer-list))) - (setq csv-field-index-idle-timer - (run-with-idle-timer csv-field-index-delay t - #'csv-field-index))) - ;; but if the mode is off then remove the display from the mode - ;; lines of all CSV buffers: - (mapc (lambda (buffer) - (with-current-buffer buffer - (when (derived-mode-p 'csv-mode) - (setq csv-field-index-string nil - csv-field-index-old nil) - (force-mode-line-update)))) - (buffer-list)))) - -(defun csv--field-index () - (save-excursion - (let ((lbp (line-beginning-position)) (field 1)) - (while (re-search-backward csv-separator-regexp lbp 'move) - ;; Move as far as possible, i.e. to beginning of line. - (setq field (1+ field))) - (unless (csv-not-looking-at-record) field)))) - -(defun csv-field-index () - "Construct `csv-field-index-string' to display in mode line. -Called by `csv-field-index-idle-timer'." - (if (derived-mode-p 'csv-mode) - (let ((field (csv--field-index))) - (when (not (eq field csv-field-index-old)) - (setq csv-field-index-old field - csv-field-index-string - (and field (format "F%d" field))) - (force-mode-line-update))))) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Killing and yanking fields -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -(defvar csv-killed-fields nil - "A list of the fields or sub-records last killed by `csv-kill-fields'.") - -(defun csv-kill-fields (fields beg end) - "Kill specified fields of each line in the region. -If not set, the region defaults to the CSV records around point. -Fields are separated by `csv-separators' and null fields are allowed anywhere. -Field indices increase from 1 on the left or decrease from -1 on the right. -The fields are stored for use by `csv-yank-fields'. Fields can be -specified in any order but are saved in increasing index order. -Ignore blank and comment lines. - -When called interactively, a prefix argument specifies a single field, -otherwise prompt for a field list, which may include ranges in the form -m-n, where m < n and n defaults to the last field index if omitted. - -When called non-interactively, FIELDS is a single field index or a -list of field indices, with ranges specified as (m.n) or (m), and BEG -and END specify the region to process." - ;; (interactive "*P\nr") - (interactive (csv-interactive-args 'multiple)) - (barf-if-buffer-read-only) - ;; Kill the field(s): - (setq csv-killed-fields nil) - (save-excursion - (save-restriction - (narrow-to-region beg end) - (goto-char (point-min)) - (if (or (cdr fields) (consp (car fields))) - (csv-kill-many-columns fields) - (csv-kill-one-column (car fields))))) - (setq csv-killed-fields (nreverse csv-killed-fields))) - -(defun csv-kill-one-field (field) - "Kill field with index FIELD in current line. -Return killed text. Assumes point is at beginning of line." - ;; Move to start of field to kill: - (csv-sort-skip-fields field) - ;; Kill to end of field (cf. `kill-region'): - (prog1 (delete-and-extract-region - (point) - (progn (csv-end-of-field) (point))) - (if (eolp) - (unless (bolp) (delete-char -1)) ; Delete trailing separator at eol - (delete-char 1)))) ; or following separator otherwise. - -(defun csv-kill-one-column (field) - "Kill field with index FIELD in all lines in (narrowed) buffer. -Save killed fields in `csv-killed-fields'. -Assumes point is at `point-min'. Called by `csv-kill-fields'. -Ignore blank and comment lines." - (while (not (eobp)) - (or (csv-not-looking-at-record) - (push (csv-kill-one-field field) csv-killed-fields)) - (forward-line))) - -(defun csv-kill-many-columns (fields) - "Kill several fields in all lines in (narrowed) buffer. -FIELDS is an unordered list of field indices. -Save killed fields in increasing index order in `csv-killed-fields'. -Assumes point is at `point-min'. Called by `csv-kill-fields'. -Ignore blank and comment lines." - (if (eolp) (error "First record is empty")) - ;; Convert non-positive to positive field numbers: - (let ((last 1) (f fields)) - (csv-end-of-field) - (while (not (eolp)) - (forward-char) ; skip separator - (csv-end-of-field) - (setq last (1+ last))) ; last = # fields in first record - (while f - (cond ((consp (car f)) - ;; Expand a field range: (m.n) -> m m+1 ... n-1 n. - ;; If n is nil then it defaults to the number of fields. - (let* ((range (car f)) (cdrf (cdr f)) - (m (car range)) (n (cdr range))) - (if (< m 0) (setq m (+ m last 1))) - (if n - (if (< n 0) (setq n (+ n last 1))) - (setq n last)) - (setq range (list n)) - (while (> n m) (push (setq n (1- n)) range)) - (setcar f (car range)) - (setcdr f (cdr range)) - (setcdr (setq f (last range)) cdrf))) - ((zerop (car f)) (setcar f 1)) - ((< (car f) 0) (setcar f (+ f last 1)))) - (setq f (cdr f)))) - (goto-char (point-min)) - ;; Kill from right to avoid miscounting: - (setq fields (sort fields '>)) - (while (not (eobp)) - (or (csv-not-looking-at-record) - (let ((fields fields) killed-fields field) - (while fields - (setq field (car fields) - fields (cdr fields)) - (beginning-of-line) - (push (csv-kill-one-field field) killed-fields)) - (push (mapconcat #'identity killed-fields (car csv-separators)) - csv-killed-fields))) - (forward-line))) - -(defun csv-yank-fields (field beg end) - "Yank fields as the ARGth field of each line in the region. -ARG may be arbitrarily large and records are extended as necessary. -If not set, the region defaults to the CSV records around point\; -if point is not in a CSV record then offer to yank as a new table. -The fields yanked are those last killed by `csv-kill-fields'. -Fields are separated by `csv-separators' and null fields are allowed anywhere. -Field indices increase from 1 on the left or decrease from -1 on the right. -A prefix argument specifies a single field, otherwise prompt for field index. -Ignore blank and comment lines. When called non-interactively, FIELD -is a single field index\; BEG and END specify the region to process." - ;; (interactive "*P\nr") - (interactive (condition-case err - (csv-interactive-args 'single) - (error (list nil nil err)))) - (barf-if-buffer-read-only) - (if (null beg) - (if (y-or-n-p (concat (error-message-string end) - ". Yank as a new table? ")) - (csv-yank-as-new-table) - (error (error-message-string end))) - (if (<= field 0) (setq field (1+ field))) - (save-excursion - (save-restriction - (narrow-to-region beg end) - (goto-char (point-min)) - (let ((fields csv-killed-fields)) - (while (not (eobp)) - (unless (csv-not-looking-at-record) - ;; Yank at start of specified field if possible, - ;; otherwise yank at end of record: - (if (zerop field) - (end-of-line) - (csv-sort-skip-fields field 'yank)) - (and (eolp) (insert (car csv-separators))) - (when fields - (insert (car fields)) - (setq fields (cdr fields))) - (or (eolp) (insert (car csv-separators)))) - (forward-line))))))) - -(defun csv-yank-as-new-table () - "Yank fields as a new table starting at point. -The fields yanked are those last killed by `csv-kill-fields'." - (interactive "*") - (let ((fields csv-killed-fields)) - (while fields - (insert (car fields) ?\n) - (setq fields (cdr fields))))) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Aligning fields -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -(defun csv--make-overlay (beg end &optional buffer front-advance rear-advance props) - (let ((o (make-overlay beg end buffer front-advance rear-advance))) - (overlay-put o 'csv t) - (while props - (overlay-put o (pop props) (pop props))) - o)) - -(defun csv--delete-overlay (o) - (and (overlay-get o 'csv) (delete-overlay o))) - -(defun csv--column-widths (beg end) - "Return a list of two lists (COLUMN-WIDTHS FIELD-WIDTHS). -COLUMN-WIDTHS is a list of elements (WIDTH START END) -indicating the widths of the columns after point (and the position of the -widest field that determined the overall width). -FIELD-WIDTHS contains the widths of each individual field after -point." - (let ((column-widths '()) - (field-widths '())) - (goto-char beg) - ;; Construct list of column widths: - (while (< (point) end) ; for each record... - (or (csv-not-looking-at-record) - (let ((w column-widths) - (col (current-column)) - (beg (point)) - field-width) - (while (not (eolp)) - (csv-end-of-field) - (setq field-width (- (current-column) col)) - (push field-width field-widths) - (if w - (if (> field-width (caar w)) - (setcar w (list field-width beg (point)))) - (setq w (list (list field-width beg (point))) - column-widths (nconc column-widths w))) - (or (eolp) (forward-char)) ; Skip separator. - (setq w (cdr w) col (current-column) beg (point))))) - (forward-line)) - (list column-widths (nreverse field-widths)))) - -(defun csv-align-fields (hard beg end) - "Align all the fields in the region to form columns. -The alignment style is specified by `csv-align-style'. The number of -spaces specified by `csv-align-padding' appears after each separator. -Use soft alignment done by displaying virtual white space after the -separators unless invoked with an argument, in which case insert real -space characters into the buffer after the separators. -Unalign first (see `csv-unalign-fields'). Ignore blank and comment lines. - -In hard-aligned records, separators become invisible whenever -`buffer-invisibility-spec' is non-nil. In soft-aligned records, make -separators invisible if and only if `buffer-invisibility-spec' is -non-nil when the records are aligned\; this can be changed only by -re-aligning. \(Unaligning always makes separators visible.) - -When called non-interactively, use hard alignment if HARD is non-nil\; -BEG and END specify the region to align. -If there is no selected region, default to the whole buffer." - (interactive (cons current-prefix-arg - (if (use-region-p) - (list (region-beginning) (region-end)) - (list (point-min) (point-max))))) - ;; FIXME: Use csv--jit-align when applicable! - (setq end (copy-marker end)) - (csv-unalign-fields hard beg end) ; If hard then barfs if buffer read only. - (save-excursion - (pcase-let ((`(,column-widths ,field-widths) (csv--column-widths beg end))) - (save-restriction - (narrow-to-region beg end) - (set-marker end nil) - - ;; Align fields: - (goto-char (point-min)) - (while (not (eobp)) ; for each record... - (unless (csv-not-looking-at-record) - (let ((w column-widths) - (column 0)) ;Desired position of left-side of this column. - (while (and w (not (eolp))) - (let* ((beg (point)) - (align-padding (if (bolp) 0 csv-align-padding)) - (left-padding 0) (right-padding 0) - (field-width (pop field-widths)) - (column-width (car (pop w))) - (x (- column-width field-width))) ; Required padding. - (csv-end-of-field) - (set-marker end (point)) ; End of current field. - ;; beg = beginning of current field - ;; end = (point) = end of current field - - ;; Compute required padding: - (cond - ((eq csv-align-style 'left) - ;; Left align -- pad on the right: - (setq left-padding align-padding - right-padding x)) - ((eq csv-align-style 'right) - ;; Right align -- pad on the left: - (setq left-padding (+ align-padding x))) - ((eq csv-align-style 'auto) - ;; Auto align -- left align text, right align numbers: - (if (string-match "\\`[-+.[:digit:]]+\\'" - (buffer-substring beg (point))) - ;; Right align -- pad on the left: - (setq left-padding (+ align-padding x)) - ;; Left align -- pad on the right: - (setq left-padding align-padding - right-padding x))) - ((eq csv-align-style 'centre) - ;; Centre -- pad on both left and right: - (let ((y (/ x 2))) ; truncated integer quotient - (setq left-padding (+ align-padding y) - right-padding (- x y))))) - - (cond - (hard ;; Hard alignment... - (when (> left-padding 0) ; Pad on the left. - ;; Insert spaces before field: - (if (= beg end) ; null field - (insert (make-string left-padding ?\ )) - (goto-char beg) ; beginning of current field - (insert (make-string left-padding ?\ )) - (goto-char end))) ; end of current field - (unless (eolp) - (if (> right-padding 0) ; pad on the right - ;; Insert spaces after field: - (insert (make-string right-padding ?\ ))) - ;; Make separator (potentially) invisible; - ;; in Emacs 21.3, neighbouring overlays - ;; conflict, so use the following only - ;; with hard alignment: - (csv--make-overlay (point) (1+ (point)) nil t nil - '(invisible csv evaporate t)) - (forward-char))) ; skip separator - - ;; Soft alignment... - ((or (memq 'csv buffer-invisibility-spec) - ;; For TSV, hidden or not doesn't make much difference, - ;; but the behavior is slightly better when we "hide" - ;; the TABs with a `display' property than if we add - ;; before/after-strings. - (tsv--mode-p)) - - ;; Hide separators... - ;; Merge right-padding from previous field - ;; with left-padding from this field: - (if (zerop column) - (when (> left-padding 0) - ;; Display spaces before first field - ;; by overlaying first character: - (csv--make-overlay - beg (1+ beg) nil nil nil - `(before-string ,(make-string left-padding ?\ )))) - ;; Display separator as spaces: - (with-silent-modifications - (put-text-property - (1- beg) beg - 'display `(space :align-to - ,(+ left-padding column))))) - (unless (eolp) (forward-char)) ; Skip separator. - (setq column (+ column column-width align-padding))) - - (t ;; Do not hide separators... - (let ((overlay (csv--make-overlay beg (point) nil nil t))) - (when (> left-padding 0) ; Pad on the left. - ;; Display spaces before field: - (overlay-put overlay 'before-string - (make-string left-padding ?\ ))) - (unless (eolp) - (if (> right-padding 0) ; Pad on the right. - ;; Display spaces after field: - (overlay-put - overlay - 'after-string (make-string right-padding ?\ ))) - (forward-char)))) ; Skip separator. - - ))))) - (forward-line))))) - (set-marker end nil)) - -(defun csv-unalign-fields (hard beg end) - "Undo soft alignment and optionally remove redundant white space. -Undo soft alignment introduced by `csv-align-fields'. If invoked with -an argument then also remove all spaces and tabs around separators. -Also make all invisible separators visible again. -Ignore blank and comment lines. When called non-interactively, remove -spaces and tabs if HARD non-nil\; BEG and END specify region to unalign. -If there is no selected region, default to the whole buffer." - (interactive (cons current-prefix-arg - (if (use-region-p) - (list (region-beginning) (region-end)) - (list (point-min) (point-max))))) - ;; Remove any soft alignment: - (mapc #'csv--delete-overlay (overlays-in beg end)) - (with-silent-modifications - (remove-list-of-text-properties beg end '(display invisible))) - (when hard - (barf-if-buffer-read-only) - ;; Remove any white-space padding around separators: - (save-excursion - (save-restriction - (narrow-to-region beg end) - (goto-char (point-min)) - (while (not (eobp)) - (or (csv-not-looking-at-record) - (while (not (eolp)) - ;; Delete horizontal white space forward: - ;; (delete-horizontal-space) - ;; This relies on left-to-right argument evaluation; - ;; see info node (elisp) Function Forms. - (delete-region (point) - (+ (point) (skip-chars-forward " \t"))) - (csv-end-of-field) - ;; Delete horizontal white space backward: - ;; (delete-horizontal-space t) - (delete-region (point) - (+ (point) (skip-chars-backward " \t"))) - (or (eolp) (forward-char)))) - (forward-line)))))) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;; Transposing rows and columns -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - -(defun csv-transpose (beg end) - "Rewrite rows (which may have different lengths) as columns. -Null fields are introduced as necessary within records but are -stripped from the ends of records. Preserve soft alignment. -This function is its own inverse. Ignore blank and comment lines. -When called non-interactively, BEG and END specify region to process." - ;; (interactive "*P\nr") - (interactive (csv-interactive-args 'noarg)) - (barf-if-buffer-read-only) - (save-excursion - (save-restriction - (narrow-to-region beg end) - (goto-char (point-min)) - ;; Delete rows and collect them as a reversed list of lists of - ;; fields, skipping comment and blank lines: - (let ((sep (car csv-separators)) - (align (overlays-in beg end)) - rows columns) - ;; Remove soft alignment if necessary: - (when align - (mapc #'csv--delete-overlay align) - (setq align t)) - (while (not (eobp)) - (if (csv-not-looking-at-record) - ;; Skip blank and comment lines: - (forward-line) - (let ((lep (line-end-position))) - (push - (split-string - (buffer-substring-no-properties (point) lep) - csv-separator-regexp) - rows) - (delete-region (point) lep) - (or (eobp) (delete-char 1))))) - ;; Rows must have monotonic decreasing lengths to be - ;; transposable, so ensure this by padding with null fields. - ;; rows is currently a reversed list of field lists, which - ;; must therefore have monotonic increasing lengths. - (let ((oldlen (length (car rows))) newlen - (r (cdr rows))) - (while r - (setq newlen (length (car r))) - (if (< newlen oldlen) - (nconc (car r) (make-list (- oldlen newlen) nil)) - (setq oldlen newlen)) - (setq r (cdr r)))) - ;; Collect columns as a reversed list of lists of fields: - (while rows - (let (column (r rows) row) - (while r - (setq row (car r)) - ;; Provided it would not be a trailing null field, push - ;; field onto column: - (if (or column (string< "" (car row))) - (push (car row) column)) - ;; Pop field off row: - (setcar r (cdr row)) - ;; If row is now empty then remove it: - (or (car r) (setq rows (cdr rows))) - (setq r (cdr r))) - (push column columns))) - ;; Insert columns into buffer as rows: - (setq columns (nreverse columns)) - (while columns - (insert (mapconcat #'identity (car columns) sep) ?\n) - (setq columns (cdr columns))) - ;; Re-do soft alignment if necessary: - (if align (csv-align-fields nil (point-min) (point-max))))))) - -(defvar-local csv--header-line nil) -(defvar-local csv--header-hscroll nil) -(defvar-local csv--header-string nil) - -(defun csv-header-line (&optional use-current-line) - "Set/unset the header line. -If the optional prefix arg USE-CURRENT-LINE is nil, use the first line -as the header line. -If there is already a header line, then unset the header line." - (interactive "P") - (if csv--header-line - (progn - (delete-overlay csv--header-line) - (setq csv--header-line nil) - (kill-local-variable 'header-line-format)) - (save-excursion - (unless use-current-line (goto-char (point-min))) - (setq csv--header-line (make-overlay (line-beginning-position) - (line-end-position) - nil nil t)) - (overlay-put csv--header-line 'modification-hooks - '(csv--header-flush))) - (csv--header-flush) - (setq header-line-format - '(:eval (csv--header-string))))) - -(defun csv--header-flush (&rest _) - ;; Force re-computation of the header-line. - (setq csv--header-hscroll nil)) - -(defun csv--header-string () - ;; FIXME: Won't work with multiple windows showing that same buffer. - (if (eql (window-hscroll) csv--header-hscroll) - csv--header-string - (setq csv--header-hscroll (window-hscroll)) - (setq csv--header-string - (csv--compute-header-string)))) - -(defun csv--compute-header-string () - (with-demoted-errors "csv--compute-header-string %S" - (save-excursion - (goto-char (overlay-start csv--header-line)) - ;; Re-set the line-end-position, just in case. - (move-overlay csv--header-line (point) (line-end-position)) - (jit-lock-fontify-now (point) (line-end-position)) - ;; Not sure why it is sometimes nil! - (move-to-column (or csv--header-hscroll 0)) - (let ((str (buffer-substring (point) (line-end-position))) - (i 0)) - (while (and i (< i (length str))) - (let ((prop (get-text-property i 'display str))) - (and (eq (car-safe prop) 'space) - (eq (car-safe (cdr prop)) :align-to) - (let* ((x (nth 2 prop)) - (nexti (next-single-property-change i 'display str)) - (newprop - `(space :align-to - ,(if (numberp x) - (- x (or csv--header-hscroll 0)) - `(- ,x csv--header-hscroll))))) - (put-text-property i (or nexti (length str)) - 'display newprop str) - (setq i nexti)))) - (setq i (next-single-property-change i 'display str))) - (concat (propertize " " 'display '((space :align-to 0))) str))))) - -;;; Auto-alignment - -(defcustom csv-align-max-width 40 - "Maximum width of a column in `csv-align-mode'. -This does not apply to the last column (for which the usual `truncate-lines' -setting works better)." - :type 'integer) - -(defvar-local csv--config-column-widths nil - "Settings per column, stored as a list indexed by the column.") - -(defun csv-align--set-column (column value) - (let ((len (length csv--config-column-widths))) - (if (< len column) - (setq csv--config-column-widths - (nconc csv--config-column-widths (make-list (- column len) nil)))) - (setf (nth (1- column) csv--config-column-widths) value))) - -(defun csv-align-set-column-width (column width) - "Set the max WIDTH to use for COLUMN." - (interactive - (let* ((field (or (csv--field-index) 1)) - (curwidth (nth (1- field) csv--config-column-widths))) - (list field - (cond - ((numberp current-prefix-arg) - current-prefix-arg) - (current-prefix-arg - (read-number (format "Column width (for field %d): " field) - curwidth)) - (t (if curwidth nil (csv--ellipsis-width))))))) - (when (eql width csv-align-max-width) - (setq width nil)) - (csv-align--set-column column width) - (jit-lock-refontify)) - -(defvar-local csv--jit-columns nil) - -(defun csv--jit-merge-columns (column-widths) - ;; FIXME: The incremental update (delayed by jit-lock-context-time) of column - ;; width is a bit jarring at times. It's OK while scrolling or when - ;; extending a column, but not right when enabling the csv-align-mode or - ;; when shortening the longest field (or deleting the line containing it), - ;; because in that case we have *several* cascaded updates, e.g.: - ;; - Remove the line with the longest field of column N. - ;; - Edit some line: this line is updated as if its field was the widest, - ;; hence its subsequent fields are too much to the left. - ;; - The rest is updated starting from the first few lines (according - ;; to jit-lock-chunk-size). - ;; - After the first few lines, come the next set of few lines, - ;; which may cause the previous few lines to need refresh again. - ;; - etc.. until arriving again at the edited line which is re-aligned - ;; again. - ;; - etc.. until the end of the windows, potentially causing yet more - ;; refreshes as we discover yet-wider fields for this column. - (let ((old-columns csv--jit-columns) - (changed nil)) - (while (and old-columns column-widths) - (when (or (> (caar column-widths) (caar old-columns)) - ;; Apparently modification-hooks aren't run when the - ;; whole text containing the overlay is deleted (e.g. - ;; the whole line), so detect this case here. - ;; It's a bit too late, but better than never. - (null (overlay-buffer (cdar old-columns)))) - (setq changed t) ;; Return non-nil if some existing column changed. - (pcase-let ((`(,width ,beg ,end) (car column-widths))) - (setf (caar old-columns) width) - (move-overlay (cdar old-columns) beg end))) - (setq old-columns (cdr old-columns)) - (setq column-widths (cdr column-widths))) - (when column-widths - ;; New columns appeared. - (setq csv--jit-columns - (nconc csv--jit-columns - (mapcar (lambda (x) - (pcase-let* - ((`(,width ,beg ,end) x) - (ol (make-overlay beg end))) - (overlay-put ol 'csv-width t) - (overlay-put ol 'evaporate t) - (overlay-put ol 'modification-hooks - (list #'csv--jit-width-change)) - (cons width ol))) - column-widths)))) - changed)) - -(defun csv--jit-width-change (ol after _beg _end &optional len) - (when (and after (> len 0)) - ;; (let ((x (rassq ol csv--jit-columns))) - ;; (when x (setf (car x) -1))) - (delete-overlay ol))) - -(defun csv--jit-unalign (beg end) - (remove-text-properties beg end - '(display nil csv--jit nil invisible nil - cursor-sensor-functions nil csv--revealed nil)) - (remove-overlays beg end 'csv--jit t)) - -(defun csv--jit-flush (beg end) - "Cause all the buffer (except for the BEG...END region) to be re-aligned." - (cl-assert (>= end beg)) - ;; The buffer shouldn't have changed since beg/end were computed, - ;; but just in case, let's make sure they're still sane. - (when (< beg (point-min)) - (setq beg (point-min) end (max end beg))) - (when (< (point-max) end) - (setq end (point-max) beg (min end beg))) - (let ((pos (point-min))) - (while (and (< pos beg) - (setq pos (text-property-any pos beg 'csv--jit t))) - (jit-lock-refontify - pos (setq pos (or (text-property-any pos beg 'csv--jit nil) beg)))) - (setq pos end) - (while (and (< pos (point-max)) - (setq pos (text-property-any pos (point-max) 'csv--jit t))) - (jit-lock-refontify - pos (setq pos (or (text-property-any pos (point-max) 'csv--jit nil) - (point-max)))))) - (csv--header-flush)) - -(defun csv--ellipsis-width () - (let ((ellipsis - (when standard-display-table - (display-table-slot standard-display-table - 'selective-display)))) - (if ellipsis (length ellipsis) 3))) - -(defun csv-align--cursor-truncated (window oldpos dir) - ;; FIXME: Neither the `entered' nor the `left' event are guaranteed - ;; to be sent, and for the `left' case, even when we do get called, - ;; it may be unclear where the revealed text was (it's somewhere around - ;; `oldpos', but that position can be stale). - ;; Worse, if we have several windows displaying the buffer, when one - ;; cursor leaves we may need to keep the text revealed because of - ;; another window's cursor. - (let* ((prop (if (eq dir 'entered) 'invisible 'csv--revealed)) - (pos (cond - ((eq dir 'entered) (window-point window)) - (t (max (point-min) - (min (point-max) - (or oldpos (window-point window))))))) - (start (cond - ((and (> pos (point-min)) - (eq (get-text-property (1- pos) prop) 'csv-truncate)) - (or (previous-single-property-change pos prop) (point-min))) - (t pos))) - (end (if (eq (get-text-property pos prop) 'csv-truncate) - (or (next-single-property-change pos prop) (point-max)) - pos))) - (unless (eql start end) - (with-silent-modifications - (put-text-property start end - (if (eq dir 'entered) 'csv--revealed 'invisible) - 'csv-truncate) - (remove-text-properties start end (list prop)))))) - -(defun csv--jit-align (beg end) - (save-excursion - ;; This is run with inhibit-modification-hooks set, so the overlays' - ;; modification-hook doesn't work :-( - (and csv--header-line - (<= beg (overlay-end csv--header-line)) - (>= end (overlay-start csv--header-line)) - (csv--header-flush)) - ;; First, round up to a whole number of lines. - (goto-char end) - (unless (bolp) (forward-line 1) (setq end (point))) - (goto-char beg) - (unless (bolp) (forward-line 1) (setq beg (point))) - (csv--jit-unalign beg end) - (put-text-property beg end 'csv--jit t) - - (pcase-let* ((`(,column-widths ,field-widths) (csv--column-widths beg end)) - (changed (csv--jit-merge-columns column-widths)) - (ellipsis-width (csv--ellipsis-width))) - (when changed - ;; Do it after the current redisplay is over. - (run-with-timer jit-lock-context-time nil #'csv--jit-flush beg end)) - - ;; Align fields: - (goto-char beg) - (while (< (point) end) - (unless (csv-not-looking-at-record) - (let ((w csv--jit-columns) - (widths-config csv--config-column-widths) - (column 0)) ;Desired position of left-side of this column. - (while (and w (not (eolp))) - (let* ((field-beg (point)) - (width-config (pop widths-config)) - (align-padding (if (bolp) 0 csv-align-padding)) - (left-padding 0) (right-padding 0) - (field-width (pop field-widths)) - (column-width - (min (car (pop w)) - (or width-config - ;; Don't apply csv-align-max-width - ;; to the last field! - (if w csv-align-max-width - most-positive-fixnum)))) - (x (- column-width field-width)) ; Required padding. - (truncate nil)) - (csv-end-of-field) - ;; beg = beginning of current field - ;; end = (point) = end of current field - (when (< x 0) - (setq truncate (max column - (+ column column-width - align-padding (- ellipsis-width)))) - (setq x 0)) - ;; Compute required padding: - (pcase csv-align-style - ('left - ;; Left align -- pad on the right: - (setq left-padding align-padding - right-padding x)) - ('right - ;; Right align -- pad on the left: - (setq left-padding (+ align-padding x))) - ('auto - ;; Auto align -- left align text, right align numbers: - (if (string-match "\\`[-+.[:digit:]]+\\'" - (buffer-substring field-beg (point))) - ;; Right align -- pad on the left: - (setq left-padding (+ align-padding x)) - ;; Left align -- pad on the right: - (setq left-padding align-padding - right-padding x))) - ('centre - ;; Centre -- pad on both left and right: - (let ((y (/ x 2))) ; truncated integer quotient - (setq left-padding (+ align-padding y) - right-padding (- x y))))) - - (cond - - ((or (memq 'csv buffer-invisibility-spec) - ;; For TSV, hidden or not doesn't make much difference, - ;; but the behavior is slightly better when we "hide" - ;; the TABs with a `display' property than if we add - ;; before/after-strings. - (tsv--mode-p)) - - ;; Hide separators... - ;; Merge right-padding from previous field - ;; with left-padding from this field: - (if (zerop column) - (when (> left-padding 0) - ;; Display spaces before first field - ;; by overlaying first character: - (csv--make-overlay - field-beg (1+ field-beg) nil nil nil - `(before-string ,(make-string left-padding ?\ ) - csv--jit t))) - ;; Display separator as spaces: - (with-silent-modifications - (put-text-property - (1- field-beg) field-beg - 'display `(space :align-to - ,(+ left-padding column)))))) - - (t ;; Do not hide separators... - (let ((overlay (csv--make-overlay field-beg (point) - nil nil t - '(csv--jit t)))) - (when (> left-padding 0) ; Pad on the left. - ;; Display spaces before field: - (overlay-put overlay 'before-string - (make-string left-padding ?\ ))) - (unless (eolp) - (if (> right-padding 0) ; Pad on the right. - ;; Display spaces after field: - (overlay-put - overlay - 'after-string (make-string right-padding ?\ ))))))) - (setq column (+ column column-width align-padding)) - ;; Do it after applying the property, so `move-to-column' can - ;; take it into account. - (when truncate - (let ((trunc-pos - (save-excursion - ;; ÂĄÂĄ BIG UGLY HACK !! - ;; `current-column' and `move-to-column' count - ;; text hidden with an ellipsis "as if" it were - ;; fully visible, which is completely wrong here, - ;; so circumvent this by temporarily pretending - ;; that `csv-truncate' is fully invisible (which - ;; isn't quite right either, but should work - ;; just well enough for us here). - (let ((buffer-invisibility-spec - buffer-invisibility-spec)) - (add-to-invisibility-spec 'csv-truncate) - (move-to-column truncate)) - (point)))) - (put-text-property trunc-pos (point) - 'invisible 'csv-truncate) - (when (> (- (point) trunc-pos) 1) - ;; Arrange to temporarily untruncate the string when - ;; cursor moves into it. - ;; FIXME: This only works if - ;; `global-disable-point-adjustment' is non-nil! - ;; Arguably this should be fixed by making - ;; point-adjustment code pay attention to - ;; cursor-sensor-functions! - (put-text-property - (1+ trunc-pos) (point) - 'cursor-sensor-functions - (list #'csv-align--cursor-truncated))))) - (unless (eolp) (forward-char)) ; Skip separator. - )))) - (forward-line))) - `(jit-lock-bounds ,beg . ,end))) - -(define-minor-mode csv-align-mode - "Align columns on the fly." - :global nil - (csv-unalign-fields nil (point-min) (point-max)) ;Just in case. - (cond - (csv-align-mode - (add-to-invisibility-spec '(csv-truncate . t)) - (kill-local-variable 'csv--jit-columns) - (cursor-sensor-mode 1) - (jit-lock-register #'csv--jit-align) - (jit-lock-refontify)) - (t - (remove-from-invisibility-spec '(csv-truncate . t)) - (jit-lock-unregister #'csv--jit-align) - (csv--jit-unalign (point-min) (point-max)))) - (csv--header-flush)) - -;;; TSV support - -;; Since "the" CSV format is really a bunch of different formats, it includes -;; TSV as a subcase, but this subcase is sufficiently interesting that it has -;; its own mime-type and mostly standard file extension, also it suffers -;; less from the usual quoting problems of CSV (because the only problematic -;; chars are LF and TAB, really, which are much less common inside fields than -;; commas, space, and semi-colons) so it's "better behaved". - -(defvar tsv-mode-syntax-table - ;; Inherit from `text-mode-syntax-table' rather than from - ;; `csv-mode-syntax-table' so as not to inherit the - ;; `csv-field-quotes' settings. - (let ((st (make-syntax-table text-mode-syntax-table))) - st)) - -(defvar tsv-mode-map - (let ((map (make-sparse-keymap))) - ;; In `tsv-mode', the `csv-invisibility-default/csv-toggle-invisibility' - ;; business doesn't make much sense. - (define-key map [remap csv-toggle-invisibility] #'undefined) - map)) - -;;;###autoload -(add-to-list 'auto-mode-alist '("\\.tsv\\'" . tsv-mode)) - -(defun tsv--mode-p () - (equal csv-separator-chars '(?\t))) - -;;;###autoload -(define-derived-mode tsv-mode csv-mode "TSV" - "Major mode for editing files of tab-separated value type." - :group 'CSV - ;; In TSV we know TAB is the only possible separator. - (setq-local csv-separators '("\t")) - ;; FIXME: Copy&pasted from the `:set'ter of csv-separators! - (setq-local csv-separator-chars '(?\t)) - (setq-local csv--skip-chars "^\n\t") - (setq-local csv-separator-regexp "\t") - (setq-local csv-font-lock-keywords - ;; NB: csv-separator-face variable evaluates to itself. - `((,csv-separator-regexp (0 'csv-separator-face)))) - - ;; According to wikipedia, TSV doesn't use quotes but uses backslash escapes - ;; of the form \n, \t, \r, and \\ instead. - (setq-local csv-field-quotes nil)) - -;;;; ChangeLog: - -;; 2019-10-22 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el (csv-align--cursor-truncated): Fix C-e -;; case -;; -;; 2019-10-22 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: Auto-shorten columns as well -;; -;; (csv--column-widths): Also return the position of the widest field in -;; each column. -;; (csv-align-fields, csv--jit-align): Update accordingly. -;; (csv--jit-width-change): New function. -;; (csv--jit-merge-columns): Use it on overlays placed on the widest field -;; of each column, to detect when they're shortened. -;; -;; 2019-10-19 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: More cvs-align-mode improvements -;; -;; Rename csv-align-fields-* to cvs-align-*. -;; (csv-transpose): Use split-string. -;; (csv-split-string): Delete function. -;; (csv--config-column-widths): New var. -;; (csv-align--set-column): New function. -;; (csv-align-set-column-width): New command. -;; (csv--jit-align): Use them to obey the per-column width settings. Delay -;; context refresh by jit-lock-context-time. Set cursor-sensor-functions to -;; untruncate fields on-the-fly. -;; (csv-align--cursor-truncated): New function. -;; (csv-align-mode): Activate cursor-sensor-mode. -;; -;; 2019-10-19 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: Fix incorrect truncation -;; -;; (csv--field-index): New function, extracted from csv-field-index. -;; (csv--jit-align): Don't apply csv-align-fields-max-width to the last -;; column. Fix move-to-column call. -;; -;; 2019-10-10 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: Fix header-line's alignment -;; -;; (csv-header-line): Change csv--header-line into an overlay. Add a -;; modification-hooks to auto-refresh the header-line. -;; (csv--header-flush, csv--header-string): New functions. -;; (csv--compute-header-string): Make sure jit-lock was applied. -;; csv--header-hscroll can be nil sometimes somehow! -;; (csv--jit-flush, csv-align-fields-mode): Flush header-line as well. -;; (csv--jit-align): Flush header-line when applicable. Fix typo. -;; -;; 2019-10-09 Filipp Gunbin -;; -;; packages/csv-mode/csv-mode.el: Fix csv-align-fields doc -;; -;; (csv-align-fields): docstring mentioned csv-align-fields instead of -;; csv-align-padding -;; -;; 2019-09-29 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: Remove Francis as maintainer -;; -;; (csv-unalign-fields): Also remove the `invisible` property since we use -;; it to truncate fields in csv--jit-align. -;; (csv-align-fields-max-width): Rename from csv-align-field-max-width to -;; match the "csv-align-fields" prefix. -;; (csv--ellipsis-width): New function. -;; (csv--jit-align): Use it to truncate more correctly. -;; -;; 2019-09-27 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el (csv-align-field-max-width): New var -;; -;; (csv--jit-unalign): Erase invisible property as well. -;; (csv--jit-align): Truncate field to fit within csv-align-field-max-width -;; when needed. -;; (csv-align-fields-mode): Add/remove `csv-truncate` to invisibility spec. -;; -;; 2019-09-27 Francis Wright -;; -;; * packages/csv-mode/csv-mode.el: Fix for customize-mode -;; -;; (csv-mode, tsv-mode): Specify :group explicitly for `customize-mode`s -;; benefit -;; -;; 2019-09-24 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: Add tsv-mode and csv-align-fields-mode -;; -;; Require cl-lib. Don't set buffer-invisibility-spec directly. -;; (csv--skip-chars): Rename from misleading csv--skip-regexp. -;; (csv-mode): Set normal-auto-fill-function to really disable -;; auto-fill-mode. -;; (csv--column-widths): Only operate over new args beg..end. -;; (csv-align-fields): No need to narrow before csv--column-widths any -;; more. -;; (csv-align-fields-mode): New minor mode. -;; (tsv-mode): New major mode. -;; -;; 2019-09-18 Simen HeggestĂžyl -;; -;; Speed up 'csv-align-fields' -;; -;; * packages/csv-mode/csv-mode.el: Bump version number and make the -;; dependency on Emacs 24.1 or higher explicit. -;; (csv--column-widths): Return the field widths as well. -;; (csv-align-fields): Speed up by using the field widths already computed -;; by 'csv--column-widths' (bug#37393). -;; -;; 2017-12-05 Stefan Monnier -;; -;; * csv-mode/csv-mode.el (csv-header-line): New command -;; -;; (csv-menu): Add an entry for it. -;; (csv--header-line, csv--header-hscroll, csv--header-string): New vars. -;; (csv--compute-header-string): New function. -;; -;; 2016-07-11 Paul Eggert -;; -;; Fix some quoting problems in doc strings -;; -;; Most of these are minor issues involving, e.g., quoting `like this' -;; instead of 'like this'. A few involve escaping ` and ' with a preceding -;; \= when the characters should not be turned into curved single quotes. -;; -;; 2016-04-21 Leo Liu -;; -;; Fix csv-mode to delete its own overlays only -;; -;; * csv-mode/csv-mode.el (csv--make-overlay, csv--delete-overlay): New -;; functions. -;; (csv-align-fields, csv-unalign-fields, csv-transpose): Use them. -;; -;; 2016-03-04 Francis Wright -;; -;; * csv-mode/csv-mode.el: Remove out-of-date "URL:" header. -;; -;; 2016-03-03 Stefan Monnier -;; -;; * csv-mode, landmark: Fix maintainer's email -;; -;; 2015-07-09 Leo Liu -;; -;; Fix column width calculation in cvs-mode.el -;; -;; * csv-mode/cvs-mode.el (csv--column-widths, csv-align-fields): Fix -;; column width calculation. -;; -;; 2015-05-24 Leo Liu -;; -;; * csv-mode/cvs-mode.el (csv-set-comment-start): Handle nil. -;; -;; See also http://debbugs.gnu.org/20564. -;; -;; 2015-04-15 Stefan Monnier -;; -;; (csv-mode): Set mode-line-position rather than mode-line-format. -;; -;; Fixes: debbugs:20343 -;; -;; * csv-mode/csv-mode.el (csv-mode-line-format): Only keep the CSV part of -;; the mode line. -;; -;; 2014-01-15 Stefan Monnier -;; -;; * csv-mode (csv-mode-line-help-echo): Remove. -;; -;; 2013-04-24 Stefan Monnier -;; -;; * csv-mode.el (csv-kill-one-field): Check for presence before deleting -;; trailing separator. Remove last arg and turn into a function. -;; (csv-kill-one-column, csv-kill-many-columns): Adjust callers. -;; -;; 2012-10-22 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el (csv-end-of-field): Don't skip TABs. -;; (csv--skip-regexp): Rename from csv-skip-regexp. -;; -;; 2012-10-10 Stefan Monnier -;; -;; * csv-mode.el: Bump version number. -;; -;; 2012-10-10 Stefan Monnier -;; -;; * csv-mode.el: Use lexical-binding. Remove redundant :group args. -;; (csv-separators): Add TAB to the default. -;; (csv-invisibility-default): Change default to t. -;; (csv-separator-face): Inherit from escape-glyph. Remove variable. -;; (csv-mode-line-format): Remove trailing "--". Move next to line-number. -;; (csv-interactive-args): Use use-region-p. -;; (csv--column-widths): New function, extracted from csv-align-fields. -;; (csv-align-fields): Use it. Use whole buffer by default. Use :align-to -;; and text-properties when possible. -;; (csv-unalign-fields): Also remove properties. -;; (csv-mode): Truncate lines. -;; -;; 2012-03-24 Chong Yidong -;; -;; Commentary fix for quarter-plane.el. -;; -;; 2012-03-24 Chong Yidong -;; -;; Commentary tweaks for csv-mode, ioccur, and nhexl-mode packages. -;; -;; 2012-03-24 Chong Yidong -;; -;; csv-mode.el: Improve commentary. -;; -;; 2012-03-12 Stefan Monnier -;; -;; * packages/csv-mode/csv-mode.el: Minor installation cleanups. Fix up -;; copyright notice. Set version. -;; (csv-separators, csv-field-quotes): Fix calls to `error'. -;; (csv-mode-line-help-echo, csv-mode-line-format): Replace -;; mode-line-format for default-mode-line-format. -;; (csv-mode-map): Declare and initialize. -;; (csv-mode): Add autoload cookie. -;; (csv-set-comment-start): Make sure vars are made buffer-local. -;; (csv-field-index-mode, csv-field-index): Use derived-mode-p. -;; (csv-align-fields): Improve insertion types of overlay's markers. -;; -;; 2012-03-12 Stefan Monnier -;; -;; Add csv-mode.el. -;; - - - -(provide 'csv-mode) - -;;; csv-mode.el ends here diff --git a/localelpa/eldoc-1.15.0.tar b/localelpa/eldoc-1.15.0.tar deleted file mode 100644 index 0d546dad6..000000000 Binary files a/localelpa/eldoc-1.15.0.tar and /dev/null differ diff --git a/localelpa/gnu-elpa-keyring-update-2022.12.tar b/localelpa/gnu-elpa-keyring-update-2022.12.tar deleted file mode 100644 index e28401feb..000000000 Binary files a/localelpa/gnu-elpa-keyring-update-2022.12.tar and /dev/null differ diff --git a/localelpa/let-alist-1.0.6.el b/localelpa/let-alist-1.0.6.el deleted file mode 100644 index 96b397f1d..000000000 --- a/localelpa/let-alist-1.0.6.el +++ /dev/null @@ -1,184 +0,0 @@ -;;; let-alist.el --- Easily let-bind values of an assoc-list by their names -*- lexical-binding: t; -*- - -;; Copyright (C) 2014-2019 Free Software Foundation, Inc. - -;; Author: Artur Malabarba -;; Package-Requires: ((emacs "24.1")) -;; Version: 1.0.6 -;; Keywords: extensions lisp -;; Prefix: let-alist -;; Separator: - - -;; This is an Elpa :core package. Don't use functionality that is not -;; compatible with Emacs 24.1. - -;; This file is part of GNU Emacs. - -;; GNU Emacs is free software: you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; GNU Emacs is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with GNU Emacs. If not, see . - -;;; Commentary: - -;; This package offers a single macro, `let-alist'. This macro takes a -;; first argument (whose value must be an alist) and a body. -;; -;; The macro expands to a let form containing body, where each dotted -;; symbol inside body is let-bound to their cdrs in the alist. Dotted -;; symbol is any symbol starting with a `.'. Only those present in -;; the body are let-bound and this search is done at compile time. -;; -;; For instance, the following code -;; -;; (let-alist alist -;; (if (and .title .body) -;; .body -;; .site -;; .site.contents)) -;; -;; essentially expands to -;; -;; (let ((.title (cdr (assq 'title alist))) -;; (.body (cdr (assq 'body alist))) -;; (.site (cdr (assq 'site alist))) -;; (.site.contents (cdr (assq 'contents (cdr (assq 'site alist)))))) -;; (if (and .title .body) -;; .body -;; .site -;; .site.contents)) -;; -;; If you nest `let-alist' invocations, the inner one can't access -;; the variables of the outer one. You can, however, access alists -;; inside the original alist by using dots inside the symbol, as -;; displayed in the example above by the `.site.contents'. -;; -;;; Code: - - -(defun let-alist--deep-dot-search (data) - "Return alist of symbols inside DATA that start with a `.'. -Perform a deep search and return an alist where each car is the -symbol, and each cdr is the same symbol without the `.'." - (cond - ((symbolp data) - (let ((name (symbol-name data))) - (when (string-match "\\`\\." name) - ;; Return the cons cell inside a list, so it can be appended - ;; with other results in the clause below. - (list (cons data (intern (replace-match "" nil nil name))))))) - ((vectorp data) - (apply #'nconc (mapcar #'let-alist--deep-dot-search data))) - ((not (consp data)) nil) - ((eq (car data) 'let-alist) - ;; For nested ‘let-alist’ forms, ignore symbols appearing in the - ;; inner body because they don’t refer to the alist currently - ;; being processed. See Bug#24641. - (let-alist--deep-dot-search (cadr data))) - (t (append (let-alist--deep-dot-search (car data)) - (let-alist--deep-dot-search (cdr data)))))) - -(defun let-alist--access-sexp (symbol variable) - "Return a sexp used to access SYMBOL inside VARIABLE." - (let* ((clean (let-alist--remove-dot symbol)) - (name (symbol-name clean))) - (if (string-match "\\`\\." name) - clean - (let-alist--list-to-sexp - (mapcar #'intern (nreverse (split-string name "\\."))) - variable)))) - -(defun let-alist--list-to-sexp (list var) - "Turn symbols LIST into recursive calls to `cdr' `assq' on VAR." - `(cdr (assq ',(car list) - ,(if (cdr list) (let-alist--list-to-sexp (cdr list) var) - var)))) - -(defun let-alist--remove-dot (symbol) - "Return SYMBOL, sans an initial dot." - (let ((name (symbol-name symbol))) - (if (string-match "\\`\\." name) - (intern (replace-match "" nil nil name)) - symbol))) - - -;;; The actual macro. -;;;###autoload -(defmacro let-alist (alist &rest body) - "Let-bind dotted symbols to their cdrs in ALIST and execute BODY. -Dotted symbol is any symbol starting with a `.'. Only those present -in BODY are let-bound and this search is done at compile time. - -For instance, the following code - - (let-alist alist - (if (and .title .body) - .body - .site - .site.contents)) - -essentially expands to - - (let ((.title (cdr (assq \\='title alist))) - (.body (cdr (assq \\='body alist))) - (.site (cdr (assq \\='site alist))) - (.site.contents (cdr (assq \\='contents (cdr (assq \\='site alist)))))) - (if (and .title .body) - .body - .site - .site.contents)) - -If you nest `let-alist' invocations, the inner one can't access -the variables of the outer one. You can, however, access alists -inside the original alist by using dots inside the symbol, as -displayed in the example above." - (declare (indent 1) (debug t)) - (let ((var (make-symbol "alist"))) - `(let ((,var ,alist)) - (let ,(mapcar (lambda (x) `(,(car x) ,(let-alist--access-sexp (car x) var))) - (delete-dups (let-alist--deep-dot-search body))) - ,@body)))) - -;;;; ChangeLog: - -;; 2015-12-01 Artur Malabarba -;; -;; packages/let-alist: Define it as a :core package -;; -;; 2015-06-11 Artur Malabarba -;; -;; * let-alist (let-alist--deep-dot-search): Fix cons -;; -;; 2015-03-07 Artur Malabarba -;; -;; let-alist: Update copyright -;; -;; 2014-12-22 Artur Malabarba -;; -;; packages/let-alist: Use `make-symbol' instead of `gensym'. -;; -;; 2014-12-20 Artur Malabarba -;; -;; packages/let-alist: Enable access to deeper alists -;; -;; 2014-12-14 Artur Malabarba -;; -;; let-alist.el: Add lexical binding. Version bump. -;; -;; 2014-12-11 Artur Malabarba -;; -;; let-alist: New package -;; - - -(provide 'let-alist) - -;;; let-alist.el ends here diff --git a/localelpa/nadvice-0.3.el b/localelpa/nadvice-0.3.el deleted file mode 100644 index 7c4ba046c..000000000 --- a/localelpa/nadvice-0.3.el +++ /dev/null @@ -1,124 +0,0 @@ -;;; nadvice.el --- Forward compatibility for Emacs-24.4's nadvice - -;; Copyright (C) 2018 Free Software Foundation, Inc. - -;; Author: Stefan Monnier -;; Version: 0.3 -;; Keywords: - -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see . - -;;; Commentary: - -;; This package tries to re-implement some of nadvice.el's functionality -;; on top of the old defadvice system, to help users of defadvice -;; move to the new advice system without dropping support for Emacs<24.4. -;; -;; Limitations; -;; - only supports `advice-add' and `advice-remove'; -;; - only handles the :before, :after, :override, and :around kinds of advice; -;; - requires a named rather than anonymous function; -;; - and does not support any additional properties like `name' or `depth'. -;; -;; It was tested on Emacs-22 and I can't see any obvious reason why it -;; wouldn't work on older Emacsen. - -;;; Code: - -(declare-function ad-remove-advice "advice") - -(unless (fboundp 'add-function) - ;; If `add-function' is defined, we're presumably running on - ;; an Emacs that comes with the real nadvice.el, so let's be careful - ;; to do nothing in that case! - - ;; Load `advice' manually, in case `advice-remove' is called first, - ;; since ad-remove-advice is not autoloaded. - (require 'advice) - -;;;###autoload -(defun advice-add (symbol where function &optional props) - (when props - (error "This version of nadvice.el does not support PROPS")) - (unless (symbolp function) - (error "This version of nadvice.el requires FUNCTION to be a symbol")) - (let ((body (cond - ((eq where :before) - `(progn (apply #',function (ad-get-args 0)) ad-do-it)) - ((eq where :after) - `(progn ad-do-it (apply #',function (ad-get-args 0)))) - ((eq where :override) - `(setq ad-return-value (apply #',function (ad-get-args 0)))) - ((eq where :around) - `(setq ad-return-value - (apply #',function - (lambda (&rest nadvice--rest-arg) - (ad-set-args 0 nadvice--rest-arg) - ad-do-it) - (ad-get-args 0)))) - (t (error "This version of nadvice.el does not handle %S" - where))))) - (ad-add-advice symbol - `(,function nil t (advice lambda () ,body)) - 'around - nil) - (ad-activate symbol))) - -;;;###autoload -(defun advice-remove (symbol function) - ;; Just return nil if there is no advice, rather than signaling an - ;; error. - (condition-case nil - (ad-remove-advice symbol 'around function) - (error nil)) - (condition-case nil - (ad-activate symbol) - (error nil))) - -) - -;;;; ChangeLog: - -;; 2018-09-15 Thomas Fitzsimmons -;; -;; packages/nadvice: Fix advice-remove behaviour -;; -;; * packages/nadvice/nadvice.el: Bump version to 0.3. -;; (advice-remove): Do not signal an error if the function already has no -;; advice. -;; -;; 2018-09-12 Stefan Monnier -;; -;; * nadvice.el: ad-remove-advice is not autoloaded -;; -;; 2018-09-12 Stefan Monnier -;; -;; * nadvice.el: Fix typo -;; -;; 2018-09-12 Stefan Monnier -;; -;; * nadvice/nadvice.el (advice-add): Add support for :override -;; -;; 2018-09-12 Stefan Monnier -;; -;; * nadvice.el: Fix copyright! -;; -;; 2018-09-12 Stefan Monnier -;; -;; * nadvice: New forward compatibility package -;; - - -(provide 'nadvice) -;;; nadvice.el ends here diff --git a/localelpa/seq-2.24.tar b/localelpa/seq-2.24.tar deleted file mode 100644 index a1412a594..000000000 Binary files a/localelpa/seq-2.24.tar and /dev/null differ diff --git a/localelpa/spinner-1.7.3.el b/localelpa/spinner-1.7.3.el deleted file mode 100644 index 90aec8f4a..000000000 --- a/localelpa/spinner-1.7.3.el +++ /dev/null @@ -1,406 +0,0 @@ -;;; spinner.el --- Add spinners and progress-bars to the mode-line for ongoing operations -*- lexical-binding: t; -*- - -;; Copyright (C) 2015 Free Software Foundation, Inc. - -;; Author: Artur Malabarba -;; Version: 1.7.3 -;; URL: https://github.com/Malabarba/spinner.el -;; Keywords: processes mode-line - -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see . - -;;; Commentary: -;; -;; 1 Usage -;; ═══════ -;; -;; First of all, don’t forget to add `(spinner "VERSION")' to your -;; package’s dependencies. -;; -;; -;; 1.1 Major-modes -;; ─────────────── -;; -;; 1. Just call `(spinner-start)' and a spinner will be added to the -;; mode-line. -;; 2. Call `(spinner-stop)' on the same buffer when you want to remove -;; it. -;; -;; The default spinner is a line drawing that rotates. You can pass an -;; argument to `spinner-start' to specify which spinner you want. All -;; possibilities are listed in the `spinner-types' variable, but here are -;; a few examples for you to try: -;; -;; ‱ `(spinner-start 'vertical-breathing 10)' -;; ‱ `(spinner-start 'minibox)' -;; ‱ `(spinner-start 'moon)' -;; ‱ `(spinner-start 'triangle)' -;; -;; You can also define your own as a vector of strings (see the examples -;; in `spinner-types'). -;; -;; -;; 1.2 Minor-modes -;; ─────────────── -;; -;; Minor-modes can create a spinner with `spinner-create' and then add it -;; to their mode-line lighter. They can then start the spinner by setting -;; a variable and calling `spinner-start-timer'. Finally, they can stop -;; the spinner (and the timer) by just setting the same variable to nil. -;; -;; Here’s an example for a minor-mode named `foo'. Assuming that -;; `foo--lighter' is used as the mode-line lighter, the following code -;; will add an *inactive* global spinner to the mode-line. -;; ┌──── -;; │ (defvar foo--spinner (spinner-create 'rotating-line)) -;; │ (defconst foo--lighter -;; │ '(" foo" (:eval (spinner-print foo--spinner)))) -;; └──── -;; -;; 1. To activate the spinner, just call `(spinner-start foo--spinner)'. -;; It will show up on the mode-line and start animating. -;; 2. To get rid of it, call `(spinner-stop foo--spinner)'. It will then -;; disappear again. -;; -;; Some minor-modes will need spinners to be buffer-local. To achieve -;; that, just make the `foo--spinner' variable buffer-local and use the -;; third argument of the `spinner-create' function. The snippet below is an -;; example. -;; -;; ┌──── -;; │ (defvar-local foo--spinner nil) -;; │ (defconst foo--lighter -;; │ '(" foo" (:eval (spinner-print foo--spinner)))) -;; │ (defun foo--start-spinner () -;; │ "Create and start a spinner on this buffer." -;; │ (unless foo--spinner -;; │ (setq foo--spinner (spinner-create 'moon t))) -;; │ (spinner-start foo--spinner)) -;; └──── -;; -;; 1. To activate the spinner, just call `(foo--start-spinner)'. -;; 2. To get rid of it, call `(spinner-stop foo--spinner)'. -;; -;; This will use the `moon' spinner, but you can use any of the names -;; defined in the `spinner-types' variable or even define your own. - - -;;; Code: -(eval-when-compile - (require 'cl)) - -(defconst spinner-types - '((3-line-clock . ["─" "┘" "┮" "└" "├" "┌" "┬" "┐"]) - (2-line-clock . ["┘" "└" "┌" "┐"]) - (flipping-line . ["_" "\\" "|" "/"]) - (rotating-line . ["-" "\\" "|" "/"]) - (progress-bar . ["[ ]" "[= ]" "[== ]" "[=== ]" "[====]" "[ ===]" "[ ==]" "[ =]"]) - (progress-bar-filled . ["| |" "|█ |" "|██ |" "|███ |" "|████|" "| ███|" "| ██|" "| █|"]) - (vertical-breathing . ["▁" "▂" "▃" "▄" "▅" "▆" "▇" "█" "▇" "▆" "▅" "▄" "▃" "▂" "▁" " "]) - (vertical-rising . ["▁" "▄" "█" "▀" "▔"]) - (horizontal-breathing . [" " "▏" "▎" "▍" "▌" "▋" "▊" "▉" "▉" "▊" "▋" "▌" "▍" "▎" "▏"]) - (horizontal-breathing-long - . [" " "▎ " "▌ " "▊ " "█ " "█▎" "█▌" "█▊" "██" "█▊" "█▌" "█▎" "█ " "▊ " "▋ " "▌ " "▍ " "▎ " "▏ "]) - (horizontal-moving . [" " "▌ " "█ " "▐▌" " █" " ▐"]) - (minibox . ["▖" "▘" "▝" "▗"]) - (triangle . ["◱" "◣" "â—€" "â—„"]) - (box-in-box . ["◰" "◳" "â—Č" "◱"]) - (box-in-circle . ["◮" "◷" "◶" "â—”"]) - (half-circle . ["◐" "◓" "◑" "◒"]) - (moon . ["🌑" "🌘" "🌖" "🌕" "🌔" "🌒"])) - "Predefined alist of spinners. -Each car is a symbol identifying the spinner, and each cdr is a -vector, the spinner itself.") - -(defun spinner-make-progress-bar (width &optional char) - "Return a vector of strings of the given WIDTH. -The vector is a valid spinner type and is similar to the -`progress-bar' spinner, except without the sorrounding brackets. -CHAR is the character to use for the moving bar (defaults to =)." - (let ((whole-string (concat (make-string (1- width) ?\s) - (make-string 4 (or char ?=)) - (make-string width ?\s)))) - (apply #'vector (mapcar (lambda (n) (substring whole-string n (+ n width))) - (number-sequence (+ width 3) 0 -1))))) - -(defvar spinner-current nil - "Spinner curently being displayed on the `mode-line-process'.") -(make-variable-buffer-local 'spinner-current) - -(defconst spinner--mode-line-construct - '(:eval (spinner-print spinner-current)) - "Construct used to display a spinner in `mode-line-process'.") -(put 'spinner--mode-line-construct 'risky-local-variable t) - -(defvar spinner-frames-per-second 10 - "Default speed at which spinners spin, in frames per second. -Each spinner can override this value.") - - -;;; The spinner object. -(defun spinner--type-to-frames (type) - "Return a vector of frames corresponding to TYPE. -The list of possible built-in spinner types is given by the -`spinner-types' variable, but you can also use your own (see -below). - -If TYPE is nil, the frames of this spinner are given by the first -element of `spinner-types'. -If TYPE is a symbol, it specifies an element of `spinner-types'. -If TYPE is `random', use a random element of `spinner-types'. -If TYPE is a list, it should be a list of symbols, and a random -one is chosen as the spinner type. -If TYPE is a vector, it should be a vector of strings and these -are used as the spinner's frames. This allows you to make your -own spinner animations." - (cond - ((vectorp type) type) - ((not type) (cdr (car spinner-types))) - ((eq type 'random) - (cdr (elt spinner-types - (random (length spinner-types))))) - ((listp type) - (cdr (assq (elt type (random (length type))) - spinner-types))) - ((symbolp type) (cdr (assq type spinner-types))) - (t (error "Unknown spinner type: %s" type)))) - -(defstruct (spinner - (:copier nil) - (:conc-name spinner--) - (:constructor make-spinner (&optional type buffer-local frames-per-second delay-before-start))) - (frames (spinner--type-to-frames type)) - (counter 0) - (fps (or frames-per-second spinner-frames-per-second)) - (timer (timer-create)) - (active-p nil) - (buffer (when buffer-local - (if (bufferp buffer-local) - buffer-local - (current-buffer)))) - (delay (or delay-before-start 0))) - -;;;###autoload -(defun spinner-create (&optional type buffer-local fps delay) - "Create a spinner of the given TYPE. -The possible TYPEs are described in `spinner--type-to-frames'. - -FPS, if given, is the number of desired frames per second. -Default is `spinner-frames-per-second'. - -If BUFFER-LOCAL is non-nil, the spinner will be automatically -deactivated if the buffer is killed. If BUFFER-LOCAL is a -buffer, use that instead of current buffer. - -When started, in order to function properly, the spinner runs a -timer which periodically calls `force-mode-line-update' in the -curent buffer. If BUFFER-LOCAL was set at creation time, then -`force-mode-line-update' is called in that buffer instead. When -the spinner is stopped, the timer is deactivated. - -DELAY, if given, is the number of seconds to wait after starting -the spinner before actually displaying it. It is safe to cancel -the spinner before this time, in which case it won't display at -all." - (make-spinner type buffer-local fps delay)) - -(defun spinner-print (spinner) - "Return a string of the current frame of SPINNER. -If SPINNER is nil, just return nil. -Designed to be used in the mode-line with: - (:eval (spinner-print some-spinner))" - (when (and spinner (spinner--active-p spinner)) - (let ((frame (spinner--counter spinner))) - (when (>= frame 0) - (elt (spinner--frames spinner) frame))))) - -(defun spinner--timer-function (spinner) - "Function called to update SPINNER. -If SPINNER is no longer active, or if its buffer has been killed, -stop the SPINNER's timer." - (let ((buffer (spinner--buffer spinner))) - (if (or (not (spinner--active-p spinner)) - (and buffer (not (buffer-live-p buffer)))) - (spinner-stop spinner) - ;; Increment - (callf (lambda (x) (if (< x 0) - (1+ x) - (% (1+ x) (length (spinner--frames spinner))))) - (spinner--counter spinner)) - ;; Update mode-line. - (if (buffer-live-p buffer) - (with-current-buffer buffer - (force-mode-line-update)) - (force-mode-line-update))))) - -(defun spinner--start-timer (spinner) - "Start a SPINNER's timer." - (let ((old-timer (spinner--timer spinner))) - (when (timerp old-timer) - (cancel-timer old-timer)) - - (setf (spinner--active-p spinner) t) - - (unless (ignore-errors (> (spinner--fps spinner) 0)) - (error "A spinner's FPS must be a positive number")) - (setf (spinner--counter spinner) (round (- (* (or (spinner--delay spinner) 0) - (spinner--fps spinner))))) - ;; Create timer. - (let* ((repeat (/ 1.0 (spinner--fps spinner))) - (time (timer-next-integral-multiple-of-time (current-time) repeat)) - ;; Create the timer as a lex variable so it can cancel itself. - (timer (spinner--timer spinner))) - (timer-set-time timer time repeat) - (timer-set-function timer #'spinner--timer-function (list spinner)) - (timer-activate timer) - ;; Return a stopping function. - (lambda () (spinner-stop spinner))))) - - -;;; The main functions -;;;###autoload -(defun spinner-start (&optional type-or-object fps delay) - "Start a mode-line spinner of given TYPE-OR-OBJECT. -If TYPE-OR-OBJECT is an object created with `make-spinner', -simply activate it. This method is designed for minor modes, so -they can use the spinner as part of their lighter by doing: - \\='(:eval (spinner-print THE-SPINNER)) -To stop this spinner, call `spinner-stop' on it. - -If TYPE-OR-OBJECT is anything else, a buffer-local spinner is -created with this type, and it is displayed in the -`mode-line-process' of the buffer it was created it. Both -TYPE-OR-OBJECT and FPS are passed to `make-spinner' (which see). -To stop this spinner, call `spinner-stop' in the same buffer. - -Either way, the return value is a function which can be called -anywhere to stop this spinner. You can also call `spinner-stop' -in the same buffer where the spinner was created. - -FPS, if given, is the number of desired frames per second. -Default is `spinner-frames-per-second'. - -DELAY, if given, is the number of seconds to wait until actually -displaying the spinner. It is safe to cancel the spinner before -this time, in which case it won't display at all." - (unless (spinner-p type-or-object) - ;; Choose type. - (if (spinner-p spinner-current) - (setf (spinner--frames spinner-current) (spinner--type-to-frames type-or-object)) - (setq spinner-current (make-spinner type-or-object (current-buffer) fps delay))) - (setq type-or-object spinner-current) - ;; Maybe add to mode-line. - (unless (memq 'spinner--mode-line-construct mode-line-process) - (setq mode-line-process - (list (or mode-line-process "") - 'spinner--mode-line-construct)))) - - ;; Create timer. - (when fps (setf (spinner--fps type-or-object) fps)) - (when delay (setf (spinner--delay type-or-object) delay)) - (spinner--start-timer type-or-object)) - -(defun spinner-start-print (spinner) - "Like `spinner-print', but also start SPINNER if it's not active." - (unless (spinner--active-p spinner) - (spinner-start spinner)) - (spinner-print spinner)) - -(defun spinner-stop (&optional spinner) - "Stop SPINNER, defaulting to the current buffer's spinner. -It is always safe to call this function, even if there is no -active spinner." - (let ((spinner (or spinner spinner-current))) - (when (spinner-p spinner) - (let ((timer (spinner--timer spinner))) - (when (timerp timer) - (cancel-timer timer))) - (setf (spinner--active-p spinner) nil) - (force-mode-line-update)))) - -;;;; ChangeLog: - -;; 2016-11-17 Artur Malabarba -;; -;; Merge commit '0637791f005f747532b4439439a81c3415961377' -;; -;; 2016-07-11 Paul Eggert -;; -;; Fix some quoting problems in doc strings -;; -;; Most of these are minor issues involving, e.g., quoting `like this' -;; instead of 'like this'. A few involve escaping ` and ' with a preceding -;; \= when the characters should not be turned into curved single quotes. -;; -;; 2016-04-01 Artur Malabarba -;; -;; Remove reference to thread-last -;; -;; 2016-02-08 Artur Malabarba -;; -;; Spinner version 1.7 -;; -;; Offer a spinner-make-progress-bar function. Make spinner-stop never -;; signal. Allow floating-point delays. -;; -;; 2016-02-07 Artur Malabarba -;; -;; Update the mode-line after spinner-stop -;; -;; 2015-08-11 Artur Malabarba -;; -;; Merge commit '8d8c459d7757cf5774f11be9147d7a54f5f9bbd7' -;; -;; 2015-05-02 Artur Malabarba -;; -;; * spinner: Rename constructor. -;; -;; 2015-04-30 Artur Malabarba -;; -;; * spinner/spinner.el: Rewrite spinners as structures -;; -;; 2015-04-09 Artur Malabarba -;; -;; spinner: Fix readme -;; -;; 2015-04-09 Artur Malabarba -;; -;; spinner: Fix leftover mode-line-format code -;; -;; 2015-04-09 Artur Malabarba -;; -;; Merge commit 'c44ef65515f50bd38304a6f50adebc984fb8e431' -;; -;; 2015-03-07 Artur Malabarba -;; -;; Merge commit '7eca7d023c95bc21c7838467b3a58d549afaf68d' -;; -;; 2015-03-07 Artur Malabarba -;; -;; Merge commit 'a7b4e52766977b58c6b9899305e962a2b5235bda' -;; -;; 2015-03-07 Artur Malabarba -;; -;; Add 'packages/spinner/' from commit -;; '9477ee899d62259d4b946f243cdcdd9cdeb1e910' -;; -;; git-subtree-dir: packages/spinner git-subtree-mainline: -;; 5736e852fd48a0f1ba1c328dd4d03e3fa008a406 git-subtree-split: -;; 9477ee899d62259d4b946f243cdcdd9cdeb1e910 -;; - - -(provide 'spinner) - -;;; spinner.el ends here diff --git a/localelpa/undo-tree-0.7.4.el b/localelpa/undo-tree-0.7.4.el deleted file mode 100644 index 9fa1fc608..000000000 --- a/localelpa/undo-tree-0.7.4.el +++ /dev/null @@ -1,4751 +0,0 @@ -;;; undo-tree.el --- Treat undo history as a tree -*- lexical-binding: t; -*- - -;; Copyright (C) 2009-2020 Free Software Foundation, Inc - -;; Author: Toby Cubitt -;; Maintainer: Toby Cubitt -;; Version: 0.7.4 -;; Keywords: convenience, files, undo, redo, history, tree -;; URL: http://www.dr-qubit.org/emacs.php -;; Repository: http://www.dr-qubit.org/git/undo-tree.git - -;; This file is part of Emacs. -;; -;; This file is free software: you can redistribute it and/or modify it under -;; the terms of the GNU General Public License as published by the Free -;; Software Foundation, either version 3 of the License, or (at your option) -;; any later version. -;; -;; This program is distributed in the hope that it will be useful, but WITHOUT -;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for -;; more details. -;; -;; You should have received a copy of the GNU General Public License along -;; with GNU Emacs. If not, see . - - -;;; Commentary: -;; -;; Emacs has a powerful undo system. Unlike the standard undo/redo system in -;; most software, it allows you to recover *any* past state of a buffer -;; (whereas the standard undo/redo system can lose past states as soon as you -;; redo). However, this power comes at a price: many people find Emacs' undo -;; system confusing and difficult to use, spawning a number of packages that -;; replace it with the less powerful but more intuitive undo/redo system. -;; -;; Both the loss of data with standard undo/redo, and the confusion of Emacs' -;; undo, stem from trying to treat undo history as a linear sequence of -;; changes. It's not. The `undo-tree-mode' provided by this package replaces -;; Emacs' undo system with a system that treats undo history as what it is: a -;; branching tree of changes. This simple idea allows the more intuitive -;; behaviour of the standard undo/redo system to be combined with the power of -;; never losing any history. An added side bonus is that undo history can in -;; some cases be stored more efficiently, allowing more changes to accumulate -;; before Emacs starts discarding history. -;; -;; The only downside to this more advanced yet simpler undo system is that it -;; was inspired by Vim. But, after all, most successful religions steal the -;; best ideas from their competitors! -;; -;; -;; Installation -;; ============ -;; -;; This package has only been tested with Emacs versions 24 and CVS. It should -;; work in Emacs versions 22 and 23 too, but will not work without -;; modifications in earlier versions of Emacs. -;; -;; To install `undo-tree-mode', make sure this file is saved in a directory in -;; your `load-path', and add the line: -;; -;; (require 'undo-tree) -;; -;; to your .emacs file. Byte-compiling undo-tree.el is recommended (e.g. using -;; "M-x byte-compile-file" from within emacs). -;; -;; If you want to replace the standard Emacs' undo system with the -;; `undo-tree-mode' system in all buffers, you can enable it globally by -;; adding: -;; -;; (global-undo-tree-mode) -;; -;; to your .emacs file. -;; -;; -;; Quick-Start -;; =========== -;; -;; If you're the kind of person who likes to jump in the car and drive, -;; without bothering to first figure out whether the button on the left dips -;; the headlights or operates the ejector seat (after all, you'll soon figure -;; it out when you push it), then here's the minimum you need to know: -;; -;; `undo-tree-mode' and `global-undo-tree-mode' -;; Enable undo-tree mode (either in the current buffer or globally). -;; -;; C-_ C-/ (`undo-tree-undo') -;; Undo changes. -;; -;; M-_ C-? (`undo-tree-redo') -;; Redo changes. -;; -;; `undo-tree-switch-branch' -;; Switch undo-tree branch. -;; (What does this mean? Better press the button and see!) -;; -;; C-x u (`undo-tree-visualize') -;; Visualize the undo tree. -;; (Better try pressing this button too!) -;; -;; C-x r u (`undo-tree-save-state-to-register') -;; Save current buffer state to register. -;; -;; C-x r U (`undo-tree-restore-state-from-register') -;; Restore buffer state from register. -;; -;; -;; -;; In the undo-tree visualizer: -;; -;; p C-p (`undo-tree-visualize-undo') -;; Undo changes. -;; -;; n C-n (`undo-tree-visualize-redo') -;; Redo changes. -;; -;; b C-b (`undo-tree-visualize-switch-branch-left') -;; Switch to previous undo-tree branch. -;; -;; f C-f (`undo-tree-visualize-switch-branch-right') -;; Switch to next undo-tree branch. -;; -;; C- M-{ (`undo-tree-visualize-undo-to-x') -;; Undo changes up to last branch point. -;; -;; C- M-} (`undo-tree-visualize-redo-to-x') -;; Redo changes down to next branch point. -;; -;; n C-n (`undo-tree-visualize-redo') -;; Redo changes. -;; -;; (`undo-tree-visualizer-mouse-set') -;; Set state to node at mouse click. -;; -;; t (`undo-tree-visualizer-toggle-timestamps') -;; Toggle display of time-stamps. -;; -;; d (`undo-tree-visualizer-toggle-diff') -;; Toggle diff display. -;; -;; s (`undo-tree-visualizer-selection-mode') -;; Toggle keyboard selection mode. -;; -;; q (`undo-tree-visualizer-quit') -;; Quit undo-tree-visualizer. -;; -;; C-q (`undo-tree-visualizer-abort') -;; Abort undo-tree-visualizer. -;; -;; , < -;; Scroll left. -;; -;; . > -;; Scroll right. -;; -;; M-v -;; Scroll up. -;; -;; C-v -;; Scroll down. -;; -;; -;; -;; In visualizer selection mode: -;; -;; p C-p (`undo-tree-visualizer-select-previous') -;; Select previous node. -;; -;; n C-n (`undo-tree-visualizer-select-next') -;; Select next node. -;; -;; b C-b (`undo-tree-visualizer-select-left') -;; Select left sibling node. -;; -;; f C-f (`undo-tree-visualizer-select-right') -;; Select right sibling node. -;; -;; M-v -;; Select node 10 above. -;; -;; C-v -;; Select node 10 below. -;; -;; (`undo-tree-visualizer-set') -;; Set state to selected node and exit selection mode. -;; -;; s (`undo-tree-visualizer-mode') -;; Exit selection mode. -;; -;; t (`undo-tree-visualizer-toggle-timestamps') -;; Toggle display of time-stamps. -;; -;; d (`undo-tree-visualizer-toggle-diff') -;; Toggle diff display. -;; -;; q (`undo-tree-visualizer-quit') -;; Quit undo-tree-visualizer. -;; -;; C-q (`undo-tree-visualizer-abort') -;; Abort undo-tree-visualizer. -;; -;; , < -;; Scroll left. -;; -;; . > -;; Scroll right. -;; -;; -;; -;; Persistent undo history: -;; -;; Note: Requires Emacs version 24.3 or higher. -;; -;; `undo-tree-auto-save-history' (variable) -;; automatically save and restore undo-tree history along with buffer -;; (disabled by default) -;; -;; `undo-tree-save-history' (command) -;; manually save undo history to file -;; -;; `undo-tree-load-history' (command) -;; manually load undo history from file -;; -;; -;; -;; Compressing undo history: -;; -;; Undo history files cannot grow beyond the maximum undo tree size, which -;; is limited by `undo-limit', `undo-strong-limit' and -;; `undo-outer-limit'. Nevertheless, undo history files can grow quite -;; large. If you want to automatically compress undo history, add the -;; following advice to your .emacs file (replacing ".gz" with the filename -;; extension of your favourite compression algorithm): -;; -;; (defadvice undo-tree-make-history-save-file-name -;; (after undo-tree activate) -;; (setq ad-return-value (concat ad-return-value ".gz"))) -;; -;; -;; -;; -;; Undo Systems -;; ============ -;; -;; To understand the different undo systems, it's easiest to consider an -;; example. Imagine you make a few edits in a buffer. As you edit, you -;; accumulate a history of changes, which we might visualize as a string of -;; past buffer states, growing downwards: -;; -;; o (initial buffer state) -;; | -;; | -;; o (first edit) -;; | -;; | -;; o (second edit) -;; | -;; | -;; x (current buffer state) -;; -;; -;; Now imagine that you undo the last two changes. We can visualize this as -;; rewinding the current state back two steps: -;; -;; o (initial buffer state) -;; | -;; | -;; x (current buffer state) -;; | -;; | -;; o -;; | -;; | -;; o -;; -;; -;; However, this isn't a good representation of what Emacs' undo system -;; does. Instead, it treats the undos as *new* changes to the buffer, and adds -;; them to the history: -;; -;; o (initial buffer state) -;; | -;; | -;; o (first edit) -;; | -;; | -;; o (second edit) -;; | -;; | -;; x (buffer state before undo) -;; | -;; | -;; o (first undo) -;; | -;; | -;; x (second undo) -;; -;; -;; Actually, since the buffer returns to a previous state after an undo, -;; perhaps a better way to visualize it is to imagine the string of changes -;; turning back on itself: -;; -;; (initial buffer state) o -;; | -;; | -;; (first edit) o x (second undo) -;; | | -;; | | -;; (second edit) o o (first undo) -;; | / -;; |/ -;; o (buffer state before undo) -;; -;; Treating undos as new changes might seem a strange thing to do. But the -;; advantage becomes clear as soon as we imagine what happens when you edit -;; the buffer again. Since you've undone a couple of changes, new edits will -;; branch off from the buffer state that you've rewound to. Conceptually, it -;; looks like this: -;; -;; o (initial buffer state) -;; | -;; | -;; o -;; |\ -;; | \ -;; o x (new edit) -;; | -;; | -;; o -;; -;; The standard undo/redo system only lets you go backwards and forwards -;; linearly. So as soon as you make that new edit, it discards the old -;; branch. Emacs' undo just keeps adding changes to the end of the string. So -;; the undo history in the two systems now looks like this: -;; -;; Undo/Redo: Emacs' undo -;; -;; o o -;; | | -;; | | -;; o o o -;; .\ | |\ -;; . \ | | \ -;; . x (new edit) o o | -;; (discarded . | / | -;; branch) . |/ | -;; . o | -;; | -;; | -;; x (new edit) -;; -;; Now, what if you change your mind about those undos, and decide you did -;; like those other changes you'd made after all? With the standard undo/redo -;; system, you're lost. There's no way to recover them, because that branch -;; was discarded when you made the new edit. -;; -;; However, in Emacs' undo system, those old buffer states are still there in -;; the undo history. You just have to rewind back through the new edit, and -;; back through the changes made by the undos, until you reach them. Of -;; course, since Emacs treats undos (even undos of undos!) as new changes, -;; you're really weaving backwards and forwards through the history, all the -;; time adding new changes to the end of the string as you go: -;; -;; o -;; | -;; | -;; o o o (undo new edit) -;; | |\ |\ -;; | | \ | \ -;; o o | | o (undo the undo) -;; | / | | | -;; |/ | | | -;; (trying to get o | | x (undo the undo) -;; to this state) | / -;; |/ -;; o -;; -;; So far, this is still reasonably intuitive to use. It doesn't behave so -;; differently to standard undo/redo, except that by going back far enough you -;; can access changes that would be lost in standard undo/redo. -;; -;; However, imagine that after undoing as just described, you decide you -;; actually want to rewind right back to the initial state. If you're lucky, -;; and haven't invoked any command since the last undo, you can just keep on -;; undoing until you get back to the start: -;; -;; (trying to get o x (got there!) -;; to this state) | | -;; | | -;; o o o o (keep undoing) -;; | |\ |\ | -;; | | \ | \ | -;; o o | | o o (keep undoing) -;; | / | | | / -;; |/ | | |/ -;; (already undid o | | o (got this far) -;; to this state) | / -;; |/ -;; o -;; -;; But if you're unlucky, and you happen to have moved the point (say) after -;; getting to the state labelled "got this far", then you've "broken the undo -;; chain". Hold on to something solid, because things are about to get -;; hairy. If you try to undo now, Emacs thinks you're trying to undo the -;; undos! So to get back to the initial state you now have to rewind through -;; *all* the changes, including the undos you just did: -;; -;; (trying to get o x (finally got there!) -;; to this state) | | -;; | | -;; o o o o o o -;; | |\ |\ |\ |\ | -;; | | \ | \ | \ | \ | -;; o o | | o o | | o o -;; | / | | | / | | | / -;; |/ | | |/ | | |/ -;; (already undid o | | o<. | | o -;; to this state) | / : | / -;; |/ : |/ -;; o : o -;; : -;; (got this far, but -;; broke the undo chain) -;; -;; Confused? -;; -;; In practice you can just hold down the undo key until you reach the buffer -;; state that you want. But whatever you do, don't move around in the buffer -;; to *check* that you've got back to where you want! Because you'll break the -;; undo chain, and then you'll have to traverse the entire string of undos -;; again, just to get back to the point at which you broke the -;; chain. Undo-in-region and commands such as `undo-only' help to make using -;; Emacs' undo a little easier, but nonetheless it remains confusing for many -;; people. -;; -;; -;; So what does `undo-tree-mode' do? Remember the diagram we drew to represent -;; the history we've been discussing (make a few edits, undo a couple of them, -;; and edit again)? The diagram that conceptually represented our undo -;; history, before we started discussing specific undo systems? It looked like -;; this: -;; -;; o (initial buffer state) -;; | -;; | -;; o -;; |\ -;; | \ -;; o x (current state) -;; | -;; | -;; o -;; -;; Well, that's *exactly* what the undo history looks like to -;; `undo-tree-mode'. It doesn't discard the old branch (as standard undo/redo -;; does), nor does it treat undos as new changes to be added to the end of a -;; linear string of buffer states (as Emacs' undo does). It just keeps track -;; of the tree of branching changes that make up the entire undo history. -;; -;; If you undo from this point, you'll rewind back up the tree to the previous -;; state: -;; -;; o -;; | -;; | -;; x (undo) -;; |\ -;; | \ -;; o o -;; | -;; | -;; o -;; -;; If you were to undo again, you'd rewind back to the initial state. If on -;; the other hand you redo the change, you'll end up back at the bottom of the -;; most recent branch: -;; -;; o (undo takes you here) -;; | -;; | -;; o (start here) -;; |\ -;; | \ -;; o x (redo takes you here) -;; | -;; | -;; o -;; -;; So far, this is just like the standard undo/redo system. But what if you -;; want to return to a buffer state located on a previous branch of the -;; history? Since `undo-tree-mode' keeps the entire history, you simply need -;; to tell it to switch to a different branch, and then redo the changes you -;; want: -;; -;; o -;; | -;; | -;; o (start here, but switch -;; |\ to the other branch) -;; | \ -;; (redo) o o -;; | -;; | -;; (redo) x -;; -;; Now you're on the other branch, if you undo and redo changes you'll stay on -;; that branch, moving up and down through the buffer states located on that -;; branch. Until you decide to switch branches again, of course. -;; -;; Real undo trees might have multiple branches and sub-branches: -;; -;; o -;; ____|______ -;; / \ -;; o o -;; ____|__ __| -;; / | \ / \ -;; o o o o x -;; | | -;; / \ / \ -;; o o o o -;; -;; Trying to imagine what Emacs' undo would do as you move about such a tree -;; will likely frazzle your brain circuits! But in `undo-tree-mode', you're -;; just moving around this undo history tree. Most of the time, you'll -;; probably only need to stay on the most recent branch, in which case it -;; behaves like standard undo/redo, and is just as simple to understand. But -;; if you ever need to recover a buffer state on a different branch, the -;; possibility of switching between branches and accessing the full undo -;; history is still there. -;; -;; -;; -;; The Undo-Tree Visualizer -;; ======================== -;; -;; Actually, it gets better. You don't have to imagine all these tree -;; diagrams, because `undo-tree-mode' includes an undo-tree visualizer which -;; draws them for you! In fact, it draws even better diagrams: it highlights -;; the node representing the current buffer state, it highlights the current -;; branch, and you can toggle the display of time-stamps (by hitting "t") and -;; a diff of the undo changes (by hitting "d"). (There's one other tiny -;; difference: the visualizer puts the most recent branch on the left rather -;; than the right.) -;; -;; Bring up the undo tree visualizer whenever you want by hitting "C-x u". -;; -;; In the visualizer, the usual keys for moving up and down a buffer instead -;; move up and down the undo history tree (e.g. the up and down arrow keys, or -;; "C-n" and "C-p"). The state of the "parent" buffer (the buffer whose undo -;; history you are visualizing) is updated as you move around the undo tree in -;; the visualizer. If you reach a branch point in the visualizer, the usual -;; keys for moving forward and backward in a buffer instead switch branch -;; (e.g. the left and right arrow keys, or "C-f" and "C-b"). -;; -;; Clicking with the mouse on any node in the visualizer will take you -;; directly to that node, resetting the state of the parent buffer to the -;; state represented by that node. -;; -;; You can also select nodes directly using the keyboard, by hitting "s" to -;; toggle selection mode. The usual motion keys now allow you to move around -;; the tree without changing the parent buffer. Hitting will reset the -;; state of the parent buffer to the state represented by the currently -;; selected node. -;; -;; It can be useful to see how long ago the parent buffer was in the state -;; represented by a particular node in the visualizer. Hitting "t" in the -;; visualizer toggles the display of time-stamps for all the nodes. (Note -;; that, because of the way `undo-tree-mode' works, these time-stamps may be -;; somewhat later than the true times, especially if it's been a long time -;; since you last undid any changes.) -;; -;; To get some idea of what changes are represented by a given node in the -;; tree, it can be useful to see a diff of the changes. Hit "d" in the -;; visualizer to toggle a diff display. This normally displays a diff between -;; the current state and the previous one, i.e. it shows you the changes that -;; will be applied if you undo (move up the tree). However, the diff display -;; really comes into its own in the visualizer's selection mode (see above), -;; where it instead shows a diff between the current state and the currently -;; selected state, i.e. it shows you the changes that will be applied if you -;; reset to the selected state. -;; -;; (Note that the diff is generated by the Emacs `diff' command, and is -;; displayed using `diff-mode'. See the corresponding customization groups if -;; you want to customize the diff display.) -;; -;; Finally, hitting "q" will quit the visualizer, leaving the parent buffer in -;; whatever state you ended at. Hitting "C-q" will abort the visualizer, -;; returning the parent buffer to whatever state it was originally in when the -;; visualizer was invoked. -;; -;; -;; -;; Undo-in-Region -;; ============== -;; -;; Emacs allows a very useful and powerful method of undoing only selected -;; changes: when a region is active, only changes that affect the text within -;; that region will be undone. With the standard Emacs undo system, changes -;; produced by undoing-in-region naturally get added onto the end of the -;; linear undo history: -;; -;; o -;; | -;; | x (second undo-in-region) -;; o | -;; | | -;; | o (first undo-in-region) -;; o | -;; | / -;; |/ -;; o -;; -;; You can of course redo these undos-in-region as usual, by undoing the -;; undos: -;; -;; o -;; | -;; | o_ -;; o | \ -;; | | | -;; | o o (undo the undo-in-region) -;; o | | -;; | / | -;; |/ | -;; o x (undo the undo-in-region) -;; -;; -;; In `undo-tree-mode', undo-in-region works much the same way: when there's -;; an active region, undoing only undoes changes that affect that region. In -;; `undo-tree-mode', redoing when there's an active region similarly only -;; redoes changes that affect that region. -;; -;; However, the way these undo- and redo-in-region changes are recorded in the -;; undo history is quite different. The good news is, you don't need to -;; understand this to use undo- and redo-in-region in `undo-tree-mode' - just -;; go ahead and use them! They'll probably work as you expect. But if you're -;; masochistic enough to want to understand conceptually what's happening to -;; the undo tree as you undo- and redo-in-region, then read on... -;; -;; -;; Undo-in-region creates a new branch in the undo history. The new branch -;; consists of an undo step that undoes some of the changes that affect the -;; current region, and another step that undoes the remaining changes needed -;; to rejoin the previous undo history. -;; -;; Previous undo history Undo-in-region -;; -;; o o -;; | | -;; | | -;; | | -;; o o -;; | | -;; | | -;; | | -;; o o_ -;; | | \ -;; | | x (undo-in-region) -;; | | | -;; x o o -;; -;; As long as you don't change the active region after undoing-in-region, -;; continuing to undo-in-region extends the new branch, pulling more changes -;; that affect the current region into an undo step immediately above your -;; current location in the undo tree, and pushing the point at which the new -;; branch is attached further up the tree: -;; -;; First undo-in-region Second undo-in-region -;; -;; o o -;; | | -;; | | -;; | | -;; o o_ -;; | | \ -;; | | x (undo-in-region) -;; | | | -;; o_ o | -;; | \ | | -;; | x | o -;; | | | | -;; o o o o -;; -;; Redoing takes you back down the undo tree, as usual (as long as you haven't -;; changed the active region after undoing-in-region, it doesn't matter if it -;; is still active): -;; -;; o -;; | -;; | -;; | -;; o_ -;; | \ -;; | o -;; | | -;; o | -;; | | -;; | o (redo) -;; | | -;; o x (redo) -;; -;; -;; What about redo-in-region? Obviously, redo-in-region only makes sense if -;; you have already undone some changes, so that there are some changes to -;; redo! Redoing-in-region splits off a new branch of the undo history below -;; your current location in the undo tree. This time, the new branch consists -;; of a first redo step that redoes some of the redo changes that affect the -;; current region, followed by *all* the remaining redo changes. -;; -;; Previous undo history Redo-in-region -;; -;; o o -;; | | -;; | | -;; | | -;; x o_ -;; | | \ -;; | | x (redo-in-region) -;; | | | -;; o o | -;; | | | -;; | | | -;; | | | -;; o o o -;; -;; As long as you don't change the active region after redoing-in-region, -;; continuing to redo-in-region extends the new branch, pulling more redo -;; changes into a redo step immediately below your current location in the -;; undo tree. -;; -;; First redo-in-region Second redo-in-region -;; -;; o o -;; | | -;; | | -;; | | -;; o_ o_ -;; | \ | \ -;; | x | o -;; | | | | -;; o | o | -;; | | | | -;; | | | x (redo-in-region) -;; | | | | -;; o o o o -;; -;; Note that undo-in-region and redo-in-region only ever add new changes to -;; the undo tree, they *never* modify existing undo history. So you can always -;; return to previous buffer states by switching to a previous branch of the -;; tree. - - - -;;; Code: - -(require 'cl-lib) -(require 'diff) -(require 'gv) - - - -;;; ===================================================================== -;;; Compatibility hacks for older Emacsen - -;; `characterp' isn't defined in Emacs versions < 23 -(unless (fboundp 'characterp) - (defalias 'characterp 'char-valid-p)) - -;; `region-active-p' isn't defined in Emacs versions < 23 -(unless (fboundp 'region-active-p) - (defun region-active-p () (and transient-mark-mode mark-active))) - - -;; `registerv' defstruct isn't defined in Emacs versions < 24 -(unless (fboundp 'registerv-make) - (defmacro registerv-make (data &rest _dummy) data)) - -(unless (fboundp 'registerv-data) - (defmacro registerv-data (data) data)) - - -;; `diff-no-select' and `diff-file-local-copy' aren't defined in Emacs -;; versions < 24 (copied and adapted from Emacs 24) -(unless (fboundp 'diff-no-select) - (defun diff-no-select (old new &optional switches no-async buf) - ;; Noninteractive helper for creating and reverting diff buffers - (unless (bufferp new) (setq new (expand-file-name new))) - (unless (bufferp old) (setq old (expand-file-name old))) - (or switches (setq switches diff-switches)) ; If not specified, use default. - (unless (listp switches) (setq switches (list switches))) - (or buf (setq buf (get-buffer-create "*Diff*"))) - (let* ((old-alt (diff-file-local-copy old)) - (new-alt (diff-file-local-copy new)) - (command - (mapconcat 'identity - `(,diff-command - ;; Use explicitly specified switches - ,@switches - ,@(mapcar #'shell-quote-argument - (nconc - (when (or old-alt new-alt) - (list "-L" (if (stringp old) - old (prin1-to-string old)) - "-L" (if (stringp new) - new (prin1-to-string new)))) - (list (or old-alt old) - (or new-alt new))))) - " ")) - (thisdir default-directory)) - (with-current-buffer buf - (setq buffer-read-only t) - (buffer-disable-undo (current-buffer)) - (let ((inhibit-read-only t)) - (erase-buffer)) - (buffer-enable-undo (current-buffer)) - (diff-mode) - (set (make-local-variable 'revert-buffer-function) - (lambda (_ignore-auto _noconfirm) - (diff-no-select old new switches no-async (current-buffer)))) - (setq default-directory thisdir) - (let ((inhibit-read-only t)) - (insert command "\n")) - (if (and (not no-async) (fboundp 'start-process)) - (let ((proc (start-process "Diff" buf shell-file-name - shell-command-switch command))) - (set-process-filter proc 'diff-process-filter) - (set-process-sentinel - proc (lambda (proc _msg) - (with-current-buffer (process-buffer proc) - (diff-sentinel (process-exit-status proc)) - (if old-alt (delete-file old-alt)) - (if new-alt (delete-file new-alt)))))) - ;; Async processes aren't available. - (let ((inhibit-read-only t)) - (diff-sentinel - (call-process shell-file-name nil buf nil - shell-command-switch command)) - (if old-alt (delete-file old-alt)) - (if new-alt (delete-file new-alt))))) - buf))) - -(unless (fboundp 'diff-file-local-copy) - (defun diff-file-local-copy (file-or-buf) - (if (bufferp file-or-buf) - (with-current-buffer file-or-buf - (let ((tempfile (make-temp-file "buffer-content-"))) - (write-region nil nil tempfile nil 'nomessage) - tempfile)) - (file-local-copy file-or-buf)))) - - -;; `user-error' isn't defined in Emacs < 24.3 -(unless (fboundp 'user-error) - (defalias 'user-error 'error) - ;; prevent debugger being called on user errors - (add-to-list 'debug-ignored-errors "^No further undo information") - (add-to-list 'debug-ignored-errors "^No further redo information") - (add-to-list 'debug-ignored-errors "^No further redo information for region")) - - - - - -;;; ===================================================================== -;;; Global variables and customization options - -(defvar buffer-undo-tree nil - "Tree of undo entries in current buffer.") -(put 'buffer-undo-tree 'permanent-local t) -(make-variable-buffer-local 'buffer-undo-tree) - - -(defgroup undo-tree nil - "Tree undo/redo." - :group 'undo) - - -(defcustom undo-tree-limit 80000000 - "Value of `undo-limit' used in `undo-tree-mode'. - -If `undo-limit' is larger than `undo-tree-limit', the larger of -the two values will be used. - -See also `undo-tree-strong-limit' and `undo-tree-outer-limit'. - -Setting this to nil prevents `undo-tree-mode' ever discarding -undo history. (As far as possible. In principle, it is still -possible for Emacs to discard undo history behind -`undo-tree-mode's back.) USE THIS SETTING AT YOUR OWN RISK! Emacs -may crash if undo history exceeds Emacs' available memory. This -is particularly risky if `undo-tree-auto-save-history' is -enabled, as in that case undo history is preserved even between -Emacs sessions." - :group 'undo-tree - :type '(choice integer (const nil))) - - -(defcustom undo-tree-strong-limit 120000000 - "Value of `undo-strong-limit' used in `undo-tree-mode'. - -If `undo-strong-limit' is larger than `undo-tree-strong-limit' -the larger of the two values will be used." - :group 'undo-tree - :type 'integer) - - -(defcustom undo-tree-outer-limit 360000000 - "Value of `undo-outer-limit' used in `undo-tree-mode'. - -If `undo-outer-limit' is larger than `undo-tree-outer-limit' the -larger of the two values will be used." - :group 'undo-tree - :type 'integer) - - -(defcustom undo-tree-mode-lighter " Undo-Tree" - "Lighter displayed in mode line -when `undo-tree-mode' is enabled." - :group 'undo-tree - :type 'string) - - -(defcustom undo-tree-incompatible-major-modes '(term-mode) - "List of major-modes in which `undo-tree-mode' should not be enabled. -\(See `turn-on-undo-tree-mode'.\)" - :group 'undo-tree - :type '(repeat symbol)) - - -(defcustom undo-tree-enable-undo-in-region nil - "When non-nil, enable undo-in-region. - -When undo-in-region is enabled, undoing or redoing when the -region is active (in `transient-mark-mode') or with a prefix -argument (not in `transient-mark-mode') only undoes changes -within the current region." - :group 'undo-tree - :type 'boolean) - - -(defcustom undo-tree-auto-save-history nil - "When non-nil, `undo-tree-mode' will save undo history to file -when a buffer is saved to file. - -It will automatically load undo history when a buffer is loaded -from file, if an undo save file exists. - -By default, undo-tree history is saved to a file called -\"..~undo-tree~\" in the same directory as the -file itself. To save under a different directory, customize -`undo-tree-history-directory-alist' (see the documentation for -that variable for details). - -WARNING! `undo-tree-auto-save-history' will not work properly in -Emacs versions prior to 24.3, so it cannot be enabled via -the customization interface in versions earlier than that one. To -ignore this warning and enable it regardless, set -`undo-tree-auto-save-history' to a non-nil value outside of -customize." - :group 'undo-tree - :type (if (version-list-< (version-to-list emacs-version) '(24 3)) - '(choice (const :tag "" nil)) - 'boolean)) - - -(defcustom undo-tree-history-directory-alist nil - "Alist of filename patterns and undo history directory names. -Each element looks like (REGEXP . DIRECTORY). Undo history for -files with names matching REGEXP will be saved in DIRECTORY. -DIRECTORY may be relative or absolute. If it is absolute, so -that all matching files are backed up into the same directory, -the file names in this directory will be the full name of the -file backed up with all directory separators changed to `!' to -prevent clashes. This will not work correctly if your filesystem -truncates the resulting name. - -For the common case of all backups going into one directory, the -alist should contain a single element pairing \".\" with the -appropriate directory name. - -If this variable is nil, or it fails to match a filename, the -backup is made in the original file's directory. - -On MS-DOS filesystems without long names this variable is always -ignored." - :group 'undo-tree - :type '(repeat (cons (regexp :tag "Regexp matching filename") - (directory :tag "Undo history directory name")))) - - - -(defcustom undo-tree-visualizer-relative-timestamps t - "When non-nil, display times relative to current time -when displaying time stamps in visualizer. - -Otherwise, display absolute times." - :group 'undo-tree - :type 'boolean) - - -(defcustom undo-tree-visualizer-timestamps nil - "When non-nil, display time-stamps by default -in undo-tree visualizer. - -\\You can always toggle time-stamps on and off \ -using \\[undo-tree-visualizer-toggle-timestamps], regardless of the -setting of this variable." - :group 'undo-tree - :type 'boolean) - - -(defcustom undo-tree-visualizer-diff nil - "When non-nil, display diff by default in undo-tree visualizer. - -\\You can always toggle the diff display \ -using \\[undo-tree-visualizer-toggle-diff], regardless of the -setting of this variable." - :group 'undo-tree - :type 'boolean) - - -(defcustom undo-tree-visualizer-lazy-drawing 100 - "When non-nil, use lazy undo-tree drawing in visualizer. - -Setting this to a number causes the visualizer to switch to lazy -drawing when the number of nodes in the tree is larger than this -value. - -Lazy drawing means that only the visible portion of the tree will -be drawn initially, and the tree will be extended later as -needed. For the most part, the only visible effect of this is to -significantly speed up displaying the visualizer for very large -trees. - -There is one potential negative effect of lazy drawing. Other -branches of the tree will only be drawn once the node from which -they branch off becomes visible. So it can happen that certain -portions of the tree that would be shown with lazy drawing -disabled, will not be drawn immediately when it is -enabled. However, this effect is quite rare in practice." - :group 'undo-tree - :type '(choice (const :tag "never" nil) - (const :tag "always" t) - (integer :tag "> size"))) - - -(defvar undo-tree-pre-save-element-functions '() - "Special hook to modify undo-tree elements prior to saving. -Each function on this hook is called in turn on each undo element -in the tree by `undo-tree-save-history' prior to writing the undo -history to file. It should return either nil, which removes that -undo element from the saved history, or a replacement element to -use instead (which should be identical to the original element if -that element should be saved unchanged).") - - -(defvar undo-tree-post-load-element-functions '() - "Special hook to modify undo-tree undo elements after loading. -Each function on this hook is called in turn on each undo element -in the tree by `undo-tree-load-history' after loading the undo -history from file. It should return either nil, which removes that -undo element from the loaded history, or a replacement element to -use instead (which should be identical to the original element if -that element should be loaded unchanged).") - - -(defface undo-tree-visualizer-default-face - '((((class color)) :foreground "gray")) - "Face used to draw undo-tree in visualizer." - :group 'undo-tree) - -(defface undo-tree-visualizer-current-face - '((((class color)) :foreground "red")) - "Face used to highlight current undo-tree node in visualizer." - :group 'undo-tree) - -(defface undo-tree-visualizer-active-branch-face - '((((class color) (background dark)) - (:foreground "white" :weight bold)) - (((class color) (background light)) - (:foreground "black" :weight bold))) - "Face used to highlight active undo-tree branch in visualizer." - :group 'undo-tree) - -(defface undo-tree-visualizer-register-face - '((((class color)) :foreground "yellow")) - "Face used to highlight undo-tree nodes saved to a register -in visualizer." - :group 'undo-tree) - -(defface undo-tree-visualizer-unmodified-face - '((((class color)) :foreground "cyan")) - "Face used to highlight nodes corresponding to unmodified buffers -in visualizer." - :group 'undo-tree) - - -(defvar undo-tree-visualizer-parent-buffer nil - "Parent buffer in visualizer.") -(put 'undo-tree-visualizer-parent-buffer 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-parent-buffer) - -;; stores modification time of parent buffer's file, if any -(defvar undo-tree-visualizer-parent-mtime nil) -(put 'undo-tree-visualizer-parent-mtime 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-parent-mtime) - -;; stores current horizontal spacing needed for drawing undo-tree -(defvar undo-tree-visualizer-spacing nil) -(put 'undo-tree-visualizer-spacing 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-spacing) - -;; calculate horizontal spacing required for drawing tree with current -;; settings -(defsubst undo-tree-visualizer-calculate-spacing () - (if undo-tree-visualizer-timestamps - (if undo-tree-visualizer-relative-timestamps 9 13) - 3)) - -;; holds node that was current when visualizer was invoked -(defvar undo-tree-visualizer-initial-node nil) -(put 'undo-tree-visualizer-initial-node 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-initial-node) - -;; holds currently selected node in visualizer selection mode -(defvar undo-tree-visualizer-selected-node nil) -(put 'undo-tree-visualizer-selected-node 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-selected) - -;; used to store nodes at edge of currently drawn portion of tree -(defvar undo-tree-visualizer-needs-extending-down nil) -(put 'undo-tree-visualizer-needs-extending-down 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-needs-extending-down) -(defvar undo-tree-visualizer-needs-extending-up nil) -(put 'undo-tree-visualizer-needs-extending-up 'permanent-local t) -(make-variable-buffer-local 'undo-tree-visualizer-needs-extending-up) - -;; dynamically bound to t when undoing from visualizer, to inhibit -;; `undo-tree-kill-visualizer' hook function in parent buffer -(defvar undo-tree-inhibit-kill-visualizer nil) - -;; can be let-bound to a face name, used in drawing functions -(defvar undo-tree-insert-face nil) - -;; visualizer buffer names -(defconst undo-tree-visualizer-buffer-name " *undo-tree*") -(defconst undo-tree-diff-buffer-name "*undo-tree Diff*") - - - - -;;; ================================================================= -;;; Default keymaps - -(defvar undo-tree-map nil - "Keymap used in undo-tree-mode.") - -(unless undo-tree-map - (let ((map (make-sparse-keymap))) - ;; remap `undo' and `undo-only' to `undo-tree-undo' - (define-key map [remap undo] 'undo-tree-undo) - (define-key map [remap undo-only] 'undo-tree-undo) - ;; bind standard undo bindings (since these match redo counterparts) - (define-key map (kbd "C-/") 'undo-tree-undo) - (define-key map "\C-_" 'undo-tree-undo) - ;; redo doesn't exist normally, so define our own keybindings - (define-key map (kbd "C-?") 'undo-tree-redo) - (define-key map (kbd "M-_") 'undo-tree-redo) - ;; just in case something has defined `redo'... - (define-key map [remap redo] 'undo-tree-redo) - ;; we use "C-x u" for the undo-tree visualizer - (define-key map (kbd "\C-x u") 'undo-tree-visualize) - ;; bind register commands - (define-key map (kbd "C-x r u") 'undo-tree-save-state-to-register) - (define-key map (kbd "C-x r U") 'undo-tree-restore-state-from-register) - ;; set keymap - (setq undo-tree-map map))) - - -(defvar undo-tree-visualizer-mode-map nil - "Keymap used in undo-tree visualizer.") - -(unless undo-tree-visualizer-mode-map - (let ((map (make-sparse-keymap))) - ;; vertical motion keys undo/redo - (define-key map [remap previous-line] 'undo-tree-visualize-undo) - (define-key map [remap next-line] 'undo-tree-visualize-redo) - (define-key map [up] 'undo-tree-visualize-undo) - (define-key map "p" 'undo-tree-visualize-undo) - (define-key map "\C-p" 'undo-tree-visualize-undo) - (define-key map [down] 'undo-tree-visualize-redo) - (define-key map "n" 'undo-tree-visualize-redo) - (define-key map "\C-n" 'undo-tree-visualize-redo) - ;; horizontal motion keys switch branch - (define-key map [remap forward-char] - 'undo-tree-visualize-switch-branch-right) - (define-key map [remap backward-char] - 'undo-tree-visualize-switch-branch-left) - (define-key map [right] 'undo-tree-visualize-switch-branch-right) - (define-key map "f" 'undo-tree-visualize-switch-branch-right) - (define-key map "\C-f" 'undo-tree-visualize-switch-branch-right) - (define-key map [left] 'undo-tree-visualize-switch-branch-left) - (define-key map "b" 'undo-tree-visualize-switch-branch-left) - (define-key map "\C-b" 'undo-tree-visualize-switch-branch-left) - ;; paragraph motion keys undo/redo to significant points in tree - (define-key map [remap backward-paragraph] 'undo-tree-visualize-undo-to-x) - (define-key map [remap forward-paragraph] 'undo-tree-visualize-redo-to-x) - (define-key map "\M-{" 'undo-tree-visualize-undo-to-x) - (define-key map "\M-}" 'undo-tree-visualize-redo-to-x) - (define-key map [C-up] 'undo-tree-visualize-undo-to-x) - (define-key map [C-down] 'undo-tree-visualize-redo-to-x) - ;; mouse sets buffer state to node at click - (define-key map [mouse-1] 'undo-tree-visualizer-mouse-set) - ;; toggle timestamps - (define-key map "t" 'undo-tree-visualizer-toggle-timestamps) - ;; toggle diff - (define-key map "d" 'undo-tree-visualizer-toggle-diff) - ;; toggle selection mode - (define-key map "s" 'undo-tree-visualizer-selection-mode) - ;; horizontal scrolling may be needed if the tree is very wide - (define-key map "," 'undo-tree-visualizer-scroll-left) - (define-key map "." 'undo-tree-visualizer-scroll-right) - (define-key map "<" 'undo-tree-visualizer-scroll-left) - (define-key map ">" 'undo-tree-visualizer-scroll-right) - ;; vertical scrolling may be needed if the tree is very tall - (define-key map [next] 'undo-tree-visualizer-scroll-up) - (define-key map [prior] 'undo-tree-visualizer-scroll-down) - ;; quit/abort visualizer - (define-key map "q" 'undo-tree-visualizer-quit) - (define-key map "\C-q" 'undo-tree-visualizer-abort) - ;; set keymap - (setq undo-tree-visualizer-mode-map map))) - - -(defvar undo-tree-visualizer-selection-mode-map nil - "Keymap used in undo-tree visualizer selection mode.") - -(unless undo-tree-visualizer-selection-mode-map - (let ((map (make-sparse-keymap))) - ;; vertical motion keys move up and down tree - (define-key map [remap previous-line] - 'undo-tree-visualizer-select-previous) - (define-key map [remap next-line] - 'undo-tree-visualizer-select-next) - (define-key map [up] 'undo-tree-visualizer-select-previous) - (define-key map "p" 'undo-tree-visualizer-select-previous) - (define-key map "\C-p" 'undo-tree-visualizer-select-previous) - (define-key map [down] 'undo-tree-visualizer-select-next) - (define-key map "n" 'undo-tree-visualizer-select-next) - (define-key map "\C-n" 'undo-tree-visualizer-select-next) - ;; vertical scroll keys move up and down quickly - (define-key map [next] - (lambda () (interactive) (undo-tree-visualizer-select-next 10))) - (define-key map [prior] - (lambda () (interactive) (undo-tree-visualizer-select-previous 10))) - ;; horizontal motion keys move to left and right siblings - (define-key map [remap forward-char] 'undo-tree-visualizer-select-right) - (define-key map [remap backward-char] 'undo-tree-visualizer-select-left) - (define-key map [right] 'undo-tree-visualizer-select-right) - (define-key map "f" 'undo-tree-visualizer-select-right) - (define-key map "\C-f" 'undo-tree-visualizer-select-right) - (define-key map [left] 'undo-tree-visualizer-select-left) - (define-key map "b" 'undo-tree-visualizer-select-left) - (define-key map "\C-b" 'undo-tree-visualizer-select-left) - ;; horizontal scroll keys move left or right quickly - (define-key map "," - (lambda () (interactive) (undo-tree-visualizer-select-left 10))) - (define-key map "." - (lambda () (interactive) (undo-tree-visualizer-select-right 10))) - (define-key map "<" - (lambda () (interactive) (undo-tree-visualizer-select-left 10))) - (define-key map ">" - (lambda () (interactive) (undo-tree-visualizer-select-right 10))) - ;; sets buffer state to node at point - (define-key map "\r" 'undo-tree-visualizer-set) - ;; mouse selects node at click - (define-key map [mouse-1] 'undo-tree-visualizer-mouse-select) - ;; toggle diff - (define-key map "d" 'undo-tree-visualizer-selection-toggle-diff) - ;; set keymap - (setq undo-tree-visualizer-selection-mode-map map))) - - - - -;;; ===================================================================== -;;; Undo-tree data structure - -(cl-defstruct - (undo-tree - :named - (:constructor nil) - (:constructor make-undo-tree - (&aux - (root (undo-tree-make-node nil nil)) - (current root) - (size 0) - (count 0) - (object-pool (make-hash-table :test 'eq :weakness 'value)))) - (:copier nil)) - root current size count object-pool) - -(defun undo-tree-copy (tree) - ;; Return a copy of undo-tree TREE. - (unwind-protect - (let ((new (make-undo-tree))) - (undo-tree-decircle tree) - (let ((max-lisp-eval-depth (* 100 (undo-tree-count tree))) - (max-specpdl-size (* 100 (undo-tree-count tree)))) - (setf (undo-tree-root new) - (undo-tree-node-copy (undo-tree-root tree) - new (undo-tree-current tree)))) - (setf (undo-tree-size new) - (undo-tree-size tree)) - (setf (undo-tree-count new) - (undo-tree-count tree)) - (setf (undo-tree-object-pool new) - (copy-hash-table (undo-tree-object-pool tree))) - (undo-tree-recircle new) - new) - (undo-tree-recircle tree))) - - -(cl-defstruct - (undo-tree-node - (:type vector) ; create unnamed struct - (:constructor nil) - (:constructor undo-tree-make-node - (previous undo - &optional redo - &aux - (timestamp (current-time)) - (branch 0))) - (:constructor undo-tree-make-node-backwards - (next-node undo - &optional redo - &aux - (next (list next-node)) - (timestamp (current-time)) - (branch 0))) - (:constructor undo-tree-make-empty-node ()) - (:copier nil)) - previous next undo redo timestamp branch meta-data) - - -(defmacro undo-tree-node-p (n) - (let ((len (length (undo-tree-make-node nil nil)))) - `(and (vectorp ,n) (= (length ,n) ,len)))) - -(defun undo-tree-node-copy (node &optional tree current) - ;; Return a copy of undo-tree NODE, sans previous link or meta-data. - ;; If TREE and CURRENT are supplied, set (undo-tree-current TREE) to the - ;; copy of CURRENT node, if found. - (let* ((new (undo-tree-make-empty-node)) - (stack (list (cons node new))) - n) - (while (setq n (pop stack)) - (setf (undo-tree-node-undo (cdr n)) - (copy-tree (undo-tree-node-undo (car n)) 'copy-vectors)) - (setf (undo-tree-node-redo (cdr n)) - (copy-tree (undo-tree-node-redo (car n)) 'copy-vectors)) - (setf (undo-tree-node-timestamp (cdr n)) - (copy-sequence (undo-tree-node-timestamp (car n)))) - (setf (undo-tree-node-branch (cdr n)) - (undo-tree-node-branch (car n))) - (setf (undo-tree-node-next (cdr n)) - (mapcar (lambda (_) (undo-tree-make-empty-node)) - (make-list (length (undo-tree-node-next (car n))) nil))) - ;; set (undo-tree-current TREE) to copy if we've found CURRENT - (when (and tree (eq (car n) current)) - (setf (undo-tree-current tree) (cdr n))) - ;; recursively copy next nodes - (let ((next0 (undo-tree-node-next (car n))) - (next1 (undo-tree-node-next (cdr n)))) - (while (and next0 next1) - (push (cons (pop next0) (pop next1)) stack)))) - new)) - - -(cl-defstruct - (undo-tree-region-data - (:type vector) ; create unnamed struct - (:constructor nil) - (:constructor undo-tree-make-region-data - (&optional undo-beginning undo-end - redo-beginning redo-end)) - (:constructor undo-tree-make-undo-region-data - (undo-beginning undo-end)) - (:constructor undo-tree-make-redo-region-data - (redo-beginning redo-end)) - (:copier nil)) - undo-beginning undo-end redo-beginning redo-end) - - -(defmacro undo-tree-region-data-p (r) - (let ((len (length (undo-tree-make-region-data)))) - `(and (vectorp ,r) (= (length ,r) ,len)))) - -(defmacro undo-tree-node-clear-region-data (node) - `(setf (undo-tree-node-meta-data ,node) - (delq nil - (delq :region - (plist-put (undo-tree-node-meta-data ,node) - :region nil))))) - - -(defmacro undo-tree-node-undo-beginning (node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (when (undo-tree-region-data-p r) - (undo-tree-region-data-undo-beginning r)))) - -(defmacro undo-tree-node-undo-end (node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (when (undo-tree-region-data-p r) - (undo-tree-region-data-undo-end r)))) - -(defmacro undo-tree-node-redo-beginning (node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (when (undo-tree-region-data-p r) - (undo-tree-region-data-redo-beginning r)))) - -(defmacro undo-tree-node-redo-end (node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (when (undo-tree-region-data-p r) - (undo-tree-region-data-redo-end r)))) - - -(gv-define-setter undo-tree-node-undo-beginning (val node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (unless (undo-tree-region-data-p r) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :region - (setq r (undo-tree-make-region-data))))) - (setf (undo-tree-region-data-undo-beginning r) ,val))) - -(gv-define-setter undo-tree-node-undo-end (val node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (unless (undo-tree-region-data-p r) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :region - (setq r (undo-tree-make-region-data))))) - (setf (undo-tree-region-data-undo-end r) ,val))) - -(gv-define-setter undo-tree-node-redo-beginning (val node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (unless (undo-tree-region-data-p r) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :region - (setq r (undo-tree-make-region-data))))) - (setf (undo-tree-region-data-redo-beginning r) ,val))) - -(gv-define-setter undo-tree-node-redo-end (val node) - `(let ((r (plist-get (undo-tree-node-meta-data ,node) :region))) - (unless (undo-tree-region-data-p r) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :region - (setq r (undo-tree-make-region-data))))) - (setf (undo-tree-region-data-redo-end r) ,val))) - - - -(cl-defstruct - (undo-tree-visualizer-data - (:type vector) ; create unnamed struct - (:constructor nil) - (:constructor undo-tree-make-visualizer-data - (&optional lwidth cwidth rwidth marker)) - (:copier nil)) - lwidth cwidth rwidth marker) - - -(defmacro undo-tree-visualizer-data-p (v) - (let ((len (length (undo-tree-make-visualizer-data)))) - `(and (vectorp ,v) (= (length ,v) ,len)))) - -(defun undo-tree-node-clear-visualizer-data (node) - (let ((plist (undo-tree-node-meta-data node))) - (if (eq (car plist) :visualizer) - (setf (undo-tree-node-meta-data node) (nthcdr 2 plist)) - (while (and plist (not (eq (cadr plist) :visualizer))) - (setq plist (cdr plist))) - (if plist (setcdr plist (nthcdr 3 plist)))))) - -(defmacro undo-tree-node-lwidth (node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (when (undo-tree-visualizer-data-p v) - (undo-tree-visualizer-data-lwidth v)))) - -(defmacro undo-tree-node-cwidth (node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (when (undo-tree-visualizer-data-p v) - (undo-tree-visualizer-data-cwidth v)))) - -(defmacro undo-tree-node-rwidth (node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (when (undo-tree-visualizer-data-p v) - (undo-tree-visualizer-data-rwidth v)))) - -(defmacro undo-tree-node-marker (node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (when (undo-tree-visualizer-data-p v) - (undo-tree-visualizer-data-marker v)))) - - -(gv-define-setter undo-tree-node-lwidth (val node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (unless (undo-tree-visualizer-data-p v) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :visualizer - (setq v (undo-tree-make-visualizer-data))))) - (setf (undo-tree-visualizer-data-lwidth v) ,val))) - -(gv-define-setter undo-tree-node-cwidth (val node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (unless (undo-tree-visualizer-data-p v) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :visualizer - (setq v (undo-tree-make-visualizer-data))))) - (setf (undo-tree-visualizer-data-cwidth v) ,val))) - -(gv-define-setter undo-tree-node-rwidth (val node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (unless (undo-tree-visualizer-data-p v) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :visualizer - (setq v (undo-tree-make-visualizer-data))))) - (setf (undo-tree-visualizer-data-rwidth v) ,val))) - -(gv-define-setter undo-tree-node-marker (val node) - `(let ((v (plist-get (undo-tree-node-meta-data ,node) :visualizer))) - (unless (undo-tree-visualizer-data-p v) - (setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :visualizer - (setq v (undo-tree-make-visualizer-data))))) - (setf (undo-tree-visualizer-data-marker v) ,val))) - - - -(cl-defstruct - (undo-tree-register-data - (:type vector) - (:constructor nil) - (:constructor undo-tree-make-register-data (buffer node))) - buffer node) - -(defun undo-tree-register-data-p (data) - (and (vectorp data) - (= (length data) 2) - (undo-tree-node-p (undo-tree-register-data-node data)))) - -(defun undo-tree-register-data-print-func (data) - (princ (format "an undo-tree state for buffer %s" - (undo-tree-register-data-buffer data)))) - -(defmacro undo-tree-node-register (node) - `(plist-get (undo-tree-node-meta-data ,node) :register)) - -(gv-define-setter undo-tree-node-register (val node) - `(setf (undo-tree-node-meta-data ,node) - (plist-put (undo-tree-node-meta-data ,node) :register ,val))) - - - - -;;; ===================================================================== -;;; Basic undo-tree data structure functions - -(defun undo-tree-grow (undo) - "Add an UNDO node to current branch of `buffer-undo-tree'." - (let* ((current (undo-tree-current buffer-undo-tree)) - (new (undo-tree-make-node current undo))) - (push new (undo-tree-node-next current)) - (setf (undo-tree-current buffer-undo-tree) new))) - - -(defun undo-tree-grow-backwards (node undo &optional redo) - "Add new node *above* undo-tree NODE, and return new node. -Note that this will overwrite NODE's \"previous\" link, so should -only be used on a detached NODE, never on nodes that are already -part of `buffer-undo-tree'." - (let ((new (undo-tree-make-node-backwards node undo redo))) - (setf (undo-tree-node-previous node) new) - new)) - - -(defun undo-tree-splice-node (node splice) - "Splice NODE into undo tree, below node SPLICE. -Note that this will overwrite NODE's \"next\" and \"previous\" -links, so should only be used on a detached NODE, never on nodes -that are already part of `buffer-undo-tree'." - (setf (undo-tree-node-next node) (undo-tree-node-next splice) - (undo-tree-node-branch node) (undo-tree-node-branch splice) - (undo-tree-node-previous node) splice - (undo-tree-node-next splice) (list node) - (undo-tree-node-branch splice) 0) - (dolist (n (undo-tree-node-next node)) - (setf (undo-tree-node-previous n) node))) - - -(defun undo-tree-snip-node (node) - "Snip NODE out of undo tree." - (let* ((parent (undo-tree-node-previous node)) - position p) - ;; if NODE is only child, replace parent's next links with NODE's - (if (= (length (undo-tree-node-next parent)) 0) - (setf (undo-tree-node-next parent) (undo-tree-node-next node) - (undo-tree-node-branch parent) (undo-tree-node-branch node)) - ;; otherwise... - (setq position (undo-tree-position node (undo-tree-node-next parent))) - (cond - ;; if active branch used do go via NODE, set parent's branch to active - ;; branch of NODE - ((= (undo-tree-node-branch parent) position) - (setf (undo-tree-node-branch parent) - (+ position (undo-tree-node-branch node)))) - ;; if active branch didn't go via NODE, update parent's branch to point - ;; to same node as before - ((> (undo-tree-node-branch parent) position) - (cl-incf (undo-tree-node-branch parent) - (1- (length (undo-tree-node-next node)))))) - ;; replace NODE in parent's next list with NODE's entire next list - (if (= position 0) - (setf (undo-tree-node-next parent) - (nconc (undo-tree-node-next node) - (cdr (undo-tree-node-next parent)))) - (setq p (nthcdr (1- position) (undo-tree-node-next parent))) - (setcdr p (nconc (undo-tree-node-next node) (cddr p))))) - ;; update previous links of NODE's children - (dolist (n (undo-tree-node-next node)) - (setf (undo-tree-node-previous n) parent)))) - - -(defun undo-tree-mapc (--undo-tree-mapc-function-- node) - ;; Apply FUNCTION to NODE and to each node below it. - (let ((stack (list node)) - n) - (while (setq n (pop stack)) - (funcall --undo-tree-mapc-function-- n) - (setq stack (append (undo-tree-node-next n) stack))))) - - -(defmacro undo-tree-num-branches () - "Return number of branches at current undo tree node." - '(length (undo-tree-node-next (undo-tree-current buffer-undo-tree)))) - - -(defun undo-tree-position (node list) - "Find the first occurrence of NODE in LIST. -Return the index of the matching item, or nil of not found. -Comparison is done with `eq'." - (let ((i 0)) - (catch 'found - (while (progn - (when (eq node (car list)) (throw 'found i)) - (cl-incf i) - (setq list (cdr list)))) - nil))) - - -(defvar *undo-tree-id-counter* 0) -(make-variable-buffer-local '*undo-tree-id-counter*) - -(defmacro undo-tree-generate-id () - ;; Generate a new, unique id (uninterned symbol). - ;; The name is made by appending a number to "undo-tree-id". - ;; (Copied from CL package `gensym'.) - `(let ((num (prog1 *undo-tree-id-counter* - (cl-incf *undo-tree-id-counter*)))) - (make-symbol (format "undo-tree-id%d" num)))) - - -(defun undo-tree-decircle (undo-tree) - ;; Nullify PREVIOUS links of UNDO-TREE nodes, to make UNDO-TREE data - ;; structure non-circular. - (undo-tree-mapc - (lambda (node) - (dolist (n (undo-tree-node-next node)) - (setf (undo-tree-node-previous n) nil))) - (undo-tree-root undo-tree))) - - -(defun undo-tree-recircle (undo-tree) - ;; Recreate PREVIOUS links of UNDO-TREE nodes, to restore circular UNDO-TREE - ;; data structure. - (undo-tree-mapc - (lambda (node) - (dolist (n (undo-tree-node-next node)) - (setf (undo-tree-node-previous n) node))) - (undo-tree-root undo-tree))) - - - - -;;; ===================================================================== -;;; Undo list and undo changeset utility functions - -(defmacro undo-list-marker-elt-p (elt) - `(markerp (car-safe ,elt))) - -(defmacro undo-list-GCd-marker-elt-p (elt) - ;; Return t if ELT is a marker element whose marker has been moved to the - ;; object-pool, so may potentially have been garbage-collected. - ;; Note: Valid marker undo elements should be uniquely identified as cons - ;; cells with a symbol in the car (replacing the marker), and a number in - ;; the cdr. However, to guard against future changes to undo element - ;; formats, we perform an additional redundant check on the symbol name. - `(and (car-safe ,elt) - (symbolp (car ,elt)) - (let ((str (symbol-name (car ,elt)))) - (and (> (length str) 12) - (string= (substring str 0 12) "undo-tree-id"))) - (numberp (cdr-safe ,elt)))) - - -(defun undo-tree-move-GC-elts-to-pool (elt) - ;; Move elements that can be garbage-collected into `buffer-undo-tree' - ;; object pool, substituting a unique id that can be used to retrieve them - ;; later. (Only markers require this treatment currently.) - (when (undo-list-marker-elt-p elt) - (let ((id (undo-tree-generate-id))) - (puthash id (car elt) (undo-tree-object-pool buffer-undo-tree)) - (setcar elt id)))) - - -(defun undo-tree-restore-GC-elts-from-pool (elt) - ;; Replace object id's in ELT with corresponding objects from - ;; `buffer-undo-tree' object pool and return modified ELT, or return nil if - ;; any object in ELT has been garbage-collected. - (if (undo-list-GCd-marker-elt-p elt) - (when (setcar elt (gethash (car elt) - (undo-tree-object-pool buffer-undo-tree))) - elt) - elt)) - - -(defun undo-list-clean-GCd-elts (undo-list) - ;; Remove object id's from UNDO-LIST that refer to elements that have been - ;; garbage-collected. UNDO-LIST is modified by side-effect. - (while (undo-list-GCd-marker-elt-p (car undo-list)) - (unless (gethash (caar undo-list) - (undo-tree-object-pool buffer-undo-tree)) - (setq undo-list (cdr undo-list)))) - (let ((p undo-list)) - (while (cdr p) - (when (and (undo-list-GCd-marker-elt-p (cadr p)) - (null (gethash (car (cadr p)) - (undo-tree-object-pool buffer-undo-tree)))) - (setcdr p (cddr p))) - (setq p (cdr p)))) - undo-list) - - -(defun undo-list-found-canary-p (undo-list) - (or (eq (car undo-list) 'undo-tree-canary) - (and (null (car undo-list)) - (eq (cadr undo-list) 'undo-tree-canary)))) - - -(defmacro undo-list-pop-changeset (undo-list &optional discard-pos) - ;; Pop changeset from `undo-list'. If DISCARD-POS is non-nil, discard - ;; any position entries from changeset. - `(when (and ,undo-list (not (undo-list-found-canary-p ,undo-list))) - (let (changeset) - ;; discard initial undo boundary(ies) - (while (null (car ,undo-list)) (setq ,undo-list (cdr ,undo-list))) - ;; pop elements up to next undo boundary, discarding position entries - ;; if DISCARD-POS is non-nil - (while (null changeset) - (while (and ,undo-list (car ,undo-list) - (not (undo-list-found-canary-p ,undo-list))) - (if (and ,discard-pos (integerp (car ,undo-list))) - (setq ,undo-list (cdr ,undo-list)) - (push (pop ,undo-list) changeset) - (undo-tree-move-GC-elts-to-pool (car changeset))))) - (nreverse changeset)))) - - -(defun undo-tree-copy-list (undo-list) - ;; Return a deep copy of first changeset in `undo-list'. Object id's are - ;; replaced by corresponding objects from `buffer-undo-tree' object-pool. - (let (copy p) - ;; if first element contains an object id, replace it with object from - ;; pool, discarding element entirely if it's been GC'd - (while (and undo-list (null copy)) - (setq copy - (undo-tree-restore-GC-elts-from-pool (pop undo-list)))) - (when copy - (setq copy (list copy) - p copy) - ;; copy remaining elements, replacing object id's with objects from - ;; pool, or discarding them entirely if they've been GC'd - (while undo-list - (when (setcdr p (undo-tree-restore-GC-elts-from-pool - (undo-copy-list-1 (pop undo-list)))) - (setcdr p (list (cdr p))) - (setq p (cdr p)))) - copy))) - - -(defvar undo-tree-gc-flag nil) - -(defun undo-tree-post-gc () - (setq undo-tree-gc-flag t)) - - -(defun undo-list-transfer-to-tree () - ;; Transfer entries accumulated in `undo-list' to `buffer-undo-tree'. - - ;; `undo-list-transfer-to-tree' should never be called when undo is disabled - ;; (i.e. `buffer-undo-tree' is t) - (cl-assert (not (eq buffer-undo-tree t))) - - ;; if `buffer-undo-tree' is empty, create initial undo-tree - (when (null buffer-undo-tree) (setq buffer-undo-tree (make-undo-tree))) - - ;; garbage-collect then repeatedly try to deep-copy `buffer-undo-list' until - ;; we succeed without GC running, in an attempt to mitigate race conditions - ;; with garbage collector corrupting undo history (is this even a thing?!) - (unless (or (null buffer-undo-list) - (undo-list-found-canary-p buffer-undo-list)) - (garbage-collect)) - (let (undo-list changeset) - (setq undo-tree-gc-flag t) - (while undo-tree-gc-flag - (setq undo-tree-gc-flag nil - undo-list (copy-tree buffer-undo-list))) - (setq buffer-undo-list '(nil undo-tree-canary)) - - ;; create new node from first changeset in `undo-list', save old - ;; `buffer-undo-tree' current node, and make new node the current node - (when (setq changeset (undo-list-pop-changeset undo-list)) - (let* ((node (undo-tree-make-node nil changeset)) - (splice (undo-tree-current buffer-undo-tree)) - (size (undo-list-byte-size (undo-tree-node-undo node))) - (count 1)) - (setf (undo-tree-current buffer-undo-tree) node) - ;; grow tree fragment backwards using `undo-list' changesets - (while (setq changeset (undo-list-pop-changeset undo-list)) - (setq node (undo-tree-grow-backwards node changeset)) - (cl-incf size (undo-list-byte-size (undo-tree-node-undo node))) - (cl-incf count)) - - ;; if no undo history has been discarded from `undo-list' since last - ;; transfer, splice new tree fragment onto end of old - ;; `buffer-undo-tree' current node - (if (undo-list-found-canary-p undo-list) - (progn - (setf (undo-tree-node-previous node) splice) - (push node (undo-tree-node-next splice)) - (setf (undo-tree-node-branch splice) 0) - (cl-incf (undo-tree-size buffer-undo-tree) size) - (cl-incf (undo-tree-count buffer-undo-tree) count)) - - ;; if undo history has been discarded, replace entire - ;; `buffer-undo-tree' with new tree fragment - (unless (= (undo-tree-size buffer-undo-tree) 0) - (message "Undo history discarded by Emacs (see `undo-limit') - rebuilding undo-tree")) - (setq node (undo-tree-grow-backwards node nil)) - (setf (undo-tree-root buffer-undo-tree) node) - (setf (undo-tree-size buffer-undo-tree) size) - (setf (undo-tree-count buffer-undo-tree) count) - (setq undo-list '(nil undo-tree-canary)))))) - - ;; discard undo history if necessary - (undo-tree-discard-history)) - - -(defun undo-list-byte-size (undo-list) - ;; Return size (in bytes) of UNDO-LIST - (let ((size 0)) - (dolist (elt undo-list) - (cl-incf size 8) ; cons cells use up 8 bytes - (when (stringp (car-safe elt)) - (cl-incf size (string-bytes (car elt))))) - size)) - - - -(defun undo-list-rebuild-from-tree () - "Rebuild `buffer-undo-list' from information in `buffer-undo-tree'." - (unless (eq buffer-undo-list t) - (undo-list-transfer-to-tree) - (setq buffer-undo-list nil) - (when buffer-undo-tree - (let ((stack (list (list (undo-tree-root buffer-undo-tree))))) - (push (sort (mapcar 'identity (undo-tree-node-next (caar stack))) - (lambda (a b) - (time-less-p (undo-tree-node-timestamp a) - (undo-tree-node-timestamp b)))) - stack) - ;; Traverse tree in depth-and-oldest-first order, but add undo records - ;; on the way down, and redo records on the way up. - (while (or (car stack) - (not (eq (car (nth 1 stack)) - (undo-tree-current buffer-undo-tree)))) - (if (car stack) - (progn - (setq buffer-undo-list - (append (undo-tree-node-undo (caar stack)) - buffer-undo-list)) - (undo-boundary) - (push (sort (mapcar 'identity - (undo-tree-node-next (caar stack))) - (lambda (a b) - (time-less-p (undo-tree-node-timestamp a) - (undo-tree-node-timestamp b)))) - stack)) - (pop stack) - (setq buffer-undo-list - (append (undo-tree-node-redo (caar stack)) - buffer-undo-list)) - (undo-boundary) - (pop (car stack)))))))) - - - - -;;; ===================================================================== -;;; History discarding utility functions - -(defun undo-tree-oldest-leaf (node) - ;; Return oldest leaf node below NODE. - (while (undo-tree-node-next node) - (setq node - (car (sort (mapcar 'identity (undo-tree-node-next node)) - (lambda (a b) - (time-less-p (undo-tree-node-timestamp a) - (undo-tree-node-timestamp b))))))) - node) - - -(defun undo-tree-discard-node (node) - ;; Discard NODE from `buffer-undo-tree', and return next in line for - ;; discarding. - - ;; don't discard current node - (unless (eq node (undo-tree-current buffer-undo-tree)) - - ;; discarding root node... - (if (eq node (undo-tree-root buffer-undo-tree)) - (cond - ;; should always discard branches before root - ((> (length (undo-tree-node-next node)) 1) - (error "Trying to discard undo-tree root which still\ - has multiple branches")) - ;; don't discard root if current node is only child - ((eq (car (undo-tree-node-next node)) - (undo-tree-current buffer-undo-tree)) - nil) - ;; discard root - (t - ;; clear any register referring to root - (let ((r (undo-tree-node-register node))) - (when (and r (eq (get-register r) node)) - (set-register r nil))) - ;; make child of root into new root - (setq node (setf (undo-tree-root buffer-undo-tree) - (car (undo-tree-node-next node)))) - ;; update undo-tree size - (cl-decf (undo-tree-size buffer-undo-tree) - (+ (undo-list-byte-size (undo-tree-node-undo node)) - (undo-list-byte-size (undo-tree-node-redo node)))) - (cl-decf (undo-tree-count buffer-undo-tree)) - ;; discard new root's undo data and PREVIOUS link - (setf (undo-tree-node-undo node) nil - (undo-tree-node-redo node) nil - (undo-tree-node-previous node) nil) - ;; if new root has branches, or new root is current node, next node - ;; to discard is oldest leaf, otherwise it's new root - (if (or (> (length (undo-tree-node-next node)) 1) - (eq (car (undo-tree-node-next node)) - (undo-tree-current buffer-undo-tree))) - (undo-tree-oldest-leaf node) - node))) - - ;; discarding leaf node... - (let* ((parent (undo-tree-node-previous node)) - (current (nth (undo-tree-node-branch parent) - (undo-tree-node-next parent)))) - ;; clear any register referring to the discarded node - (let ((r (undo-tree-node-register node))) - (when (and r (eq (get-register r) node)) - (set-register r nil))) - ;; update undo-tree size - (cl-decf (undo-tree-size buffer-undo-tree) - (+ (undo-list-byte-size (undo-tree-node-undo node)) - (undo-list-byte-size (undo-tree-node-redo node)))) - (cl-decf (undo-tree-count buffer-undo-tree)) - ;; discard leaf - (setf (undo-tree-node-next parent) - (delq node (undo-tree-node-next parent)) - (undo-tree-node-branch parent) - (undo-tree-position current (undo-tree-node-next parent))) - ;; if parent has branches, or parent is current node, next node to - ;; discard is oldest leaf, otherwise it's the parent itself - (if (or (eq parent (undo-tree-current buffer-undo-tree)) - (and (undo-tree-node-next parent) - (or (not (eq parent (undo-tree-root buffer-undo-tree))) - (> (length (undo-tree-node-next parent)) 1)))) - (undo-tree-oldest-leaf parent) - parent))))) - - - -(defun undo-tree-discard-history () - "Discard undo history until we're within memory usage limits -set by `undo-limit', `undo-strong-limit' and `undo-outer-limit'." - - (when (> (undo-tree-size buffer-undo-tree) undo-limit) - ;; if there are no branches off root, first node to discard is root; - ;; otherwise it's leaf node at botom of oldest branch - (let ((node (if (> (length (undo-tree-node-next - (undo-tree-root buffer-undo-tree))) 1) - (undo-tree-oldest-leaf (undo-tree-root buffer-undo-tree)) - (undo-tree-root buffer-undo-tree))) - discarded) - - ;; discard nodes until memory use is within `undo-strong-limit' - (while (and node - (> (undo-tree-size buffer-undo-tree) undo-strong-limit)) - (setq node (undo-tree-discard-node node) - discarded t)) - - ;; discard nodes until next node to discard would bring memory use - ;; within `undo-limit' - (while (and node - ;; check first if last discard has brought us within - ;; `undo-limit', in case we can avoid more expensive - ;; `undo-strong-limit' calculation - ;; Note: this assumes undo-strong-limit > undo-limit; - ;; if not, effectively undo-strong-limit = undo-limit - (> (undo-tree-size buffer-undo-tree) undo-limit) - (> (- (undo-tree-size buffer-undo-tree) - ;; if next node to discard is root, the memory we - ;; free-up comes from discarding changesets from its - ;; only child... - (if (eq node (undo-tree-root buffer-undo-tree)) - (+ (undo-list-byte-size - (undo-tree-node-undo - (car (undo-tree-node-next node)))) - (undo-list-byte-size - (undo-tree-node-redo - (car (undo-tree-node-next node))))) - ;; ...otherwise, it comes from discarding changesets - ;; from along with the node itself - (+ (undo-list-byte-size (undo-tree-node-undo node)) - (undo-list-byte-size (undo-tree-node-redo node))) - )) - undo-limit)) - (setq node (undo-tree-discard-node node) - discarded t)) - - (when discarded - (message "Undo history discarded by undo-tree (see `undo-tree-limit')")) - - ;; if we're still over the `undo-outer-limit', discard entire history - (when (and undo-outer-limit - (> (undo-tree-size buffer-undo-tree) undo-outer-limit)) - ;; query first if `undo-ask-before-discard' is set - (if undo-ask-before-discard - (when (yes-or-no-p - (format - "Buffer `%s' undo info is %d bytes long; discard it? " - (buffer-name) (undo-tree-size buffer-undo-tree))) - (setq buffer-undo-tree nil)) - ;; otherwise, discard and display warning - (display-warning - '(undo discard-info) - (concat - (format "Buffer `%s' undo info was %d bytes long.\n" - (buffer-name) (undo-tree-size buffer-undo-tree)) - "The undo info was discarded because it exceeded\ - `undo-outer-limit'. - -This is normal if you executed a command that made a huge change -to the buffer. In that case, to prevent similar problems in the -future, set `undo-outer-limit' to a value that is large enough to -cover the maximum size of normal changes you expect a single -command to make, but not so large that it might exceed the -maximum memory allotted to Emacs. - -If you did not execute any such command, the situation is -probably due to a bug and you should report it. - -You can disable the popping up of this buffer by adding the entry -\(undo discard-info) to the user option `warning-suppress-types', -which is defined in the `warnings' library.\n") - :warning) - (setq buffer-undo-tree nil))) - - ;; if currently displaying the visualizer, redraw it - (when (and buffer-undo-tree - discarded - (or (eq major-mode 'undo-tree-visualizer-mode) - undo-tree-visualizer-parent-buffer - (get-buffer undo-tree-visualizer-buffer-name))) - (let ((undo-tree buffer-undo-tree)) - (with-current-buffer undo-tree-visualizer-buffer-name - (undo-tree-draw-tree undo-tree) - (when undo-tree-visualizer-diff (undo-tree-visualizer-update-diff))))) - ))) - - - - -;;; ===================================================================== -;;; Visualizer utility functions - -(defun undo-tree-compute-widths (node) - "Recursively compute widths for nodes below NODE." - (let ((stack (list node)) - res) - (while stack - ;; try to compute widths for node at top of stack - (if (undo-tree-node-p - (setq res (undo-tree-node-compute-widths (car stack)))) - ;; if computation fails, it returns a node whose widths still need - ;; computing, which we push onto the stack - (push res stack) - ;; otherwise, store widths and remove it from stack - (setf (undo-tree-node-lwidth (car stack)) (aref res 0) - (undo-tree-node-cwidth (car stack)) (aref res 1) - (undo-tree-node-rwidth (car stack)) (aref res 2)) - (pop stack))))) - - -(defun undo-tree-node-compute-widths (node) - ;; Compute NODE's left-, centre-, and right-subtree widths. Returns widths - ;; (in a vector) if successful. Otherwise, returns a node whose widths need - ;; calculating before NODE's can be calculated. - (let ((num-children (length (undo-tree-node-next node))) - (lwidth 0) (cwidth 0) (rwidth 0) p) - (catch 'need-widths - (cond - ;; leaf nodes have 0 width - ((= 0 num-children) - (setf cwidth 1 - (undo-tree-node-lwidth node) 0 - (undo-tree-node-cwidth node) 1 - (undo-tree-node-rwidth node) 0)) - - ;; odd number of children - ((= (mod num-children 2) 1) - (setq p (undo-tree-node-next node)) - ;; compute left-width - (dotimes (_ (/ num-children 2)) - (if (undo-tree-node-lwidth (car p)) - (cl-incf lwidth (+ (undo-tree-node-lwidth (car p)) - (undo-tree-node-cwidth (car p)) - (undo-tree-node-rwidth (car p)))) - ;; if child's widths haven't been computed, return that child - (throw 'need-widths (car p))) - (setq p (cdr p))) - (if (undo-tree-node-lwidth (car p)) - (cl-incf lwidth (undo-tree-node-lwidth (car p))) - (throw 'need-widths (car p))) - ;; centre-width is inherited from middle child - (setf cwidth (undo-tree-node-cwidth (car p))) - ;; compute right-width - (cl-incf rwidth (undo-tree-node-rwidth (car p))) - (setq p (cdr p)) - (dotimes (_ (/ num-children 2)) - (if (undo-tree-node-lwidth (car p)) - (cl-incf rwidth (+ (undo-tree-node-lwidth (car p)) - (undo-tree-node-cwidth (car p)) - (undo-tree-node-rwidth (car p)))) - (throw 'need-widths (car p))) - (setq p (cdr p)))) - - ;; even number of children - (t - (setq p (undo-tree-node-next node)) - ;; compute left-width - (dotimes (_ (/ num-children 2)) - (if (undo-tree-node-lwidth (car p)) - (cl-incf lwidth (+ (undo-tree-node-lwidth (car p)) - (undo-tree-node-cwidth (car p)) - (undo-tree-node-rwidth (car p)))) - (throw 'need-widths (car p))) - (setq p (cdr p))) - ;; centre-width is 0 when number of children is even - (setq cwidth 0) - ;; compute right-width - (dotimes (_ (/ num-children 2)) - (if (undo-tree-node-lwidth (car p)) - (cl-incf rwidth (+ (undo-tree-node-lwidth (car p)) - (undo-tree-node-cwidth (car p)) - (undo-tree-node-rwidth (car p)))) - (throw 'need-widths (car p))) - (setq p (cdr p))))) - - ;; return left-, centre- and right-widths - (vector lwidth cwidth rwidth)))) - - -(defun undo-tree-clear-visualizer-data (tree) - ;; Clear visualizer data below NODE. - (undo-tree-mapc - (lambda (n) (undo-tree-node-clear-visualizer-data n)) - (undo-tree-root tree))) - - -(defun undo-tree-node-unmodified-p (node &optional mtime) - ;; Return non-nil if NODE corresponds to a buffer state that once upon a - ;; time was unmodified. If a file modification time MTIME is specified, - ;; return non-nil if the corresponding buffer state really is unmodified. - (let (changeset ntime) - (setq changeset - (or (undo-tree-node-redo node) - (and (setq changeset (car (undo-tree-node-next node))) - (undo-tree-node-undo changeset))) - ntime - (catch 'found - (dolist (elt changeset) - (when (and (consp elt) (eq (car elt) t) (consp (cdr elt)) - (throw 'found (cdr elt))))))) - (and ntime - (or (null mtime) - ;; high-precision timestamps - (if (listp (cdr ntime)) - (equal ntime mtime) - ;; old-style timestamps - (and (= (car ntime) (car mtime)) - (= (cdr ntime) (cadr mtime)))))))) - - - - -;;; ===================================================================== -;;; Undo-in-region utility functions - -;; `undo-elt-in-region' uses this as a dynamically-scoped variable -(defvar undo-adjusted-markers nil) - - -(defun undo-tree-pull-undo-in-region-branch (start end) - ;; Pull out entries from undo changesets to create a new undo-in-region - ;; branch, which undoes changeset entries lying between START and END first, - ;; followed by remaining entries from the changesets, before rejoining the - ;; existing undo tree history. Repeated calls will, if appropriate, extend - ;; the current undo-in-region branch rather than creating a new one. - - ;; if we're just reverting the last redo-in-region, we don't need to - ;; manipulate the undo tree at all - (if (undo-tree-reverting-redo-in-region-p start end) - t ; return t to indicate success - - ;; We build the `region-changeset' and `delta-list' lists forwards, using - ;; pointers `r' and `d' to the penultimate element of the list. So that we - ;; don't have to treat the first element differently, we prepend a dummy - ;; leading nil to the lists, and have the pointers point to that - ;; initially. - ;; Note: using '(nil) instead of (list nil) in the `let*' results in - ;; errors when the code is byte-compiled, presumably because the - ;; Lisp reader generates a single cons, and that same cons gets used - ;; each call. - (let* ((region-changeset (list nil)) - (r region-changeset) - (delta-list (list nil)) - (d delta-list) - (node (undo-tree-current buffer-undo-tree)) - (repeated-undo-in-region - (undo-tree-repeated-undo-in-region-p start end)) - undo-adjusted-markers ; `undo-elt-in-region' expects this - fragment splice original-fragment original-splice original-current - got-visible-elt undo-list elt) - - ;; --- initialisation --- - (cond - ;; if this is a repeated undo in the same region, start pulling changes - ;; from NODE at which undo-in-region branch is attached, and detatch - ;; the branch, using it as initial FRAGMENT of branch being constructed - (repeated-undo-in-region - (setq original-current node - fragment (car (undo-tree-node-next node)) - splice node) - ;; undo up to node at which undo-in-region branch is attached - ;; (recognizable as first node with more than one branch) - (let ((mark-active nil)) - (while (= (length (undo-tree-node-next node)) 1) - (undo-tree-undo-1) - (setq fragment node - node (undo-tree-current buffer-undo-tree)))) - (when (eq splice node) (setq splice nil)) - ;; detatch undo-in-region branch - (setf (undo-tree-node-next node) - (delq fragment (undo-tree-node-next node)) - (undo-tree-node-previous fragment) nil - original-fragment fragment - original-splice node)) - - ;; if this is a new undo-in-region, initial FRAGMENT is a copy of all - ;; nodes below the current one in the active branch - ((undo-tree-node-next node) - (setq fragment (undo-tree-make-node nil nil) - splice fragment) - (while (setq node (nth (undo-tree-node-branch node) - (undo-tree-node-next node))) - (push (undo-tree-make-node - splice - (undo-copy-list (undo-tree-node-undo node)) - (undo-copy-list (undo-tree-node-redo node))) - (undo-tree-node-next splice)) - (setq splice (car (undo-tree-node-next splice)))) - (setq fragment (car (undo-tree-node-next fragment)) - splice nil - node (undo-tree-current buffer-undo-tree)))) - - - ;; --- pull undo-in-region elements into branch --- - ;; work backwards up tree, pulling out undo elements within region until - ;; we've got one that undoes a visible change (insertion or deletion) - (catch 'abort - (while (and (not got-visible-elt) node (undo-tree-node-undo node)) - ;; we cons a dummy nil element on the front of the changeset so that - ;; we can conveniently remove the first (real) element from the - ;; changeset if we need to; the leading nil is removed once we're - ;; done with this changeset - (setq undo-list (cons nil (undo-copy-list (undo-tree-node-undo node))) - elt (cadr undo-list)) - (if fragment - (progn - (setq fragment (undo-tree-grow-backwards fragment undo-list)) - (unless splice (setq splice fragment))) - (setq fragment (undo-tree-make-node nil undo-list)) - (setq splice fragment)) - - (while elt - (cond - ;; keep elements within region - ((undo-elt-in-region elt start end) - ;; set flag if kept element is visible (insertion or deletion) - (when (and (consp elt) - (or (stringp (car elt)) (integerp (car elt)))) - (setq got-visible-elt t)) - ;; adjust buffer positions in elements previously undone before - ;; kept element, as kept element will now be undone first - (undo-tree-adjust-elements-to-elt splice elt) - ;; move kept element to undo-in-region changeset, adjusting its - ;; buffer position as it will now be undone first - (setcdr r (list (undo-tree-apply-deltas elt (cdr delta-list)))) - (setq r (cdr r)) - (setcdr undo-list (cddr undo-list))) - - ;; discard "was unmodified" elements - ;; FIXME: deal properly with these - ((and (consp elt) (eq (car elt) t)) - (setcdr undo-list (cddr undo-list))) - - ;; if element crosses region, we can't pull any more elements - ((undo-elt-crosses-region elt start end) - ;; if we've found a visible element, it must be earlier in - ;; current node's changeset; stop pulling elements (null - ;; `undo-list' and non-nil `got-visible-elt' cause loop to exit) - (if got-visible-elt - (setq undo-list nil) - ;; if we haven't found a visible element yet, pulling - ;; undo-in-region branch has failed - (setq region-changeset nil) - (throw 'abort t))) - - ;; if rejecting element, add its delta (if any) to the list - (t - (let ((delta (undo-delta elt))) - (when (/= 0 (cdr delta)) - (setcdr d (list delta)) - (setq d (cdr d)))) - (setq undo-list (cdr undo-list)))) - - ;; process next element of current changeset - (setq elt (cadr undo-list))) - - ;; if there are remaining elements in changeset, remove dummy nil - ;; from front - (if (cadr (undo-tree-node-undo fragment)) - (pop (undo-tree-node-undo fragment)) - ;; otherwise, if we've kept all elements in changeset, discard - ;; empty changeset - (when (eq splice fragment) (setq splice nil)) - (setq fragment (car (undo-tree-node-next fragment)))) - ;; process changeset from next node up the tree - (setq node (undo-tree-node-previous node)))) - - ;; pop dummy nil from front of `region-changeset' - (setq region-changeset (cdr region-changeset)) - - - ;; --- integrate branch into tree --- - ;; if no undo-in-region elements were found, restore undo tree - (if (null region-changeset) - (when original-current - (push original-fragment (undo-tree-node-next original-splice)) - (setf (undo-tree-node-branch original-splice) 0 - (undo-tree-node-previous original-fragment) original-splice) - (let ((mark-active nil)) - (while (not (eq (undo-tree-current buffer-undo-tree) - original-current)) - (undo-tree-redo-1))) - nil) ; return nil to indicate failure - - ;; otherwise... - ;; need to undo up to node where new branch will be attached, to - ;; ensure redo entries are populated, and then redo back to where we - ;; started - (let ((mark-active nil) - (current (undo-tree-current buffer-undo-tree))) - (while (not (eq (undo-tree-current buffer-undo-tree) node)) - (undo-tree-undo-1)) - (while (not (eq (undo-tree-current buffer-undo-tree) current)) - (undo-tree-redo-1))) - - (cond - ;; if there's no remaining fragment, just create undo-in-region node - ;; and attach it to parent of last node from which elements were - ;; pulled - ((null fragment) - (setq fragment (undo-tree-make-node node region-changeset)) - (push fragment (undo-tree-node-next node)) - (setf (undo-tree-node-branch node) 0) - ;; set current node to undo-in-region node - (setf (undo-tree-current buffer-undo-tree) fragment)) - - ;; if no splice point has been set, add undo-in-region node to top of - ;; fragment and attach it to parent of last node from which elements - ;; were pulled - ((null splice) - (setq fragment (undo-tree-grow-backwards fragment region-changeset)) - (push fragment (undo-tree-node-next node)) - (setf (undo-tree-node-branch node) 0 - (undo-tree-node-previous fragment) node) - ;; set current node to undo-in-region node - (setf (undo-tree-current buffer-undo-tree) fragment)) - - ;; if fragment contains nodes, attach fragment to parent of last node - ;; from which elements were pulled, and splice in undo-in-region node - (t - (setf (undo-tree-node-previous fragment) node) - (push fragment (undo-tree-node-next node)) - (setf (undo-tree-node-branch node) 0) - ;; if this is a repeated undo-in-region, then we've left the current - ;; node at the original splice-point; we need to set the current - ;; node to the equivalent node on the undo-in-region branch and redo - ;; back to where we started - (when repeated-undo-in-region - (setf (undo-tree-current buffer-undo-tree) - (undo-tree-node-previous original-fragment)) - (let ((mark-active nil)) - (while (not (eq (undo-tree-current buffer-undo-tree) splice)) - (undo-tree-redo-1 nil 'preserve-undo)))) - ;; splice new undo-in-region node into fragment - (setq node (undo-tree-make-node nil region-changeset)) - (undo-tree-splice-node node splice) - ;; set current node to undo-in-region node - (setf (undo-tree-current buffer-undo-tree) node))) - - ;; update undo-tree size - (setq node (undo-tree-node-previous fragment)) - (while (progn - (and (setq node (car (undo-tree-node-next node))) - (not (eq node original-fragment)) - (cl-incf (undo-tree-count buffer-undo-tree)) - (cl-incf (undo-tree-size buffer-undo-tree) - (+ (undo-list-byte-size (undo-tree-node-undo node)) - (undo-list-byte-size (undo-tree-node-redo node))))))) - t) ; indicate undo-in-region branch was successfully pulled - ))) - - - -(defun undo-tree-pull-redo-in-region-branch (start end) - ;; Pull out entries from redo changesets to create a new redo-in-region - ;; branch, which redoes changeset entries lying between START and END first, - ;; followed by remaining entries from the changesets. Repeated calls will, - ;; if appropriate, extend the current redo-in-region branch rather than - ;; creating a new one. - - ;; if we're just reverting the last undo-in-region, we don't need to - ;; manipulate the undo tree at all - (if (undo-tree-reverting-undo-in-region-p start end) - t ; return t to indicate success - - ;; We build the `region-changeset' and `delta-list' lists forwards, using - ;; pointers `r' and `d' to the penultimate element of the list. So that we - ;; don't have to treat the first element differently, we prepend a dummy - ;; leading nil to the lists, and have the pointers point to that - ;; initially. - ;; Note: using '(nil) instead of (list nil) in the `let*' causes bizarre - ;; errors when the code is byte-compiled, where parts of the lists - ;; appear to survive across different calls to this function. An - ;; obscure byte-compiler bug, perhaps? - (let* ((region-changeset (list nil)) - (r region-changeset) - (delta-list (list nil)) - (d delta-list) - (node (undo-tree-current buffer-undo-tree)) - (repeated-redo-in-region - (undo-tree-repeated-redo-in-region-p start end)) - undo-adjusted-markers ; `undo-elt-in-region' expects this - fragment splice got-visible-elt redo-list elt) - - ;; --- inisitalisation --- - (cond - ;; if this is a repeated redo-in-region, detach fragment below current - ;; node - (repeated-redo-in-region - (when (setq fragment (car (undo-tree-node-next node))) - (setf (undo-tree-node-previous fragment) nil - (undo-tree-node-next node) - (delq fragment (undo-tree-node-next node))))) - ;; if this is a new redo-in-region, initial fragment is a copy of all - ;; nodes below the current one in the active branch - ((undo-tree-node-next node) - (setq fragment (undo-tree-make-node nil nil) - splice fragment) - (while (setq node (nth (undo-tree-node-branch node) - (undo-tree-node-next node))) - (push (undo-tree-make-node - splice nil - (undo-copy-list (undo-tree-node-redo node))) - (undo-tree-node-next splice)) - (setq splice (car (undo-tree-node-next splice)))) - (setq fragment (car (undo-tree-node-next fragment))))) - - - ;; --- pull redo-in-region elements into branch --- - ;; work down fragment, pulling out redo elements within region until - ;; we've got one that redoes a visible change (insertion or deletion) - (setq node fragment) - (catch 'abort - (while (and (not got-visible-elt) node (undo-tree-node-redo node)) - ;; we cons a dummy nil element on the front of the changeset so that - ;; we can conveniently remove the first (real) element from the - ;; changeset if we need to; the leading nil is removed once we're - ;; done with this changeset - (setq redo-list (push nil (undo-tree-node-redo node)) - elt (cadr redo-list)) - (while elt - (cond - ;; keep elements within region - ((undo-elt-in-region elt start end) - ;; set flag if kept element is visible (insertion or deletion) - (when (and (consp elt) - (or (stringp (car elt)) (integerp (car elt)))) - (setq got-visible-elt t)) - ;; adjust buffer positions in elements previously redone before - ;; kept element, as kept element will now be redone first - (undo-tree-adjust-elements-to-elt fragment elt t) - ;; move kept element to redo-in-region changeset, adjusting its - ;; buffer position as it will now be redone first - (setcdr r (list (undo-tree-apply-deltas elt (cdr delta-list) -1))) - (setq r (cdr r)) - (setcdr redo-list (cddr redo-list))) - - ;; discard "was unmodified" elements - ;; FIXME: deal properly with these - ((and (consp elt) (eq (car elt) t)) - (setcdr redo-list (cddr redo-list))) - - ;; if element crosses region, we can't pull any more elements - ((undo-elt-crosses-region elt start end) - ;; if we've found a visible element, it must be earlier in - ;; current node's changeset; stop pulling elements (null - ;; `redo-list' and non-nil `got-visible-elt' cause loop to exit) - (if got-visible-elt - (setq redo-list nil) - ;; if we haven't found a visible element yet, pulling - ;; redo-in-region branch has failed - (setq region-changeset nil) - (throw 'abort t))) - - ;; if rejecting element, add its delta (if any) to the list - (t - (let ((delta (undo-delta elt))) - (when (/= 0 (cdr delta)) - (setcdr d (list delta)) - (setq d (cdr d)))) - (setq redo-list (cdr redo-list)))) - - ;; process next element of current changeset - (setq elt (cadr redo-list))) - - ;; if there are remaining elements in changeset, remove dummy nil - ;; from front - (if (cadr (undo-tree-node-redo node)) - (pop (undo-tree-node-undo node)) - ;; otherwise, if we've kept all elements in changeset, discard - ;; empty changeset - (if (eq fragment node) - (setq fragment (car (undo-tree-node-next fragment))) - (undo-tree-snip-node node))) - ;; process changeset from next node in fragment - (setq node (car (undo-tree-node-next node))))) - - ;; pop dummy nil from front of `region-changeset' - (setq region-changeset (cdr region-changeset)) - - - ;; --- integrate branch into tree --- - (setq node (undo-tree-current buffer-undo-tree)) - ;; if no redo-in-region elements were found, restore undo tree - (if (null (car region-changeset)) - (when (and repeated-redo-in-region fragment) - (push fragment (undo-tree-node-next node)) - (setf (undo-tree-node-branch node) 0 - (undo-tree-node-previous fragment) node) - nil) ; return nil to indicate failure - - ;; otherwise, add redo-in-region node to top of fragment, and attach - ;; it below current node - (setq fragment - (if fragment - (undo-tree-grow-backwards fragment nil region-changeset) - (undo-tree-make-node nil nil region-changeset))) - (push fragment (undo-tree-node-next node)) - (setf (undo-tree-node-branch node) 0 - (undo-tree-node-previous fragment) node) - ;; update undo-tree size - (unless repeated-redo-in-region - (setq node fragment) - (while (and (setq node (car (undo-tree-node-next node))) - (cl-incf (undo-tree-count buffer-undo-tree)) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size - (undo-tree-node-redo node)))))) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo fragment))) - t) ; indicate redo-in-region branch was successfully pulled - ))) - - - -(defun undo-tree-adjust-elements-to-elt (node undo-elt &optional below) - "Adjust buffer positions of undo elements, starting at NODE's -and going up the tree (or down the active branch if BELOW is -non-nil) and through the nodes' undo elements until we reach -UNDO-ELT. UNDO-ELT must appear somewhere in the undo changeset -of either NODE itself or some node above it in the tree." - (let ((delta (list (undo-delta undo-elt))) - (undo-list (undo-tree-node-undo node))) - ;; adjust elements until we reach UNDO-ELT - (while (and (car undo-list) - (not (eq (car undo-list) undo-elt))) - (setcar undo-list - (undo-tree-apply-deltas (car undo-list) delta -1)) - ;; move to next undo element in list, or to next node if we've run out - ;; of elements - (unless (car (setq undo-list (cdr undo-list))) - (if below - (setq node (nth (undo-tree-node-branch node) - (undo-tree-node-next node))) - (setq node (undo-tree-node-previous node))) - (setq undo-list (undo-tree-node-undo node)))))) - - - -(defun undo-tree-apply-deltas (undo-elt deltas &optional sgn) - ;; Apply DELTAS in order to UNDO-ELT, multiplying deltas by SGN - ;; (only useful value for SGN is -1). - (let (position offset) - (dolist (delta deltas) - (setq position (car delta) - offset (* (cdr delta) (or sgn 1))) - (cond - ;; POSITION - ((integerp undo-elt) - (when (>= undo-elt position) - (setq undo-elt (- undo-elt offset)))) - ;; nil (or any other atom) - ((atom undo-elt)) - ;; (TEXT . POSITION) - ((stringp (car undo-elt)) - (let ((text-pos (abs (cdr undo-elt))) - (point-at-end (< (cdr undo-elt) 0))) - (if (>= text-pos position) - (setcdr undo-elt (* (if point-at-end -1 1) - (- text-pos offset)))))) - ;; (BEGIN . END) - ((integerp (car undo-elt)) - (when (>= (car undo-elt) position) - (setcar undo-elt (- (car undo-elt) offset)) - (setcdr undo-elt (- (cdr undo-elt) offset)))) - ;; (nil PROPERTY VALUE BEG . END) - ((null (car undo-elt)) - (let ((tail (nthcdr 3 undo-elt))) - (when (>= (car tail) position) - (setcar tail (- (car tail) offset)) - (setcdr tail (- (cdr tail) offset))))) - )) - undo-elt)) - - - -(defun undo-tree-repeated-undo-in-region-p (start end) - ;; Return non-nil if undo-in-region between START and END is a repeated - ;; undo-in-region - (let ((node (undo-tree-current buffer-undo-tree))) - (and (setq node - (nth (undo-tree-node-branch node) (undo-tree-node-next node))) - (eq (undo-tree-node-undo-beginning node) start) - (eq (undo-tree-node-undo-end node) end)))) - - -(defun undo-tree-repeated-redo-in-region-p (start end) - ;; Return non-nil if undo-in-region between START and END is a repeated - ;; undo-in-region - (let ((node (undo-tree-current buffer-undo-tree))) - (and (eq (undo-tree-node-redo-beginning node) start) - (eq (undo-tree-node-redo-end node) end)))) - - -;; Return non-nil if undo-in-region between START and END is simply -;; reverting the last redo-in-region -(defalias 'undo-tree-reverting-undo-in-region-p - 'undo-tree-repeated-undo-in-region-p) - - -;; Return non-nil if redo-in-region between START and END is simply -;; reverting the last undo-in-region -(defalias 'undo-tree-reverting-redo-in-region-p - 'undo-tree-repeated-redo-in-region-p) - - - - -;;; ===================================================================== -;;; Undo-tree commands - -(defvar undo-tree-timer nil) - -;;;###autoload -(define-minor-mode undo-tree-mode - "Toggle undo-tree mode. -With no argument, this command toggles the mode. -A positive prefix argument turns the mode on. -A negative prefix argument turns it off. - -Undo-tree-mode replaces Emacs' standard undo feature with a more -powerful yet easier to use version, that treats the undo history -as what it is: a tree. - -The following keys are available in `undo-tree-mode': - - \\{undo-tree-map} - -Within the undo-tree visualizer, the following keys are available: - - \\{undo-tree-visualizer-mode-map}" - - nil ; init value - undo-tree-mode-lighter ; lighter - undo-tree-map ; keymap - - (cond - (undo-tree-mode ; enabling `undo-tree-mode' - (set (make-local-variable 'undo-limit) - (if undo-tree-limit - (max undo-limit undo-tree-limit) - most-positive-fixnum)) - (set (make-local-variable 'undo-strong-limit) - (if undo-tree-limit - (max undo-strong-limit undo-tree-strong-limit) - most-positive-fixnum)) - (set (make-local-variable 'undo-outer-limit) ; null `undo-outer-limit' means no limit - (when (and undo-tree-limit undo-outer-limit undo-outer-limit) - (max undo-outer-limit undo-tree-outer-limit))) - (when (null undo-tree-limit) - (setq undo-tree-timer - (run-with-idle-timer 5 'repeat #'undo-list-transfer-to-tree))) - (add-hook 'post-gc-hook #'undo-tree-post-gc nil)) - - (t ; disabling `undo-tree-mode' - ;; rebuild `buffer-undo-list' from tree so Emacs undo can work - (undo-list-rebuild-from-tree) - (setq buffer-undo-tree nil) - (remove-hook 'post-gc-hook #'undo-tree-post-gc 'local) - (when (timerp undo-tree-timer) (cancel-timer undo-tree-timer)) - (kill-local-variable 'undo-limit) - (kill-local-variable 'undo-strong-limit) - (kill-local-variable 'undo-outer-limit)))) - - -(defun turn-on-undo-tree-mode (&optional print-message) - "Enable `undo-tree-mode' in the current buffer, when appropriate. -Some major modes implement their own undo system, which should -not normally be overridden by `undo-tree-mode'. This command does -not enable `undo-tree-mode' in such buffers. If you want to force -`undo-tree-mode' to be enabled regardless, use (undo-tree-mode 1) -instead. - -The heuristic used to detect major modes in which -`undo-tree-mode' should not be used is to check whether either -the `undo' command has been remapped, or the default undo -keybindings (C-/ and C-_) have been overridden somewhere other -than in the global map. In addition, `undo-tree-mode' will not be -enabled if the buffer's `major-mode' appears in -`undo-tree-incompatible-major-modes'." - (interactive "p") - (if (or (key-binding [remap undo]) - (undo-tree-overridden-undo-bindings-p) - (memq major-mode undo-tree-incompatible-major-modes)) - (when print-message - (message "Buffer does not support undo-tree-mode;\ - undo-tree-mode NOT enabled")) - (undo-tree-mode 1))) - - -(defun undo-tree-overridden-undo-bindings-p () - "Returns t if default undo bindings are overridden, nil otherwise. -Checks if either of the default undo key bindings (\"C-/\" or -\"C-_\") are overridden in the current buffer by any keymap other -than the global one. (So global redefinitions of the default undo -key bindings do not count.)" - (let ((binding1 (lookup-key (current-global-map) [?\C-/])) - (binding2 (lookup-key (current-global-map) [?\C-_]))) - (global-set-key [?\C-/] 'undo) - (global-set-key [?\C-_] 'undo) - (unwind-protect - (or (and (key-binding [?\C-/]) - (not (eq (key-binding [?\C-/]) 'undo))) - (and (key-binding [?\C-_]) - (not (eq (key-binding [?\C-_]) 'undo)))) - (global-set-key [?\C-/] binding1) - (global-set-key [?\C-_] binding2)))) - - -;;;###autoload -(define-globalized-minor-mode global-undo-tree-mode - undo-tree-mode turn-on-undo-tree-mode) - - - -(defun undo-tree-undo (&optional arg) - "Undo changes. -Repeat this command to undo more changes. -A numeric ARG serves as a repeat count. - -In Transient Mark mode when the mark is active, only undo changes -within the current region. Similarly, when not in Transient Mark -mode, just \\[universal-argument] as an argument limits undo to -changes within the current region." - (interactive "*P") - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - ;; throw error if undo is disabled in buffer - (when (eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - (undo-tree-undo-1 arg) - ;; inform user if at branch point - (when (> (undo-tree-num-branches) 1) (message "Undo branch point!"))) - - -(defun undo-tree-undo-1 (&optional arg preserve-redo preserve-timestamps) - ;; Internal undo function. An active mark in `transient-mark-mode', or - ;; non-nil ARG otherwise, enables undo-in-region. Non-nil PRESERVE-REDO - ;; causes the existing redo record to be preserved, rather than replacing it - ;; with the new one generated by undoing. Non-nil PRESERVE-TIMESTAMPS - ;; disables updating of timestamps in visited undo-tree nodes. (This latter - ;; should *only* be used when temporarily visiting another undo state and - ;; immediately returning to the original state afterwards. Otherwise, it - ;; could cause history-discarding errors.) - (let ((undo-in-progress t) - (undo-in-region (and undo-tree-enable-undo-in-region - (or (region-active-p) - (and arg (not (numberp arg)))))) - pos current) - ;; transfer entries accumulated in `buffer-undo-list' to - ;; `buffer-undo-tree' - (undo-list-transfer-to-tree) - - (dotimes (_ (or (and (numberp arg) (prefix-numeric-value arg)) 1)) - ;; check if at top of undo tree - (unless (undo-tree-node-previous (undo-tree-current buffer-undo-tree)) - (user-error "No further undo information")) - - ;; if region is active, or a non-numeric prefix argument was supplied, - ;; try to pull out a new branch of changes affecting the region - (when (and undo-in-region - (not (undo-tree-pull-undo-in-region-branch - (region-beginning) (region-end)))) - (user-error "No further undo information for region")) - - ;; remove any GC'd elements from node's undo list - (setq current (undo-tree-current buffer-undo-tree)) - (cl-decf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-undo current))) - (setf (undo-tree-node-undo current) - (undo-list-clean-GCd-elts (undo-tree-node-undo current))) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-undo current))) - ;; undo one record from undo tree - (when undo-in-region - (setq pos (set-marker (make-marker) (point))) - (set-marker-insertion-type pos t)) - (primitive-undo 1 (undo-tree-copy-list (undo-tree-node-undo current))) - (undo-boundary) - - ;; if preserving old redo record, discard new redo entries that - ;; `primitive-undo' has added to `buffer-undo-list', and remove any GC'd - ;; elements from node's redo list - (if preserve-redo - (progn - (undo-list-pop-changeset buffer-undo-list) - (cl-decf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo current))) - (setf (undo-tree-node-redo current) - (undo-list-clean-GCd-elts (undo-tree-node-redo current))) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo current)))) - ;; otherwise, record redo entries that `primitive-undo' has added to - ;; `buffer-undo-list' in current node's redo record, replacing - ;; existing entry if one already exists - (cl-decf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo current))) - (setf (undo-tree-node-redo current) - (undo-list-pop-changeset buffer-undo-list 'discard-pos)) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo current)))) - - ;; rewind current node and update timestamp - (setf (undo-tree-current buffer-undo-tree) - (undo-tree-node-previous (undo-tree-current buffer-undo-tree))) - (unless preserve-timestamps - (setf (undo-tree-node-timestamp (undo-tree-current buffer-undo-tree)) - (current-time))) - - ;; if undoing-in-region, record current node, region and direction so we - ;; can tell if undo-in-region is repeated, and re-activate mark if in - ;; `transient-mark-mode'; if not, erase any leftover data - (if (not undo-in-region) - (undo-tree-node-clear-region-data current) - (goto-char pos) - ;; note: we deliberately want to store the region information in the - ;; node *below* the now current one - (setf (undo-tree-node-undo-beginning current) (region-beginning) - (undo-tree-node-undo-end current) (region-end)) - (set-marker pos nil))) - - ;; undo deactivates mark unless undoing-in-region - (setq deactivate-mark (not undo-in-region)))) - - - -(defun undo-tree-redo (&optional arg) - "Redo changes. A numeric ARG serves as a repeat count. - -In Transient Mark mode when the mark is active, only redo changes -within the current region. Similarly, when not in Transient Mark -mode, just \\[universal-argument] as an argument limits redo to -changes within the current region." - (interactive "*P") - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - ;; throw error if undo is disabled in buffer - (when (eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - (undo-tree-redo-1 arg) - ;; inform user if at branch point - (when (> (undo-tree-num-branches) 1) (message "Undo branch point!"))) - - -(defun undo-tree-redo-1 (&optional arg preserve-undo preserve-timestamps) - ;; Internal redo function. An active mark in `transient-mark-mode', or - ;; non-nil ARG otherwise, enables undo-in-region. Non-nil PRESERVE-UNDO - ;; causes the existing redo record to be preserved, rather than replacing it - ;; with the new one generated by undoing. Non-nil PRESERVE-TIMESTAMPS - ;; disables updating of timestamps in visited undo-tree nodes. (This latter - ;; should *only* be used when temporarily visiting another undo state and - ;; immediately returning to the original state afterwards. Otherwise, it - ;; could cause history-discarding errors.) - (let ((undo-in-progress t) - (redo-in-region (and undo-tree-enable-undo-in-region - (or (region-active-p) - (and arg (not (numberp arg)))))) - pos current) - ;; transfer entries accumulated in `buffer-undo-list' to - ;; `buffer-undo-tree' - (undo-list-transfer-to-tree) - - (dotimes (_ (or (and (numberp arg) (prefix-numeric-value arg)) 1)) - ;; check if at bottom of undo tree - (when (null (undo-tree-node-next (undo-tree-current buffer-undo-tree))) - (user-error "No further redo information")) - - ;; if region is active, or a non-numeric prefix argument was supplied, - ;; try to pull out a new branch of changes affecting the region - (when (and redo-in-region - (not (undo-tree-pull-redo-in-region-branch - (region-beginning) (region-end)))) - (user-error "No further redo information for region")) - - ;; get next node (but DON'T advance current node in tree yet, in case - ;; redoing fails) - (setq current (undo-tree-current buffer-undo-tree) - current (nth (undo-tree-node-branch current) - (undo-tree-node-next current))) - ;; remove any GC'd elements from node's redo list - (cl-decf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo current))) - (setf (undo-tree-node-redo current) - (undo-list-clean-GCd-elts (undo-tree-node-redo current))) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-redo current))) - ;; redo one record from undo tree - (when redo-in-region - (setq pos (set-marker (make-marker) (point))) - (set-marker-insertion-type pos t)) - (primitive-undo 1 (undo-tree-copy-list (undo-tree-node-redo current))) - (undo-boundary) - ;; advance current node in tree - (setf (undo-tree-current buffer-undo-tree) current) - - ;; if preserving old undo record, discard new undo entries that - ;; `primitive-undo' has added to `buffer-undo-list', and remove any GC'd - ;; elements from node's redo list - (if preserve-undo - (progn - (undo-list-pop-changeset buffer-undo-list) - (cl-decf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-undo current))) - (setf (undo-tree-node-undo current) - (undo-list-clean-GCd-elts (undo-tree-node-undo current))) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-undo current)))) - ;; otherwise, record undo entries that `primitive-undo' has added to - ;; `buffer-undo-list' in current node's undo record, replacing - ;; existing entry if one already exists - (cl-decf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-undo current))) - (setf (undo-tree-node-undo current) - (undo-list-pop-changeset buffer-undo-list 'discard-pos)) - (cl-incf (undo-tree-size buffer-undo-tree) - (undo-list-byte-size (undo-tree-node-undo current)))) - - ;; update timestamp - (unless preserve-timestamps - (setf (undo-tree-node-timestamp current) (current-time))) - - ;; if redoing-in-region, record current node, region and direction so we - ;; can tell if redo-in-region is repeated, and re-activate mark if in - ;; `transient-mark-mode' - (if (not redo-in-region) - (undo-tree-node-clear-region-data current) - (goto-char pos) - (setf (undo-tree-node-redo-beginning current) (region-beginning) - (undo-tree-node-redo-end current) (region-end)) - (set-marker pos nil))) - - ;; redo deactivates the mark unless redoing-in-region - (setq deactivate-mark (not redo-in-region)))) - - - -(defun undo-tree-switch-branch (branch) - "Switch to a different BRANCH of the undo tree. -This will affect which branch to descend when *redoing* changes -using `undo-tree-redo'." - (interactive (list (or (and prefix-arg (prefix-numeric-value prefix-arg)) - (and (not (eq buffer-undo-list t)) - (undo-list-transfer-to-tree) - (let ((b (undo-tree-node-branch - (undo-tree-current - buffer-undo-tree)))) - (cond - ;; switch to other branch if only 2 - ((= (undo-tree-num-branches) 2) (- 1 b)) - ;; prompt if more than 2 - ((> (undo-tree-num-branches) 2) - (read-number - (format "Branch (0-%d, on %d): " - (1- (undo-tree-num-branches)) b))) - )))))) - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - ;; throw error if undo is disabled in buffer - (when (eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - ;; sanity check branch number - (when (<= (undo-tree-num-branches) 1) - (user-error "Not at undo branch point")) - (when (or (< branch 0) (> branch (1- (undo-tree-num-branches)))) - (user-error "Invalid branch number")) - ;; transfer entries accumulated in `buffer-undo-list' to `buffer-undo-tree' - (undo-list-transfer-to-tree) - ;; switch branch - (setf (undo-tree-node-branch (undo-tree-current buffer-undo-tree)) - branch) - (message "Switched to branch %d" branch)) - - -(defun undo-tree-set (node &optional preserve-timestamps) - ;; Set buffer to state corresponding to NODE. Returns intersection point - ;; between path back from current node and path back from selected NODE. - ;; Non-nil PRESERVE-TIMESTAMPS disables updating of timestamps in visited - ;; undo-tree nodes. (This should *only* be used when temporarily visiting - ;; another undo state and immediately returning to the original state - ;; afterwards. Otherwise, it could cause history-discarding errors.) - (let ((path (make-hash-table :test 'eq)) - (n node)) - (puthash (undo-tree-root buffer-undo-tree) t path) - ;; build list of nodes leading back from selected node to root, updating - ;; branches as we go to point down to selected node - (while (progn - (puthash n t path) - (when (undo-tree-node-previous n) - (setf (undo-tree-node-branch (undo-tree-node-previous n)) - (undo-tree-position - n (undo-tree-node-next (undo-tree-node-previous n)))) - (setq n (undo-tree-node-previous n))))) - ;; work backwards from current node until we intersect path back from - ;; selected node - (setq n (undo-tree-current buffer-undo-tree)) - (while (not (gethash n path)) - (setq n (undo-tree-node-previous n))) - ;; ascend tree until intersection node - (while (not (eq (undo-tree-current buffer-undo-tree) n)) - (undo-tree-undo-1 nil nil preserve-timestamps)) - ;; descend tree until selected node - (while (not (eq (undo-tree-current buffer-undo-tree) node)) - (undo-tree-redo-1 nil nil preserve-timestamps)) - n)) ; return intersection node - - - -(defun undo-tree-save-state-to-register (register) - "Store current undo-tree state to REGISTER. -The saved state can be restored using -`undo-tree-restore-state-from-register'. -Argument is a character, naming the register." - (interactive "cUndo-tree state to register: ") - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - ;; throw error if undo is disabled in buffer - (when (eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - ;; transfer entries accumulated in `buffer-undo-list' to `buffer-undo-tree' - (undo-list-transfer-to-tree) - ;; save current node to REGISTER - (set-register - register (registerv-make - (undo-tree-make-register-data - (current-buffer) (undo-tree-current buffer-undo-tree)) - :print-func 'undo-tree-register-data-print-func)) - ;; record REGISTER in current node, for visualizer - (setf (undo-tree-node-register (undo-tree-current buffer-undo-tree)) - register)) - - - -(defun undo-tree-restore-state-from-register (register) - "Restore undo-tree state from REGISTER. -The state must be saved using `undo-tree-save-state-to-register'. -Argument is a character, naming the register." - (interactive "*cRestore undo-tree state from register: ") - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - ;; throw error if undo is disabled in buffer, or if register doesn't contain - ;; an undo-tree node - (let ((data (registerv-data (get-register register)))) - (cond - ((eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - ((not (undo-tree-register-data-p data)) - (user-error "Register doesn't contain undo-tree state")) - ((not (eq (current-buffer) (undo-tree-register-data-buffer data))) - (user-error "Register contains undo-tree state for a different buffer"))) - ;; transfer entries accumulated in `buffer-undo-list' to `buffer-undo-tree' - (undo-list-transfer-to-tree) - ;; restore buffer state corresponding to saved node - (undo-tree-set (undo-tree-register-data-node data)))) - - - - -;;; ===================================================================== -;;; Undo-tree menu bar - -(defvar undo-tree-old-undo-menu-item nil) - -(defun undo-tree-update-menu-bar () - "Update `undo-tree-mode' Edit menu items." - (if undo-tree-mode - (progn - ;; save old undo menu item, and install undo/redo menu items - (setq undo-tree-old-undo-menu-item - (cdr (assq 'undo (lookup-key global-map [menu-bar edit])))) - (define-key (lookup-key global-map [menu-bar edit]) - [undo] '(menu-item "Undo" undo-tree-undo - :enable (and undo-tree-mode - (not buffer-read-only) - (not (eq t buffer-undo-list)) - (not (eq nil buffer-undo-tree)) - (undo-tree-node-previous - (undo-tree-current buffer-undo-tree))) - :help "Undo last operation")) - (define-key-after (lookup-key global-map [menu-bar edit]) - [redo] '(menu-item "Redo" undo-tree-redo - :enable (and undo-tree-mode - (not buffer-read-only) - (not (eq t buffer-undo-list)) - (not (eq nil buffer-undo-tree)) - (undo-tree-node-next - (undo-tree-current buffer-undo-tree))) - :help "Redo last operation") - 'undo)) - ;; uninstall undo/redo menu items - (define-key (lookup-key global-map [menu-bar edit]) - [undo] undo-tree-old-undo-menu-item) - (define-key (lookup-key global-map [menu-bar edit]) - [redo] nil))) - -(add-hook 'menu-bar-update-hook 'undo-tree-update-menu-bar) - - - - -;;; ===================================================================== -;;; Persistent storage commands - -(defun undo-tree-make-history-save-file-name (file) - "Create the undo history file name for FILE. -Normally this is the file's name with \".\" prepended and -\".~undo-tree~\" appended. - -A match for FILE is sought in `undo-tree-history-directory-alist' -\(see the documentation of that variable for details\). If the -directory for the backup doesn't exist, it is created." - (let* ((backup-directory-alist undo-tree-history-directory-alist) - (name (make-backup-file-name-1 file))) - (concat (file-name-directory name) "." (file-name-nondirectory name) - ".~undo-tree~"))) - - -(defun undo-tree-save-history (&optional filename overwrite) - "Store undo-tree history to file. - -If optional argument FILENAME is omitted, default save file is -\"..~undo-tree\" if buffer is visiting a file. -Otherwise, prompt for one. - -If OVERWRITE is non-nil, any existing file will be overwritten -without asking for confirmation." - (interactive) - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - (when (eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - (undo-list-transfer-to-tree) - (when (and buffer-undo-tree (not (eq buffer-undo-tree t))) - (undo-tree-kill-visualizer) - ;; should be cleared already by killing the visualizer, but writes - ;; unreasable data if not for some reason, so just in case... - (undo-tree-clear-visualizer-data buffer-undo-tree) - (let ((buff (current-buffer)) - tree) - ;; get filename - (unless filename - (setq filename - (if buffer-file-name - (undo-tree-make-history-save-file-name buffer-file-name) - (expand-file-name (read-file-name "File to save in: ") nil)))) - (when (or (not (file-exists-p filename)) - overwrite - (yes-or-no-p (format "Overwrite \"%s\"? " filename))) - ;; transform undo-tree into non-circular structure, and make tmp copy - (setq tree (undo-tree-copy buffer-undo-tree)) - (undo-tree-decircle tree) - ;; discard undo-tree object pool before saving - (setf (undo-tree-object-pool tree) nil) - ;; run pre-save transformer functions - (when undo-tree-pre-save-element-functions - (undo-tree-mapc - (lambda (node) - (let ((changeset (undo-tree-node-undo node))) - (run-hook-wrapped - 'undo-tree-pre-save-element-functions - (lambda (fun) - (setq changeset (delq nil (mapcar fun changeset))))) - (setf (undo-tree-node-undo node) changeset)) - (let ((changeset (undo-tree-node-redo node))) - (run-hook-wrapped - 'undo-tree-pre-save-element-functions - (lambda (fun) - (setq changeset (delq nil (mapcar fun changeset))))) - (setf (undo-tree-node-redo node) changeset))) - (undo-tree-root tree))) - ;; print undo-tree to file - ;; NOTE: We use `with-temp-buffer' instead of `with-temp-file' to - ;; allow `auto-compression-mode' to take effect, in case user - ;; has overridden or advised the default - ;; `undo-tree-make-history-save-file-name' to add a compressed - ;; file extension. - (with-auto-compression-mode - (with-temp-buffer - (prin1 (sha1 buff) (current-buffer)) - (terpri (current-buffer)) - (let ((print-circle t)) (prin1 tree (current-buffer))) - (write-region nil nil filename))))))) - - - -(defun undo-tree-load-history (&optional filename noerror) - "Load undo-tree history from file, for the current buffer. - -If optional argument FILENAME is null, default load file is -\"..~undo-tree\" if buffer is visiting a file. -Otherwise, prompt for one. - -If optional argument NOERROR is non-nil, return nil instead of -signaling an error if file is not found. - -Note this will overwrite any existing undo history." - (interactive) - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - ;; get filename - (unless filename - (setq filename - (if buffer-file-name - (undo-tree-make-history-save-file-name buffer-file-name) - (expand-file-name (read-file-name "File to load from: ") nil)))) - - ;; attempt to read undo-tree from FILENAME - (catch 'load-error - (unless (file-exists-p filename) - (if noerror - (throw 'load-error nil) - (error "File \"%s\" does not exist; could not load undo-tree history" - filename))) - (let (buff hash tree) - (setq buff (current-buffer)) - (with-auto-compression-mode - (with-temp-buffer - (insert-file-contents filename) - (goto-char (point-min)) - (condition-case nil - (setq hash (read (current-buffer))) - (error - (kill-buffer nil) - (funcall (if noerror #'message #'user-error) - "Error reading undo-tree history from \"%s\"" filename) - (throw 'load-error nil))) - (unless (string= (sha1 buff) hash) - (kill-buffer nil) - (funcall (if noerror 'message 'user-error) - "Buffer has been modified; could not load undo-tree history") - (throw 'load-error nil)) - (condition-case nil - (setq tree (read (current-buffer))) - (error - (kill-buffer nil) - (funcall (if noerror #'message #'error) - "Error reading undo-tree history from \"%s\"" filename) - (throw 'load-error nil))) - (kill-buffer nil))) - ;; run post-load transformer functions - (when undo-tree-post-load-element-functions - (undo-tree-mapc - (lambda (node) - (let ((changeset (undo-tree-node-undo node))) - (run-hook-wrapped - 'undo-tree-post-load-element-functions - (lambda (fun) - (setq changeset (delq nil (mapcar fun changeset))))) - (setf (undo-tree-node-undo node) changeset)) - (let ((changeset (undo-tree-node-redo node))) - (run-hook-wrapped - 'undo-tree-post-load-element-functions - (lambda (fun) - (setq changeset (delq nil (mapcar fun changeset))))) - (setf (undo-tree-node-redo node) changeset))) - (undo-tree-root tree))) ;; initialise empty undo-tree object pool - (setf (undo-tree-object-pool tree) - (make-hash-table :test 'eq :weakness 'value)) - ;; restore circular undo-tree data structure - (undo-tree-recircle tree) - ;; create undo-tree object pool - (setf (undo-tree-object-pool tree) - (make-hash-table :test 'eq :weakness 'value)) - (setq buffer-undo-tree tree - buffer-undo-list '(nil undo-tree-canary))))) - - - -;; Versions of save/load functions for use in hooks -(defun undo-tree-save-history-from-hook () - (when (and undo-tree-mode undo-tree-auto-save-history - (not (eq buffer-undo-list t)) - buffer-file-name - (file-writable-p - (undo-tree-make-history-save-file-name buffer-file-name))) - (undo-tree-save-history nil 'overwrite) nil)) - -(define-obsolete-function-alias - 'undo-tree-save-history-hook 'undo-tree-save-history-from-hook - "`undo-tree-save-history-hook' is obsolete since undo-tree - version 0.6.6. Use `undo-tree-save-history-from-hook' instead.") - - -(defun undo-tree-load-history-from-hook () - (when (and undo-tree-mode undo-tree-auto-save-history - (not (eq buffer-undo-list t)) - (not revert-buffer-in-progress-p)) - (undo-tree-load-history nil 'noerror))) - -(define-obsolete-function-alias - 'undo-tree-load-history-hook 'undo-tree-load-history-from-hook - "`undo-tree-load-history-hook' is obsolete since undo-tree - version 0.6.6. Use `undo-tree-load-history-from-hook' instead.") - - -;; install history-auto-save hooks -(add-hook 'write-file-functions #'undo-tree-save-history-from-hook) -(add-hook 'kill-buffer-hook #'undo-tree-save-history-from-hook) -(add-hook 'find-file-hook #'undo-tree-load-history-from-hook) - - - - -;;; ===================================================================== -;;; Visualizer drawing functions - -(defun undo-tree-visualize () - "Visualize the current buffer's undo tree." - (interactive "*") - (unless undo-tree-mode - (user-error "Undo-tree mode not enabled in buffer")) - (deactivate-mark) - ;; throw error if undo is disabled in buffer - (when (eq buffer-undo-list t) - (user-error "No undo information in this buffer")) - ;; transfer entries accumulated in `buffer-undo-list' to `buffer-undo-tree' - (undo-list-transfer-to-tree) - ;; add hook to kill visualizer buffer if original buffer is changed - (add-hook 'before-change-functions 'undo-tree-kill-visualizer nil t) - ;; prepare *undo-tree* buffer, then draw tree in it - (let ((undo-tree buffer-undo-tree) - (buff (current-buffer)) - (display-buffer-mark-dedicated 'soft)) - (switch-to-buffer-other-window - (get-buffer-create undo-tree-visualizer-buffer-name)) - (setq undo-tree-visualizer-parent-buffer buff) - (setq undo-tree-visualizer-parent-mtime - (and (buffer-file-name buff) - (nth 5 (file-attributes (buffer-file-name buff))))) - (setq undo-tree-visualizer-initial-node (undo-tree-current undo-tree)) - (setq undo-tree-visualizer-spacing - (undo-tree-visualizer-calculate-spacing)) - (make-local-variable 'undo-tree-visualizer-timestamps) - (make-local-variable 'undo-tree-visualizer-diff) - (setq buffer-undo-tree undo-tree) - (undo-tree-visualizer-mode) - ;; FIXME; don't know why `undo-tree-visualizer-mode' clears this - (setq buffer-undo-tree undo-tree) - (set (make-local-variable 'undo-tree-visualizer-lazy-drawing) - (or (eq undo-tree-visualizer-lazy-drawing t) - (and (numberp undo-tree-visualizer-lazy-drawing) - (>= (undo-tree-count undo-tree) - undo-tree-visualizer-lazy-drawing)))) - (when undo-tree-visualizer-diff (undo-tree-visualizer-show-diff)) - (let ((inhibit-read-only t)) (undo-tree-draw-tree undo-tree)))) - - -(defun undo-tree-kill-visualizer (&rest _dummy) - ;; Kill visualizer. Added to `before-change-functions' hook of original - ;; buffer when visualizer is invoked. - (unless (or undo-tree-inhibit-kill-visualizer - (null (get-buffer undo-tree-visualizer-buffer-name))) - (with-current-buffer undo-tree-visualizer-buffer-name - (undo-tree-visualizer-quit)))) - - - -(defun undo-tree-draw-tree (undo-tree) - ;; Draw undo-tree in current buffer starting from NODE (or root if nil). - (let ((inhibit-read-only t) - (node (if undo-tree-visualizer-lazy-drawing - (undo-tree-current undo-tree) - (undo-tree-root undo-tree)))) - (erase-buffer) - (setq undo-tree-visualizer-needs-extending-down nil - undo-tree-visualizer-needs-extending-up nil) - (undo-tree-clear-visualizer-data undo-tree) - (undo-tree-compute-widths node) - ;; lazy drawing starts vertically centred and displaced horizontally to - ;; the left (window-width/4), since trees will typically grow right - (if undo-tree-visualizer-lazy-drawing - (progn - (undo-tree-move-down (/ (window-height) 2)) - (undo-tree-move-forward (max 2 (/ (window-width) 4)))) ; left margin - ;; non-lazy drawing starts in centre at top of buffer - (undo-tree-move-down 1) ; top margin - (undo-tree-move-forward - (max (/ (window-width) 2) - (+ (undo-tree-node-char-lwidth node) - ;; add space for left part of left-most time-stamp - (if undo-tree-visualizer-timestamps - (/ (- undo-tree-visualizer-spacing 4) 2) - 0) - 2)))) ; left margin - ;; link starting node to its representation in visualizer - (setf (undo-tree-node-marker node) (make-marker)) - (set-marker-insertion-type (undo-tree-node-marker node) nil) - (move-marker (undo-tree-node-marker node) (point)) - ;; draw undo-tree - (let ((undo-tree-insert-face 'undo-tree-visualizer-default-face) - node-list) - (if (not undo-tree-visualizer-lazy-drawing) - (undo-tree-extend-down node t) - (undo-tree-extend-down node) - (undo-tree-extend-up node) - (setq node-list undo-tree-visualizer-needs-extending-down - undo-tree-visualizer-needs-extending-down nil) - (while node-list (undo-tree-extend-down (pop node-list))))) - ;; highlight active branch - (let ((undo-tree-insert-face 'undo-tree-visualizer-active-branch-face)) - (undo-tree-highlight-active-branch - (or undo-tree-visualizer-needs-extending-up - (undo-tree-root undo-tree)))) - ;; highlight current node - (undo-tree-draw-node (undo-tree-current undo-tree) 'current))) - - -(defun undo-tree-extend-down (node &optional bottom) - ;; Extend tree downwards starting from NODE and point. If BOTTOM is t, - ;; extend all the way down to the leaves. If BOTTOM is a node, extend down - ;; as far as that node. If BOTTOM is an integer, extend down as far as that - ;; line. Otherwise, only extend visible portion of tree. NODE is assumed to - ;; already have a node marker. Returns non-nil if anything was actually - ;; extended. - (let ((extended nil) - (cur-stack (list node)) - next-stack) - ;; don't bother extending if BOTTOM specifies an already-drawn node - (unless (and (undo-tree-node-p bottom) (undo-tree-node-marker bottom)) - ;; draw nodes layer by layer - (while (or cur-stack - (prog1 (setq cur-stack next-stack) - (setq next-stack nil))) - (setq node (pop cur-stack)) - ;; if node is within range being drawn... - (if (or (eq bottom t) - (and (undo-tree-node-p bottom) - (not (eq (undo-tree-node-previous node) bottom))) - (and (integerp bottom) - (>= bottom (line-number-at-pos - (undo-tree-node-marker node)))) - (and (null bottom) - (pos-visible-in-window-p (undo-tree-node-marker node) - nil t))) - ;; ...draw one layer of node's subtree (if not already drawn) - (progn - (unless (and (undo-tree-node-next node) - (undo-tree-node-marker - (nth (undo-tree-node-branch node) - (undo-tree-node-next node)))) - (goto-char (undo-tree-node-marker node)) - (undo-tree-draw-subtree node) - (setq extended t)) - (setq next-stack - (append (undo-tree-node-next node) next-stack))) - ;; ...otherwise, postpone drawing until later - (push node undo-tree-visualizer-needs-extending-down)))) - extended)) - - -(defun undo-tree-extend-up (node &optional top) - ;; Extend tree upwards starting from NODE. If TOP is t, extend all the way - ;; to root. If TOP is a node, extend up as far as that node. If TOP is an - ;; integer, extend up as far as that line. Otherwise, only extend visible - ;; portion of tree. NODE is assumed to already have a node marker. Returns - ;; non-nil if anything was actually extended. - (let ((extended nil) parent) - ;; don't bother extending if TOP specifies an already-drawn node - (unless (and (undo-tree-node-p top) (undo-tree-node-marker top)) - (while node - (setq parent (undo-tree-node-previous node)) - ;; if we haven't reached root... - (if parent - ;; ...and node is within range being drawn... - (if (or (eq top t) - (and (undo-tree-node-p top) (not (eq node top))) - (and (integerp top) - (< top (line-number-at-pos - (undo-tree-node-marker node)))) - (and (null top) - ;; NOTE: we check point in case window-start is outdated - (< (min (line-number-at-pos (point)) - (line-number-at-pos (window-start))) - (line-number-at-pos - (undo-tree-node-marker node))))) - ;; ...and it hasn't already been drawn - (when (not (undo-tree-node-marker parent)) - ;; link parent node to its representation in visualizer - (undo-tree-compute-widths parent) - (undo-tree-move-to-parent node) - (setf (undo-tree-node-marker parent) (make-marker)) - (set-marker-insertion-type - (undo-tree-node-marker parent) nil) - (move-marker (undo-tree-node-marker parent) (point)) - ;; draw subtree beneath parent - (setq undo-tree-visualizer-needs-extending-down - (nconc (delq node (undo-tree-draw-subtree parent)) - undo-tree-visualizer-needs-extending-down)) - (setq extended t)) - ;; ...otherwise, postpone drawing for later and exit - (setq undo-tree-visualizer-needs-extending-up (when parent node) - parent nil)) - - ;; if we've reached root, stop extending and add top margin - (setq undo-tree-visualizer-needs-extending-up nil) - (goto-char (undo-tree-node-marker node)) - (undo-tree-move-up 1) ; top margin - (delete-region (point-min) (line-beginning-position))) - ;; next iteration - (setq node parent))) - extended)) - - -(defun undo-tree-expand-down (from &optional to) - ;; Expand tree downwards. FROM is the node to start expanding from. Stop - ;; expanding at TO if specified. Otherwise, just expand visible portion of - ;; tree and highlight active branch from FROM. - (when undo-tree-visualizer-needs-extending-down - (let ((inhibit-read-only t) - node-list extended) - ;; extend down as far as TO node - (when to - (setq extended (undo-tree-extend-down from to)) - (goto-char (undo-tree-node-marker to)) - (redisplay t)) ; force redisplay to scroll buffer if necessary - ;; extend visible portion of tree downwards - (setq node-list undo-tree-visualizer-needs-extending-down - undo-tree-visualizer-needs-extending-down nil) - (when node-list - (dolist (n node-list) - (when (undo-tree-extend-down n) (setq extended t))) - ;; highlight active branch in newly-extended-down portion, if any - (when extended - (let ((undo-tree-insert-face - 'undo-tree-visualizer-active-branch-face)) - (undo-tree-highlight-active-branch from))))))) - - -(defun undo-tree-expand-up (from &optional to) - ;; Expand tree upwards. FROM is the node to start expanding from, TO is the - ;; node to stop expanding at. If TO node isn't specified, just expand visible - ;; portion of tree and highlight active branch down to FROM. - (when undo-tree-visualizer-needs-extending-up - (let ((inhibit-read-only t) - extended node-list) - ;; extend up as far as TO node - (when to - (setq extended (undo-tree-extend-up from to)) - (goto-char (undo-tree-node-marker to)) - ;; simulate auto-scrolling if close to top of buffer - (when (<= (line-number-at-pos (point)) scroll-margin) - (undo-tree-move-up (if (= scroll-conservatively 0) - (/ (window-height) 2) 3)) - (when (undo-tree-extend-up to) (setq extended t)) - (goto-char (undo-tree-node-marker to)) - (unless (= scroll-conservatively 0) (recenter scroll-margin)))) - ;; extend visible portion of tree upwards - (and undo-tree-visualizer-needs-extending-up - (undo-tree-extend-up undo-tree-visualizer-needs-extending-up) - (setq extended t)) - ;; extend visible portion of tree downwards - (setq node-list undo-tree-visualizer-needs-extending-down - undo-tree-visualizer-needs-extending-down nil) - (dolist (n node-list) (undo-tree-extend-down n)) - ;; highlight active branch in newly-extended-up portion, if any - (when extended - (let ((undo-tree-insert-face - 'undo-tree-visualizer-active-branch-face)) - (undo-tree-highlight-active-branch - (or undo-tree-visualizer-needs-extending-up - (undo-tree-root buffer-undo-tree)) - from)))))) - - - -(defun undo-tree-highlight-active-branch (node &optional end) - ;; Draw highlighted active branch below NODE in current buffer. Stop - ;; highlighting at END node if specified. - (let ((stack (list node))) - ;; draw active branch - (while stack - (setq node (pop stack)) - (unless (or (eq node end) - (memq node undo-tree-visualizer-needs-extending-down)) - (goto-char (undo-tree-node-marker node)) - (setq node (undo-tree-draw-subtree node 'active) - stack (nconc stack node)))))) - - -(defun undo-tree-draw-node (node &optional current) - ;; Draw symbol representing NODE in visualizer. If CURRENT is non-nil, node - ;; is current node. - (goto-char (undo-tree-node-marker node)) - (when undo-tree-visualizer-timestamps - (undo-tree-move-backward (/ undo-tree-visualizer-spacing 2))) - - (let* ((undo-tree-insert-face (and undo-tree-insert-face - (or (and (consp undo-tree-insert-face) - undo-tree-insert-face) - (list undo-tree-insert-face)))) - (register (undo-tree-node-register node)) - (unmodified (if undo-tree-visualizer-parent-mtime - (undo-tree-node-unmodified-p - node undo-tree-visualizer-parent-mtime) - (undo-tree-node-unmodified-p node))) - node-string) - ;; check node's register (if any) still stores appropriate undo-tree state - (unless (and register - (undo-tree-register-data-p - (registerv-data (get-register register))) - (eq node (undo-tree-register-data-node - (registerv-data (get-register register))))) - (setq register nil)) - ;; represent node by different symbols, depending on whether it's the - ;; current node, is saved in a register, or corresponds to an unmodified - ;; buffer - (setq node-string - (cond - (undo-tree-visualizer-timestamps - (undo-tree-timestamp-to-string - (undo-tree-node-timestamp node) - undo-tree-visualizer-relative-timestamps - current register)) - (register (char-to-string register)) - (unmodified "s") - (current "x") - (t "o")) - undo-tree-insert-face - (nconc - (cond - (current '(undo-tree-visualizer-current-face)) - (unmodified '(undo-tree-visualizer-unmodified-face)) - (register '(undo-tree-visualizer-register-face))) - undo-tree-insert-face)) - ;; draw node and link it to its representation in visualizer - (undo-tree-insert node-string) - (undo-tree-move-backward (if undo-tree-visualizer-timestamps - (1+ (/ undo-tree-visualizer-spacing 2)) - 1)) - (move-marker (undo-tree-node-marker node) (point)) - (put-text-property (point) (1+ (point)) 'undo-tree-node node))) - - -(defun undo-tree-draw-subtree (node &optional active-branch) - ;; Draw subtree rooted at NODE. The subtree will start from point. - ;; If ACTIVE-BRANCH is non-nil, just draw active branch below NODE. Returns - ;; list of nodes below NODE. - (let ((num-children (length (undo-tree-node-next node))) - node-list pos trunk-pos n) - ;; draw node itself - (undo-tree-draw-node node) - - (cond - ;; if we're at a leaf node, we're done - ((= num-children 0)) - - ;; if node has only one child, draw it (not strictly necessary to deal - ;; with this case separately, but as it's by far the most common case - ;; this makes the code clearer and more efficient) - ((= num-children 1) - (undo-tree-move-down 1) - (undo-tree-insert ?|) - (undo-tree-move-backward 1) - (undo-tree-move-down 1) - (undo-tree-insert ?|) - (undo-tree-move-backward 1) - (undo-tree-move-down 1) - (setq n (car (undo-tree-node-next node))) - ;; link next node to its representation in visualizer - (unless (markerp (undo-tree-node-marker n)) - (setf (undo-tree-node-marker n) (make-marker)) - (set-marker-insertion-type (undo-tree-node-marker n) nil)) - (move-marker (undo-tree-node-marker n) (point)) - ;; add next node to list of nodes to draw next - (push n node-list)) - - ;; if node has multiple children, draw branches - (t - (undo-tree-move-down 1) - (undo-tree-insert ?|) - (undo-tree-move-backward 1) - (move-marker (setq trunk-pos (make-marker)) (point)) - ;; left subtrees - (undo-tree-move-backward - (- (undo-tree-node-char-lwidth node) - (undo-tree-node-char-lwidth - (car (undo-tree-node-next node))))) - (move-marker (setq pos (make-marker)) (point)) - (setq n (cons nil (undo-tree-node-next node))) - (dotimes (_ (/ num-children 2)) - (setq n (cdr n)) - (when (or (null active-branch) - (eq (car n) - (nth (undo-tree-node-branch node) - (undo-tree-node-next node)))) - (undo-tree-move-forward 2) - (undo-tree-insert ?_ (- trunk-pos pos 2)) - (goto-char pos) - (undo-tree-move-forward 1) - (undo-tree-move-down 1) - (undo-tree-insert ?/) - (undo-tree-move-backward 2) - (undo-tree-move-down 1) - ;; link node to its representation in visualizer - (unless (markerp (undo-tree-node-marker (car n))) - (setf (undo-tree-node-marker (car n)) (make-marker)) - (set-marker-insertion-type (undo-tree-node-marker (car n)) nil)) - (move-marker (undo-tree-node-marker (car n)) (point)) - ;; add node to list of nodes to draw next - (push (car n) node-list)) - (goto-char pos) - (undo-tree-move-forward - (+ (undo-tree-node-char-rwidth (car n)) - (undo-tree-node-char-lwidth (cadr n)) - undo-tree-visualizer-spacing 1)) - (move-marker pos (point))) - ;; middle subtree (only when number of children is odd) - (when (= (mod num-children 2) 1) - (setq n (cdr n)) - (when (or (null active-branch) - (eq (car n) - (nth (undo-tree-node-branch node) - (undo-tree-node-next node)))) - (undo-tree-move-down 1) - (undo-tree-insert ?|) - (undo-tree-move-backward 1) - (undo-tree-move-down 1) - ;; link node to its representation in visualizer - (unless (markerp (undo-tree-node-marker (car n))) - (setf (undo-tree-node-marker (car n)) (make-marker)) - (set-marker-insertion-type (undo-tree-node-marker (car n)) nil)) - (move-marker (undo-tree-node-marker (car n)) (point)) - ;; add node to list of nodes to draw next - (push (car n) node-list)) - (goto-char pos) - (undo-tree-move-forward - (+ (undo-tree-node-char-rwidth (car n)) - (if (cadr n) (undo-tree-node-char-lwidth (cadr n)) 0) - undo-tree-visualizer-spacing 1)) - (move-marker pos (point))) - ;; right subtrees - (move-marker trunk-pos (1+ trunk-pos)) - (dotimes (_ (/ num-children 2)) - (setq n (cdr n)) - (when (or (null active-branch) - (eq (car n) - (nth (undo-tree-node-branch node) - (undo-tree-node-next node)))) - (goto-char trunk-pos) - (undo-tree-insert ?_ (- pos trunk-pos 1)) - (goto-char pos) - (undo-tree-move-backward 1) - (undo-tree-move-down 1) - (undo-tree-insert ?\\) - (undo-tree-move-down 1) - ;; link node to its representation in visualizer - (unless (markerp (undo-tree-node-marker (car n))) - (setf (undo-tree-node-marker (car n)) (make-marker)) - (set-marker-insertion-type (undo-tree-node-marker (car n)) nil)) - (move-marker (undo-tree-node-marker (car n)) (point)) - ;; add node to list of nodes to draw next - (push (car n) node-list)) - (when (cdr n) - (goto-char pos) - (undo-tree-move-forward - (+ (undo-tree-node-char-rwidth (car n)) - (if (cadr n) (undo-tree-node-char-lwidth (cadr n)) 0) - undo-tree-visualizer-spacing 1)) - (move-marker pos (point)))) - )) - ;; return list of nodes to draw next - (nreverse node-list))) - - -(defun undo-tree-node-char-lwidth (node) - ;; Return left-width of NODE measured in characters. - (if (= (length (undo-tree-node-next node)) 0) 0 - (- (* (+ undo-tree-visualizer-spacing 1) (undo-tree-node-lwidth node)) - (if (= (undo-tree-node-cwidth node) 0) - (1+ (/ undo-tree-visualizer-spacing 2)) 0)))) - - -(defun undo-tree-node-char-rwidth (node) - ;; Return right-width of NODE measured in characters. - (if (= (length (undo-tree-node-next node)) 0) 0 - (- (* (+ undo-tree-visualizer-spacing 1) (undo-tree-node-rwidth node)) - (if (= (undo-tree-node-cwidth node) 0) - (1+ (/ undo-tree-visualizer-spacing 2)) 0)))) - - -(defun undo-tree-insert (str &optional arg) - ;; Insert character or string STR ARG times, overwriting, and using - ;; `undo-tree-insert-face'. - (unless arg (setq arg 1)) - (when (characterp str) - (setq str (make-string arg str)) - (setq arg 1)) - (dotimes (_ arg) (insert str)) - (setq arg (* arg (length str))) - (undo-tree-move-forward arg) - ;; make sure mark isn't active, otherwise `backward-delete-char' might - ;; delete region instead of single char if transient-mark-mode is enabled - (setq mark-active nil) - (backward-delete-char arg) - (when undo-tree-insert-face - (put-text-property (- (point) arg) (point) 'face undo-tree-insert-face))) - - -(defun undo-tree-move-down (&optional arg) - ;; Move down, extending buffer if necessary. - (let ((row (line-number-at-pos)) - (col (current-column)) - line) - (unless arg (setq arg 1)) - (forward-line arg) - (setq line (line-number-at-pos)) - ;; if buffer doesn't have enough lines, add some - (when (/= line (+ row arg)) - (cond - ((< arg 0) - (insert (make-string (- line row arg) ?\n)) - (forward-line (+ arg (- row line)))) - (t (insert (make-string (- arg (- line row)) ?\n))))) - (undo-tree-move-forward col))) - - -(defun undo-tree-move-up (&optional arg) - ;; Move up, extending buffer if necessary. - (unless arg (setq arg 1)) - (undo-tree-move-down (- arg))) - - -(defun undo-tree-move-forward (&optional arg) - ;; Move forward, extending buffer if necessary. - (unless arg (setq arg 1)) - (let (n) - (cond - ((>= arg 0) - (setq n (- (line-end-position) (point))) - (if (> n arg) - (forward-char arg) - (end-of-line) - (insert (make-string (- arg n) ? )))) - ((< arg 0) - (setq arg (- arg)) - (setq n (- (point) (line-beginning-position))) - (when (< (- n 2) arg) ; -2 to create left-margin - ;; no space left - shift entire buffer contents right! - (let ((pos (move-marker (make-marker) (point)))) - (set-marker-insertion-type pos t) - (goto-char (point-min)) - (while (not (eobp)) - (insert-before-markers (make-string (- arg -2 n) ? )) - (forward-line 1)) - (goto-char pos))) - (backward-char arg))))) - - -(defun undo-tree-move-backward (&optional arg) - ;; Move backward, extending buffer if necessary. - (unless arg (setq arg 1)) - (undo-tree-move-forward (- arg))) - - -(defun undo-tree-move-to-parent (node) - ;; Move to position of parent of NODE, extending buffer if necessary. - (let* ((parent (undo-tree-node-previous node)) - (n (undo-tree-node-next parent)) - (l (length n)) p) - (goto-char (undo-tree-node-marker node)) - (unless (= l 1) - ;; move horizontally - (setq p (undo-tree-position node n)) - (cond - ;; node in centre subtree: no horizontal movement - ((and (= (mod l 2) 1) (= p (/ l 2)))) - ;; node in left subtree: move right - ((< p (/ l 2)) - (setq n (nthcdr p n)) - (undo-tree-move-forward - (+ (undo-tree-node-char-rwidth (car n)) - (/ undo-tree-visualizer-spacing 2) 1)) - (dotimes (_ (- (/ l 2) p 1)) - (setq n (cdr n)) - (undo-tree-move-forward - (+ (undo-tree-node-char-lwidth (car n)) - (undo-tree-node-char-rwidth (car n)) - undo-tree-visualizer-spacing 1))) - (when (= (mod l 2) 1) - (setq n (cdr n)) - (undo-tree-move-forward - (+ (undo-tree-node-char-lwidth (car n)) - (/ undo-tree-visualizer-spacing 2) 1)))) - (t ;; node in right subtree: move left - (setq n (nthcdr (/ l 2) n)) - (when (= (mod l 2) 1) - (undo-tree-move-backward - (+ (undo-tree-node-char-rwidth (car n)) - (/ undo-tree-visualizer-spacing 2) 1)) - (setq n (cdr n))) - (dotimes (_ (- p (/ l 2) (mod l 2))) - (undo-tree-move-backward - (+ (undo-tree-node-char-lwidth (car n)) - (undo-tree-node-char-rwidth (car n)) - undo-tree-visualizer-spacing 1)) - (setq n (cdr n))) - (undo-tree-move-backward - (+ (undo-tree-node-char-lwidth (car n)) - (/ undo-tree-visualizer-spacing 2) 1))))) - ;; move vertically - (undo-tree-move-up 3))) - - -(defun undo-tree-timestamp-to-string - (timestamp &optional relative current register) - ;; Convert TIMESTAMP to string (either absolute or RELATVE time), indicating - ;; if it's the CURRENT node and/or has an associated REGISTER. - (if relative - ;; relative time - (let ((time (floor (float-time - (time-subtract (current-time) timestamp)))) - n) - (setq time - ;; years - (if (> (setq n (/ time 315360000)) 0) - (if (> n 999) "-ages" (format "-%dy" n)) - (setq time (% time 315360000)) - ;; days - (if (> (setq n (/ time 86400)) 0) - (format "-%dd" n) - (setq time (% time 86400)) - ;; hours - (if (> (setq n (/ time 3600)) 0) - (format "-%dh" n) - (setq time (% time 3600)) - ;; mins - (if (> (setq n (/ time 60)) 0) - (format "-%dm" n) - ;; secs - (format "-%ds" (% time 60))))))) - (setq time (concat - (if current "*" " ") - time - (if register (concat "[" (char-to-string register) "]") - " "))) - (setq n (length time)) - (if (< n 9) - (concat (make-string (- 9 n) ? ) time) - time)) - ;; absolute time - (concat (if current " *" " ") - (format-time-string "%H:%M:%S" timestamp) - (if register - (concat "[" (char-to-string register) "]") - " ")))) - - - - -;;; ===================================================================== -;;; Visualizer modes - -(define-derived-mode - undo-tree-visualizer-mode special-mode "undo-tree-visualizer" - "Major mode used in undo-tree visualizer. - -The undo-tree visualizer can only be invoked from a buffer in -which `undo-tree-mode' is enabled. The visualizer displays the -undo history tree graphically, and allows you to browse around -the undo history, undoing or redoing the corresponding changes in -the parent buffer. - -Within the undo-tree visualizer, the following keys are available: - - \\{undo-tree-visualizer-mode-map}" - :syntax-table nil - :abbrev-table nil - (setq truncate-lines t) - (setq cursor-type nil) - (setq undo-tree-visualizer-selected-node nil)) - - -(define-minor-mode undo-tree-visualizer-selection-mode - "Toggle mode to select nodes in undo-tree visualizer." - :lighter "Select" - :keymap undo-tree-visualizer-selection-mode-map - :group undo-tree - (cond - ;; enable selection mode - (undo-tree-visualizer-selection-mode - (setq cursor-type 'box) - (setq undo-tree-visualizer-selected-node - (undo-tree-current buffer-undo-tree)) - ;; erase diff (if any), as initially selected node is identical to current - (when undo-tree-visualizer-diff - (let ((buff (get-buffer undo-tree-diff-buffer-name)) - (inhibit-read-only t)) - (when buff (with-current-buffer buff (erase-buffer)))))) - (t ;; disable selection mode - (setq cursor-type nil) - (setq undo-tree-visualizer-selected-node nil) - (goto-char (undo-tree-node-marker (undo-tree-current buffer-undo-tree))) - (when undo-tree-visualizer-diff (undo-tree-visualizer-update-diff))) - )) - - - - -;;; ===================================================================== -;;; Visualizer commands - -(defun undo-tree-visualize-undo (&optional arg) - "Undo changes. A numeric ARG serves as a repeat count." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((old (undo-tree-current buffer-undo-tree)) - current) - ;; undo in parent buffer - (switch-to-buffer-other-window undo-tree-visualizer-parent-buffer) - (deactivate-mark) - (unwind-protect - (let ((undo-tree-inhibit-kill-visualizer t)) (undo-tree-undo-1 arg)) - (setq current (undo-tree-current buffer-undo-tree)) - (switch-to-buffer-other-window undo-tree-visualizer-buffer-name) - ;; unhighlight old current node - (let ((undo-tree-insert-face 'undo-tree-visualizer-active-branch-face) - (inhibit-read-only t)) - (undo-tree-draw-node old)) - ;; when using lazy drawing, extend tree upwards as required - (when undo-tree-visualizer-lazy-drawing - (undo-tree-expand-up old current)) - ;; highlight new current node - (let ((inhibit-read-only t)) (undo-tree-draw-node current 'current)) - ;; update diff display, if any - (when undo-tree-visualizer-diff (undo-tree-visualizer-update-diff))))) - - -(defun undo-tree-visualize-redo (&optional arg) - "Redo changes. A numeric ARG serves as a repeat count." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((old (undo-tree-current buffer-undo-tree)) - current) - ;; redo in parent buffer - (switch-to-buffer-other-window undo-tree-visualizer-parent-buffer) - (deactivate-mark) - (unwind-protect - (let ((undo-tree-inhibit-kill-visualizer t)) (undo-tree-redo-1 arg)) - (setq current (undo-tree-current buffer-undo-tree)) - (switch-to-buffer-other-window undo-tree-visualizer-buffer-name) - ;; unhighlight old current node - (let ((undo-tree-insert-face 'undo-tree-visualizer-active-branch-face) - (inhibit-read-only t)) - (undo-tree-draw-node old)) - ;; when using lazy drawing, extend tree downwards as required - (when undo-tree-visualizer-lazy-drawing - (undo-tree-expand-down old current)) - ;; highlight new current node - (let ((inhibit-read-only t)) (undo-tree-draw-node current 'current)) - ;; update diff display, if any - (when undo-tree-visualizer-diff (undo-tree-visualizer-update-diff))))) - - -(defun undo-tree-visualize-switch-branch-right (arg) - "Switch to next branch of the undo tree. -This will affect which branch to descend when *redoing* changes -using `undo-tree-redo' or `undo-tree-visualizer-redo'." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - ;; un-highlight old active branch below current node - (goto-char (undo-tree-node-marker (undo-tree-current buffer-undo-tree))) - (let ((undo-tree-insert-face 'undo-tree-visualizer-default-face) - (inhibit-read-only t)) - (undo-tree-highlight-active-branch (undo-tree-current buffer-undo-tree))) - ;; increment branch - (let ((branch (undo-tree-node-branch (undo-tree-current buffer-undo-tree)))) - (setf (undo-tree-node-branch (undo-tree-current buffer-undo-tree)) - (cond - ((>= (+ branch arg) (undo-tree-num-branches)) - (1- (undo-tree-num-branches))) - ((<= (+ branch arg) 0) 0) - (t (+ branch arg)))) - (let ((inhibit-read-only t)) - ;; highlight new active branch below current node - (goto-char (undo-tree-node-marker (undo-tree-current buffer-undo-tree))) - (let ((undo-tree-insert-face 'undo-tree-visualizer-active-branch-face)) - (undo-tree-highlight-active-branch (undo-tree-current buffer-undo-tree))) - ;; re-highlight current node - (undo-tree-draw-node (undo-tree-current buffer-undo-tree) 'current)))) - - -(defun undo-tree-visualize-switch-branch-left (arg) - "Switch to previous branch of the undo tree. -This will affect which branch to descend when *redoing* changes -using `undo-tree-redo' or `undo-tree-visualizer-redo'." - (interactive "p") - (undo-tree-visualize-switch-branch-right (- arg))) - - -(defun undo-tree-visualizer-quit () - "Quit the undo-tree visualizer." - (interactive) - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (undo-tree-clear-visualizer-data buffer-undo-tree) - ;; remove kill visualizer hook from parent buffer - (unwind-protect - (with-current-buffer undo-tree-visualizer-parent-buffer - (remove-hook 'before-change-functions 'undo-tree-kill-visualizer t)) - ;; kill diff buffer, if any - (when undo-tree-visualizer-diff (undo-tree-visualizer-hide-diff)) - (let ((parent undo-tree-visualizer-parent-buffer) - window) - ;; kill visualizer buffer - (kill-buffer nil) - ;; switch back to parent buffer - (unwind-protect - (if (setq window (get-buffer-window parent)) - (select-window window) - (switch-to-buffer parent)))))) - - -(defun undo-tree-visualizer-abort () - "Quit the undo-tree visualizer and return buffer to original state." - (interactive) - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((node undo-tree-visualizer-initial-node)) - (undo-tree-visualizer-quit) - (undo-tree-set node))) - - -(defun undo-tree-visualizer-set (&optional pos) - "Set buffer to state corresponding to undo tree node -at POS, or point if POS is nil." - (interactive) - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (unless pos (setq pos (point))) - (let ((node (get-text-property pos 'undo-tree-node))) - (when node - ;; set parent buffer to state corresponding to node at POS - (switch-to-buffer-other-window undo-tree-visualizer-parent-buffer) - (let ((undo-tree-inhibit-kill-visualizer t)) (undo-tree-set node)) - (switch-to-buffer-other-window undo-tree-visualizer-buffer-name) - ;; re-draw undo tree - (let ((inhibit-read-only t)) (undo-tree-draw-tree buffer-undo-tree)) - (when undo-tree-visualizer-diff (undo-tree-visualizer-update-diff))))) - - -(defun undo-tree-visualizer-mouse-set (pos) - "Set buffer to state corresponding to undo tree node -at mouse event POS." - (interactive "@e") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (undo-tree-visualizer-set (event-start (nth 1 pos)))) - - -(defun undo-tree-visualize-undo-to-x (&optional x) - "Undo to last branch point, register, or saved state. -If X is the symbol `branch', undo to last branch point. If X is -the symbol `register', undo to last register. If X is the symbol -`saved', undo to last saved state. If X is null, undo to first of -these that's encountered. - -Interactively, a single \\[universal-argument] specifies -`branch', a double \\[universal-argument] \\[universal-argument] -specifies `saved', and a negative prefix argument specifies -`register'." - (interactive "P") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (when (and (called-interactively-p 'any) x) - (setq x (prefix-numeric-value x) - x (cond - ((< x 0) 'register) - ((<= x 4) 'branch) - (t 'saved)))) - (let ((current (if undo-tree-visualizer-selection-mode - undo-tree-visualizer-selected-node - (undo-tree-current buffer-undo-tree))) - (diff undo-tree-visualizer-diff) - r) - (undo-tree-visualizer-hide-diff) - (while (and (undo-tree-node-previous current) - (or (if undo-tree-visualizer-selection-mode - (progn - (undo-tree-visualizer-select-previous) - (setq current undo-tree-visualizer-selected-node)) - (undo-tree-visualize-undo) - (setq current (undo-tree-current buffer-undo-tree))) - t) - ;; branch point - (not (or (and (or (null x) (eq x 'branch)) - (> (undo-tree-num-branches) 1)) - ;; register - (and (or (null x) (eq x 'register)) - (setq r (undo-tree-node-register current)) - (undo-tree-register-data-p - (setq r (registerv-data (get-register r)))) - (eq current (undo-tree-register-data-node r))) - ;; saved state - (and (or (null x) (eq x 'saved)) - (undo-tree-node-unmodified-p current)) - )))) - ;; update diff display, if any - (when diff - (undo-tree-visualizer-show-diff - (when undo-tree-visualizer-selection-mode - undo-tree-visualizer-selected-node))))) - - -(defun undo-tree-visualize-redo-to-x (&optional x) - "Redo to last branch point, register, or saved state. -If X is the symbol `branch', redo to last branch point. If X is -the symbol `register', redo to last register. If X is the sumbol -`saved', redo to last saved state. If X is null, redo to first of -these that's encountered. - -Interactively, a single \\[universal-argument] specifies -`branch', a double \\[universal-argument] \\[universal-argument] -specifies `saved', and a negative prefix argument specifies -`register'." - (interactive "P") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (when (and (called-interactively-p 'any) x) - (setq x (prefix-numeric-value x) - x (cond - ((< x 0) 'register) - ((<= x 4) 'branch) - (t 'saved)))) - (let ((current (if undo-tree-visualizer-selection-mode - undo-tree-visualizer-selected-node - (undo-tree-current buffer-undo-tree))) - (diff undo-tree-visualizer-diff) - r) - (undo-tree-visualizer-hide-diff) - (while (and (undo-tree-node-next current) - (or (if undo-tree-visualizer-selection-mode - (progn - (undo-tree-visualizer-select-next) - (setq current undo-tree-visualizer-selected-node)) - (undo-tree-visualize-redo) - (setq current (undo-tree-current buffer-undo-tree))) - t) - ;; branch point - (not (or (and (or (null x) (eq x 'branch)) - (> (undo-tree-num-branches) 1)) - ;; register - (and (or (null x) (eq x 'register)) - (setq r (undo-tree-node-register current)) - (undo-tree-register-data-p - (setq r (registerv-data (get-register r)))) - (eq current (undo-tree-register-data-node r))) - ;; saved state - (and (or (null x) (eq x 'saved)) - (undo-tree-node-unmodified-p current)) - )))) - ;; update diff display, if any - (when diff - (undo-tree-visualizer-show-diff - (when undo-tree-visualizer-selection-mode - undo-tree-visualizer-selected-node))))) - - -(defun undo-tree-visualizer-toggle-timestamps () - "Toggle display of time-stamps." - (interactive) - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (setq undo-tree-visualizer-timestamps (not undo-tree-visualizer-timestamps)) - (setq undo-tree-visualizer-spacing (undo-tree-visualizer-calculate-spacing)) - ;; redraw tree - (let ((inhibit-read-only t)) (undo-tree-draw-tree buffer-undo-tree))) - - -(defun undo-tree-visualizer-scroll-left (&optional arg) - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (scroll-left (or arg 1) t)) - - -(defun undo-tree-visualizer-scroll-right (&optional arg) - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (scroll-right (or arg 1) t)) - - -(defun undo-tree-visualizer-scroll-up (&optional arg) - (interactive "P") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (if (or (and (numberp arg) (< arg 0)) (eq arg '-)) - (undo-tree-visualizer-scroll-down arg) - ;; scroll up and expand newly-visible portion of tree - (unwind-protect - (scroll-up-command arg) - (undo-tree-expand-down - (nth (undo-tree-node-branch (undo-tree-current buffer-undo-tree)) - (undo-tree-node-next (undo-tree-current buffer-undo-tree))))) - ;; signal error if at eob - (when (and (not undo-tree-visualizer-needs-extending-down) (eobp)) - (scroll-up)))) - - -(defun undo-tree-visualizer-scroll-down (&optional arg) - (interactive "P") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (if (or (and (numberp arg) (< arg 0)) (eq arg '-)) - (undo-tree-visualizer-scroll-up arg) - ;; ensure there's enough room at top of buffer to scroll - (let ((scroll-lines - (or arg (- (window-height) next-screen-context-lines))) - (window-line (1- (line-number-at-pos (window-start))))) - (when (and undo-tree-visualizer-needs-extending-up - (< window-line scroll-lines)) - (let ((inhibit-read-only t)) - (goto-char (point-min)) - (undo-tree-move-up (- scroll-lines window-line))))) - ;; scroll down and expand newly-visible portion of tree - (unwind-protect - (scroll-down-command arg) - (undo-tree-expand-up - (undo-tree-node-previous (undo-tree-current buffer-undo-tree)))) - ;; signal error if at bob - (when (and (not undo-tree-visualizer-needs-extending-down) (bobp)) - (scroll-down)))) - - - - -;;; ===================================================================== -;;; Visualizer selection mode commands - -(defun undo-tree-visualizer-select-previous (&optional arg) - "Move to previous node." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((node undo-tree-visualizer-selected-node)) - (catch 'top - (dotimes (_ (or arg 1)) - (unless (undo-tree-node-previous node) (throw 'top t)) - (setq node (undo-tree-node-previous node)))) - ;; when using lazy drawing, extend tree upwards as required - (when undo-tree-visualizer-lazy-drawing - (undo-tree-expand-up undo-tree-visualizer-selected-node node)) - ;; update diff display, if any - (when (and undo-tree-visualizer-diff - (not (eq node undo-tree-visualizer-selected-node))) - (undo-tree-visualizer-update-diff node)) - ;; move to selected node - (goto-char (undo-tree-node-marker node)) - (setq undo-tree-visualizer-selected-node node))) - - -(defun undo-tree-visualizer-select-next (&optional arg) - "Move to next node." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((node undo-tree-visualizer-selected-node)) - (catch 'bottom - (dotimes (_ (or arg 1)) - (unless (nth (undo-tree-node-branch node) (undo-tree-node-next node)) - (throw 'bottom t)) - (setq node - (nth (undo-tree-node-branch node) (undo-tree-node-next node))))) - ;; when using lazy drawing, extend tree downwards as required - (when undo-tree-visualizer-lazy-drawing - (undo-tree-expand-down undo-tree-visualizer-selected-node node)) - ;; update diff display, if any - (when (and undo-tree-visualizer-diff - (not (eq node undo-tree-visualizer-selected-node))) - (undo-tree-visualizer-update-diff node)) - ;; move to selected node - (goto-char (undo-tree-node-marker node)) - (setq undo-tree-visualizer-selected-node node))) - - -(defun undo-tree-visualizer-select-right (&optional arg) - "Move right to a sibling node." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((node undo-tree-visualizer-selected-node) - end) - (goto-char (undo-tree-node-marker undo-tree-visualizer-selected-node)) - (setq end (line-end-position)) - (catch 'end - (dotimes (_ arg) - (while (or (null node) (eq node undo-tree-visualizer-selected-node)) - (forward-char) - (setq node (get-text-property (point) 'undo-tree-node)) - (when (= (point) end) (throw 'end t))))) - (goto-char (undo-tree-node-marker - (or node undo-tree-visualizer-selected-node))) - (when (and undo-tree-visualizer-diff node - (not (eq node undo-tree-visualizer-selected-node))) - (undo-tree-visualizer-update-diff node)) - (when node (setq undo-tree-visualizer-selected-node node)))) - - -(defun undo-tree-visualizer-select-left (&optional arg) - "Move left to a sibling node." - (interactive "p") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (let ((node (get-text-property (point) 'undo-tree-node)) - beg) - (goto-char (undo-tree-node-marker undo-tree-visualizer-selected-node)) - (setq beg (line-beginning-position)) - (catch 'beg - (dotimes (_ arg) - (while (or (null node) (eq node undo-tree-visualizer-selected-node)) - (backward-char) - (setq node (get-text-property (point) 'undo-tree-node)) - (when (= (point) beg) (throw 'beg t))))) - (goto-char (undo-tree-node-marker - (or node undo-tree-visualizer-selected-node))) - (when (and undo-tree-visualizer-diff node - (not (eq node undo-tree-visualizer-selected-node))) - (undo-tree-visualizer-update-diff node)) - (when node (setq undo-tree-visualizer-selected-node node)))) - - -(defun undo-tree-visualizer-select (pos) - (let ((node (get-text-property pos 'undo-tree-node))) - (when node - ;; select node at POS - (goto-char (undo-tree-node-marker node)) - ;; when using lazy drawing, extend tree up and down as required - (when undo-tree-visualizer-lazy-drawing - (undo-tree-expand-up undo-tree-visualizer-selected-node node) - (undo-tree-expand-down undo-tree-visualizer-selected-node node)) - ;; update diff display, if any - (when (and undo-tree-visualizer-diff - (not (eq node undo-tree-visualizer-selected-node))) - (undo-tree-visualizer-update-diff node)) - ;; update selected node - (setq undo-tree-visualizer-selected-node node) - ))) - - -(defun undo-tree-visualizer-mouse-select (pos) - "Select undo tree node at mouse event POS." - (interactive "@e") - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (undo-tree-visualizer-select (event-start (nth 1 pos)))) - - - - -;;; ===================================================================== -;;; Visualizer diff display - -(defun undo-tree-visualizer-toggle-diff () - "Toggle diff display in undo-tree visualizer." - (interactive) - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (if undo-tree-visualizer-diff - (undo-tree-visualizer-hide-diff) - (undo-tree-visualizer-show-diff))) - - -(defun undo-tree-visualizer-selection-toggle-diff () - "Toggle diff display in undo-tree visualizer selection mode." - (interactive) - (unless (eq major-mode 'undo-tree-visualizer-mode) - (user-error "Undo-tree mode not enabled in buffer")) - (if undo-tree-visualizer-diff - (undo-tree-visualizer-hide-diff) - (let ((node (get-text-property (point) 'undo-tree-node))) - (when node (undo-tree-visualizer-show-diff node))))) - - -(defun undo-tree-visualizer-show-diff (&optional node) - ;; show visualizer diff display - (setq undo-tree-visualizer-diff t) - (let ((buff (with-current-buffer undo-tree-visualizer-parent-buffer - (undo-tree-diff node))) - (display-buffer-mark-dedicated 'soft) - win) - (setq win (split-window)) - (set-window-buffer win buff) - (shrink-window-if-larger-than-buffer win))) - - -(defun undo-tree-visualizer-hide-diff () - ;; hide visualizer diff display - (setq undo-tree-visualizer-diff nil) - (let ((win (get-buffer-window undo-tree-diff-buffer-name))) - (when win (with-selected-window win (kill-buffer-and-window))))) - - -(defun undo-tree-diff (&optional node) - ;; Create diff between NODE and current state (or previous state and current - ;; state, if NODE is null). Returns buffer containing diff. - (let (tmpfile buff) - ;; generate diff - (let ((undo-tree-inhibit-kill-visualizer t) - (current (undo-tree-current buffer-undo-tree))) - (undo-tree-set (or node (undo-tree-node-previous current) current) - 'preserve-timestamps) - (setq tmpfile (diff-file-local-copy (current-buffer))) - (undo-tree-set current 'preserve-timestamps)) - (setq buff (diff-no-select - tmpfile (current-buffer) nil 'noasync - (get-buffer-create undo-tree-diff-buffer-name))) - ;; delete process messages and useless headers from diff buffer - (let ((inhibit-read-only t)) - (with-current-buffer buff - (goto-char (point-min)) - (delete-region (point) (1+ (line-end-position 3))) - (goto-char (point-max)) - (forward-line -2) - (delete-region (point) (point-max)) - (setq cursor-type nil) - (setq buffer-read-only t))) - buff)) - - -(defun undo-tree-visualizer-update-diff (&optional node) - ;; update visualizer diff display to show diff between current state and - ;; NODE (or previous state, if NODE is null) - (with-current-buffer undo-tree-visualizer-parent-buffer - (undo-tree-diff node)) - (let ((win (get-buffer-window undo-tree-diff-buffer-name))) - (when win - (balance-windows) - (shrink-window-if-larger-than-buffer win)))) - -;;;; ChangeLog: - -;; 2020-01-28 Toby S. Cubitt -;; -;; Undo-tree bug-fix release. -;; -;; 2020-01-26 Toby S. Cubitt -;; -;; Undo-tree point release. -;; -;; 2020-01-11 Toby S. Cubitt -;; -;; Undo-tree bug-fix release. -;; -;; 2020-01-09 Toby S. Cubitt -;; -;; Bump undo-tree version number. -;; -;; 2020-01-09 Toby S. Cubitt -;; -;; Undo-tree bug-fix release. -;; -;; 2020-01-06 Toby S. Cubitt -;; -;; New undo-tree package release. -;; -;; 2014-05-01 Barry O'Reilly -;; -;; Fix bug that caused undo-tree to hang when undoing in region -;; (bug#16377). -;; -;; 2013-12-28 Toby S. Cubitt -;; -;; * undo-tree: Update to version 0.6.5. -;; -;; 2012-12-05 Toby S. Cubitt -;; -;; Update undo-tree to version 0.6.3 -;; -;; * undo-tree.el: Implement lazy tree drawing to significantly speed up -;; visualization of large trees + various more minor improvements. -;; -;; 2012-09-25 Toby S. Cubitt -;; -;; Updated undo-tree package to version 0.5.5. -;; -;; Small bug-fix to avoid hooks triggering an error when trying to save -;; undo history in a buffer where undo is disabled. -;; -;; 2012-09-11 Toby S. Cubitt -;; -;; Updated undo-tree package to version 0.5.4 -;; -;; Bug-fixes and improvements to persistent history storage. -;; -;; 2012-07-18 Toby S. Cubitt -;; -;; Update undo-tree to version 0.5.3 -;; -;; * undo-tree.el: Cope gracefully with undo boundaries being deleted -;; (cf. bug#11774). Allow customization of directory to which undo history -;; is -;; saved. -;; -;; 2012-05-24 Toby S. Cubitt -;; -;; updated undo-tree package to version 0.5.2 -;; -;; * undo-tree.el: add diff view feature in undo-tree visualizer. -;; -;; 2012-05-02 Toby S. Cubitt -;; -;; undo-tree.el: Update package to version 0.4 -;; -;; 2012-04-20 Toby S. Cubitt -;; -;; undo-tree.el: Update package to version 0.3.4 -;; -;; * undo-tree.el (undo-list-pop-changeset): fix pernicious bug causing -;; undo history to be lost. -;; (buffer-undo-tree): set permanent-local property. -;; (undo-tree-enable-undo-in-region): add new customization option allowing -;; undo-in-region to be disabled. -;; -;; 2012-01-26 Toby S. Cubitt -;; -;; undo-tree.el: Fixed copyright attribution and Emacs status. -;; -;; 2012-01-26 Toby S. Cubitt -;; -;; undo-tree.el: Update package to version 0.3.3 -;; -;; 2011-09-17 Stefan Monnier -;; -;; Add undo-tree.el -;; - - - - -(provide 'undo-tree) - -;;; undo-tree.el ends here diff --git a/localelpa/xr-1.14.el b/localelpa/xr-1.14.el deleted file mode 100644 index f80dba24b..000000000 --- a/localelpa/xr-1.14.el +++ /dev/null @@ -1,1371 +0,0 @@ -;;; xr.el --- Convert string regexp to rx notation -*- lexical-binding: t -*- - -;; Copyright (C) 2019 Free Software Foundation, Inc. - -;; Author: Mattias EngdegĂ„rd -;; Version: 1.14 -;; URL: https://github.com/mattiase/xr -;; Keywords: lisp, maint, regexps - -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see . - -;;; Commentary: - -;; This is an inverse companion to the rx package for translating -;; regexps in string form to the rx notation. Its chief uses are: -;; -;; - Migrating existing code to rx form, for better readability and -;; maintainability -;; - Understanding complex regexp strings and finding errors in them -;; -;; Please refer to `rx' for more information about the notation. -;; -;; In addition to Emacs regexps, this package can also parse and -;; find mistakes in skip set strings, which are arguments to -;; `skip-chars-forward' and `skip-chars-backward'. -;; -;; The exported functions are: -;; -;; Regexps: -;; `xr' - returns the converted rx expression -;; `xr-pp' - converts to rx and pretty-prints -;; `xr-lint' - finds mistakes in a regexp string -;; -;; Skip sets: -;; `xr-skip-set' - return the converted rx expression -;; `xr-skip-set-pp' - converts to rx and pretty-prints -;; `xr-skip-set-lint' - finds mistakes in a skip set string -;; -;; General: -;; `xr-pp-rx-to-str' - pretty-prints an rx expression to a string -;; -;; Example (regexp found in compile.el): -;; -;; (xr-pp "\\`\\(?:[^^]\\|\\^\\(?: \\*\\|\\[\\)\\)") -;; => -;; (seq bos -;; (or (not (any "^")) -;; (seq "^" -;; (or " *" "[")))) -;; -;; The rx notation admits many synonyms. The user is encouraged to -;; edit the result for maximum readability, consistency and personal -;; preference when replacing existing regexps in elisp code. -;; -;; Related work: -;; -;; The `lex' package, a lexical analyser generator, provides the -;; `lex-parse-re' function which translates regexps to rx, but does -;; not attempt to handle all the edge cases of Elisp's regexp syntax -;; or pretty-print the result. -;; -;; The `pcre2el' package, a regexp syntax converter and interactive -;; regexp explainer, could also be used for translating regexps to rx. -;; `xr' is narrower in scope but more accurate for the purpose of -;; parsing Emacs regexps and printing the results in rx form. -;; -;; Neither of these packages parse skip-set strings or provide -;; mistake-finding functions. - -;;; News: - -;; Version 1.14: -;; - Warn about repetition of grouped repetition -;; Version 1.13: -;; - More robust pretty-printing, especially for characters -;; - Generate (category CHAR) for unknown categories -;; Version 1.12: -;; - Warn about branch subsumption, like [AB]\|A -;; Version 1.11: -;; - Warn about repetition of empty-matching expressions -;; - Detect `-' not first or last in char alternatives or skip-sets -;; - Stronger ad-hoc [...] check in skip-sets -;; Version 1.10: -;; - Warn about [[:class:]] in skip-sets -;; - Warn about two-character ranges like [*-+] in regexps -;; Version 1.9: -;; - Don't complain about [z-a] and [^z-a] specifically -;; - Improved skip set checks -;; Version 1.8: -;; - Improved skip set checks -;; Version 1.7: -;; - Parse skip-sets, adding `xr-skip-set', `xr-skip-set-pp' and -;; `xr-skip-set-lint' -;; - Ad-hoc check for misplaced `]' in regexps -;; Version 1.6: -;; - Detect duplicated branches like A\|A -;; Version 1.5: -;; - Add dialect option to `xr' and `xr-pp' -;; - Negative empty sets, [^z-a], now become `anything' -;; Version 1.4: -;; - Detect overlap in character alternatives -;; Version 1.3: -;; - Improved xr-lint warnings -;; Version 1.2: -;; - `xr-lint' added - -;;; Code: - -(require 'rx) -(require 'cl-lib) - -(defun xr--report (warnings position message) - "Add the report MESSAGE at POSITION to WARNINGS." - (when warnings - (push (cons (1- position) message) (car warnings)))) - -(defun xr--parse-char-alt (negated warnings) - (let ((start-pos (point)) - (intervals nil) - (classes nil)) - (cond - ;; Initial ]-x range - ((looking-at (rx "]-" (not (any "]")))) - (let ((end (aref (match-string 0) 2))) - (if (>= end ?\]) - (push (vector ?\] end (point)) intervals) - (xr--report warnings (point) - (format "Reversed range `%s' matches nothing" - (xr--escape-string (match-string 0) nil)))) - (when (eq end ?^) - (xr--report warnings (point) - (format "Two-character range `%s'" - (xr--escape-string (match-string 0) nil))))) - (goto-char (match-end 0))) - ;; Initial ] - ((looking-at "]") - (push (vector ?\] ?\] (point)) intervals) - (forward-char 1))) - - (while (not (looking-at "]")) - (cond - ;; character class - ((looking-at (rx "[:" (group (*? anything)) ":]")) - (let ((sym (intern (match-string 1)))) - (unless (memq sym - '(ascii alnum alpha blank cntrl digit graph - lower multibyte nonascii print punct space - unibyte upper word xdigit)) - (error "No character class `%s'" (match-string 0))) - (if (memq sym classes) - (xr--report warnings (point) - (format "Duplicated character class `[:%s:]'" sym)) - (push sym classes)) - (goto-char (match-end 0)))) - ;; character range - ((looking-at (rx (group (not (any "]"))) "-" (group (not (any "]"))))) - (let ((start (string-to-char (match-string 1))) - (end (string-to-char (match-string 2)))) - (cond - ((<= start end) - (push (vector start end (point)) intervals)) - ;; It's unlikely that anyone writes z-a by mistake; don't complain. - ((and (eq start ?z) (eq end ?a))) - (t - (xr--report warnings (point) - (format "Reversed range `%s' matches nothing" - (xr--escape-string (match-string 0) nil))))) - ;; Suppress warnings about ranges between adjacent digits, - ;; like [0-1], as they are common and harmless. - (when (and (= end (1+ start)) (not (<= ?0 start end ?9))) - (xr--report warnings (point) - (format "Two-character range `%s'" - (xr--escape-string (match-string 0) nil)))) - (goto-char (match-end 0)))) - ((looking-at (rx eos)) - (error "Unterminated character alternative")) - ;; plain character (including ^ or -) - (t - (let ((ch (following-char))) - (when (and (eq ch ?\[) - ;; Ad-hoc pattern attempting to catch mistakes - ;; on the form [...[...]...] - ;; where we are ^here - (looking-at (rx "[" - (zero-or-more (not (any "[]"))) - "]" - (zero-or-more (not (any "[]"))) - (not (any "[\\")) - "]")) - ;; Only if the alternative didn't start with ] - (not (and intervals - (eq (aref (car (last intervals)) 0) ?\])))) - (xr--report warnings (point) - "Suspect `[' in char alternative")) - (when (and (looking-at (rx "-" (not (any "]")))) - (> (point) start-pos)) - (xr--report - warnings (point) - "Literal `-' not first or last in character alternative")) - (push (vector ch ch (point)) intervals)) - (forward-char 1)))) - - (forward-char 1) ; eat the ] - - ;; Detect duplicates and overlapping intervals. - (let* ((sorted - (sort (nreverse intervals) - (lambda (a b) (< (aref a 0) (aref b 0))))) - (s sorted)) - (while (cdr s) - (let ((this (car s)) - (next (cadr s))) - (when (>= (aref this 1) (aref next 0)) - (let ((message - (cond - ;; Duplicate character: drop it and warn. - ((and (eq (aref this 0) (aref this 1)) - (eq (aref next 0) (aref next 1))) - (setcdr s (cddr s)) - (format "Duplicated `%c' inside character alternative" - (aref this 0))) - ;; Duplicate range: drop it and warn. - ((and (eq (aref this 0) (aref next 0)) - (eq (aref this 1) (aref next 1))) - (setcdr s (cddr s)) - (format "Duplicated `%c-%c' inside character alternative" - (aref this 0) (aref this 1))) - ;; Character in range: drop it and warn. - ((eq (aref this 0) (aref this 1)) - (setcar s next) - (setcdr s (cddr s)) - (format "Character `%c' included in range `%c-%c'" - (aref this 0) (aref next 0) (aref next 1))) - ;; Same but other way around. - ((eq (aref next 0) (aref next 1)) - (setcdr s (cddr s)) - (format "Character `%c' included in range `%c-%c'" - (aref next 0) (aref this 0) (aref this 1))) - ;; Overlapping ranges: merge and warn. - (t - (let ((this-end (aref this 1))) - (aset this 1 (max (aref this 1) (aref next 1))) - (setcdr s (cddr s)) - (format "Ranges `%c-%c' and `%c-%c' overlap" - (aref this 0) this-end - (aref next 0) (aref next 1))))))) - (xr--report warnings (max (aref this 2) (aref next 2)) - (xr--escape-string message nil))))) - (setq s (cdr s))) - - ;; Gather ranges and single characters separately. - ;; We make no attempts at merging adjacent intervals/characters, - ;; nor at splitting short intervals such as "a-b"; if the user - ;; wrote it that way, there was probably a reason for it. - (let ((ranges nil) - (chars nil)) - (dolist (interv sorted) - (if (eq (aref interv 0) (aref interv 1)) - (push (aref interv 0) chars) - (push (string (aref interv 0) ?- (aref interv 1)) - ranges))) - - ;; Note that we return (any) for non-negated empty sets, - ;; such as [z-a]. (any) is not accepted by rx but at least we - ;; are not hiding potential bugs from the user. - (cond - ;; Negated empty set, like [^z-a]: anything. - ((and negated - (null chars) - (null ranges) - (null classes)) - 'anything) - ;; Non-negated single-char set, like [$]: make a string. - ((and (= (length chars) 1) - (not negated) - (null ranges) - (null classes)) - (string (car chars))) - ;; Single named class, like [[:space:]]: use the symbol. - ((and (= (length classes) 1) - (null chars) - (null ranges)) - (if negated - (list 'not (car classes)) - (car classes))) - ;; Anything else: produce (any ...) - (t - ;; Put dash last of all single characters. - (when (memq ?- chars) - (setq chars (cons ?- (delq ?- chars)))) - (let* ((set (cons 'any - (append - (and ranges - (list (apply #'concat (nreverse ranges)))) - (and chars - (list (apply #'string (nreverse chars)))) - (nreverse classes))))) - (if negated - (list 'not set) - set)))))))) - -(defun xr--rev-join-seq (sequence) - "Reverse a sequence, flatten any (seq ...) inside, and concatenate -adjacent strings." - (let ((result nil)) - (while sequence - (let ((elem (car sequence)) - (rest (cdr sequence))) - (cond ((and (consp elem) (eq (car elem) 'seq)) - (setq sequence (append (reverse (cdr elem)) rest))) - ((and (stringp elem) (stringp (car result))) - (setq result (cons (concat elem (car result)) (cdr result))) - (setq sequence rest)) - (t - (setq result (cons elem result)) - (setq sequence rest))))) - result)) - -(defun xr--char-category (negated category-code) - (let* ((sym (assq category-code - '((?\s . space-for-indent) - (?. . base) - (?0 . consonant) - (?1 . base-vowel) - (?2 . upper-diacritical-mark) - (?3 . lower-diacritical-mark) - (?4 . tone-mark) - (?5 . symbol) - (?6 . digit) - (?7 . vowel-modifying-diacritical-mark) - (?8 . vowel-sign) - (?9 . semivowel-lower) - (?< . not-at-end-of-line) - (?> . not-at-beginning-of-line) - (?A . alpha-numeric-two-byte) - (?C . chinese-two-byte) - (?G . greek-two-byte) - (?H . japanese-hiragana-two-byte) - (?I . indian-two-byte) - (?K . japanese-katakana-two-byte) - (?L . strong-left-to-right) - (?N . korean-hangul-two-byte) - (?R . strong-right-to-left) - (?Y . cyrillic-two-byte) - (?^ . combining-diacritic) - (?a . ascii) - (?b . arabic) - (?c . chinese) - (?e . ethiopic) - (?g . greek) - (?h . korean) - (?i . indian) - (?j . japanese) - (?k . japanese-katakana) - (?l . latin) - (?o . lao) - (?q . tibetan) - (?r . japanese-roman) - (?t . thai) - (?v . vietnamese) - (?w . hebrew) - (?y . cyrillic) - (?| . can-break)))) - (item (list 'category (if sym (cdr sym) category-code)))) - (if negated (list 'not item) item))) - -(defun xr--char-syntax (negated syntax-code) - (let ((sym (assq syntax-code - '((?- . whitespace) - (?\s . whitespace) - (?. . punctuation) - (?w . word) - (?W . word) ; undocumented - (?_ . symbol) - (?\( . open-parenthesis) - (?\) . close-parenthesis) - (?' . expression-prefix) - (?\" . string-quote) - (?$ . paired-delimiter) - (?\\ . escape) - (?/ . character-quote) - (?< . comment-start) - (?> . comment-end) - (?| . string-delimiter) - (?! . comment-delimiter))))) - (when (not sym) - (error "Unknown syntax code `%s'" - (xr--escape-string (char-to-string syntax-code) nil))) - (let ((item (list 'syntax (cdr sym)))) - (if negated (list 'not item) item)))) - -(defun xr--postfix (operator operand) - ;; We use verbose names for the common *, + and ? operators for readability, - ;; even though these names are affected by the rx-greedy-flag. - ;; For the (less common) non-greedy operators we might want to - ;; consider using minimal-match/maximal-match instead, but - ;; this would complicate the implementation. - (let* ((sym (cdr (assoc operator '(("*" . zero-or-more) - ("+" . one-or-more) - ("?" . opt) - ("*?" . *?) - ("+?" . +?) - ("??" . ??))))) - ;; Simplify when the operand is (seq ...) - (body (if (and (listp operand) (eq (car operand) 'seq)) - (cdr operand) - (list operand)))) - (cons sym body))) - -(defun xr--repeat (lower upper operand) - "Apply a repetition of {LOWER,UPPER} to OPERAND. -UPPER may be nil, meaning infinity." - (when (and upper (> lower upper)) - (error "Invalid repetition interval")) - ;; rx does not accept (= 0 ...) or (>= 0 ...), so we use - ;; (repeat 0 0 ...) and (zero-or-more ...), respectively. - ;; Note that we cannot just delete the operand if LOWER=UPPER=0, - ;; since doing so may upset the group numbering. - (let* ((operator (cond ((null upper) - (if (zerop lower) - '(zero-or-more) - (list '>= lower))) - ((and (= lower upper) (> lower 0)) - (list '= lower)) - (t - (list 'repeat lower upper)))) - ;; Simplify when the operand is (seq ...). - (body (if (and (listp operand) (eq (car operand) 'seq)) - (cdr operand) - (list operand)))) - (append operator body))) - -(defconst xr--zero-width-assertions - '(bol eol bos eos bow eow word-boundary not-word-boundary - symbol-start symbol-end point)) - -(defun xr--matches-empty-p (rx) - "Whether RX can match the empty string regardless of context." - (pcase rx - (`(,(or 'seq 'one-or-more 'group) . ,body) - (cl-every #'xr--matches-empty-p body)) - (`(or . ,body) - (cl-some #'xr--matches-empty-p body)) - (`(group-n ,_ . ,body) - (cl-every #'xr--matches-empty-p body)) - (`(,(or 'opt 'zero-or-more) . ,_) - t) - (`(repeat ,from ,_ . ,body) - (or (= from 0) - (cl-every #'xr--matches-empty-p body))) - (`(,(or '= '>=) ,_ . ,body) - (cl-every #'xr--matches-empty-p body)) - ("" t))) - -(defun xr--parse-seq (warnings) - (let ((sequence nil)) ; reversed - (while (not (looking-at (rx (or "\\|" "\\)" eos)))) - (cond - ;; ^ - only special at beginning of sequence - ((looking-at (rx "^")) - (forward-char 1) - (if (null sequence) - (push 'bol sequence) - (xr--report warnings (match-beginning 0) "Unescaped literal `^'") - (push "^" sequence))) - - ;; $ - only special at end of sequence - ((looking-at (rx "$")) - (forward-char 1) - (if (looking-at (rx (or "\\|" "\\)" eos))) - (push 'eol sequence) - (xr--report warnings (match-beginning 0) "Unescaped literal `$'") - (push "$" sequence))) - - ;; * ? + (and non-greedy variants) - ;; - not special at beginning of sequence or after ^ - ((looking-at (rx (group (any "*?+")) (opt "?"))) - (if (and sequence - (not (and (eq (car sequence) 'bol) (eq (preceding-char) ?^)))) - (let ((operator (match-string 0)) - (operand (car sequence))) - (when warnings - (cond - ;; (* (* X)), for any repetitions * - ((and (consp operand) - (memq (car operand) - '(opt zero-or-more one-or-more +? *? ??))) - (xr--report warnings (match-beginning 0) - "Repetition of repetition")) - ;; (* (group (* X))), for any repetitions * - ((and (consp operand) - (eq (car operand) 'group) - (null (cddr operand)) - (let ((inner (cadr operand))) - (and (consp inner) - (memq (car inner) - '(opt zero-or-more one-or-more +? *? ??)) - ;; Except (? (group (+ X))), since that may - ;; be legitimate. - (not (and (equal operator "?") - (memq (car inner) - '(one-or-more +?))))))) - (xr--report warnings (match-beginning 0) - "Repetition of repetition")) - ((memq operand xr--zero-width-assertions) - (xr--report warnings (match-beginning 0) - "Repetition of zero-width assertion")) - ((and (xr--matches-empty-p operand) - ;; Rejecting repetition of the empty string - ;; suppresses some false positives. - (not (equal operand ""))) - (xr--report - warnings (match-beginning 0) - "Repetition of expression matching an empty string")))) - (goto-char (match-end 0)) - (setq sequence (cons (xr--postfix operator operand) - (cdr sequence)))) - (let ((literal (match-string 1))) - (goto-char (match-end 1)) - (xr--report warnings (match-beginning 0) - (format "Unescaped literal `%s'" literal)) - (push literal sequence)))) - - ;; \{..\} - not special at beginning of sequence or after ^ - ((and (looking-at (rx "\\{")) - sequence - (not (and (eq (car sequence) 'bol) (eq (preceding-char) ?^)))) - (forward-char 2) - (let ((operand (car sequence))) - (when warnings - (cond - ;; (** N M (* X)), for any repetition * - ((and (consp operand) - (memq (car operand) - '(opt zero-or-more one-or-more +? *? ??))) - (xr--report warnings (match-beginning 0) - "Repetition of repetition")) - ;; (** N M (group (* X))), for any repetition * - ((and (consp operand) - (eq (car operand) 'group) - (null (cddr operand)) - (let ((inner (cadr operand))) - (and (consp inner) - (memq (car inner) - '(opt zero-or-more one-or-more +? *? ??))))) - (xr--report warnings (match-beginning 0) - "Repetition of repetition")) - ((memq operand xr--zero-width-assertions) - (xr--report warnings (match-beginning 0) - "Repetition of zero-width assertion")) - ((and (xr--matches-empty-p operand) - ;; Rejecting repetition of the empty string - ;; suppresses some false positives. - (not (equal operand ""))) - (xr--report - warnings (match-beginning 0) - "Repetition of expression matching an empty string")))) - (if (looking-at (rx (opt (group (one-or-more digit))) - (opt (group ",") - (opt (group (one-or-more digit)))) - "\\}")) - (let ((lower (if (match-string 1) - (string-to-number (match-string 1)) - 0)) - (comma (match-string 2)) - (upper (and (match-string 3) - (string-to-number (match-string 3))))) - (unless (or (match-beginning 1) (match-string 3)) - (xr--report warnings (- (match-beginning 0) 2) - (if comma - "Uncounted repetition" - "Implicit zero repetition"))) - (goto-char (match-end 0)) - (setq sequence (cons (xr--repeat lower - (if comma upper lower) - operand) - (cdr sequence)))) - (error "Invalid \\{\\} syntax")))) - - ;; nonspecial character - ((looking-at (rx (not (any "\\.[")))) - (forward-char 1) - (push (match-string 0) sequence)) - - ;; character alternative - ((looking-at (rx "[" (opt (group "^")))) - (goto-char (match-end 0)) - (let ((negated (match-string 1))) - (push (xr--parse-char-alt negated warnings) sequence))) - - ;; group - ((looking-at (rx "\\(" (opt (group "?") - (opt (opt (group (any "1-9") - (zero-or-more digit))) - (group ":"))))) - (let ((question (match-string 1)) - (number (match-string 2)) - (colon (match-string 3))) - (when (and question (not colon)) - (error "Invalid \\(? syntax")) - (goto-char (match-end 0)) - (let* ((group (xr--parse-alt warnings)) - ;; simplify - group has an implicit seq - (operand (if (and (listp group) (eq (car group) 'seq)) - (cdr group) - (list group)))) - (when (not (looking-at (rx "\\)"))) - (error "Missing \\)")) - (forward-char 2) - (let ((item (cond (number ; numbered group - (append (list 'group-n (string-to-number number)) - operand)) - (question ; shy group - group) - (t ; plain group - (cons 'group operand))))) - (push item sequence))))) - - ;; back-reference - ((looking-at (rx "\\" (group (any "1-9")))) - (forward-char 2) - (push (list 'backref (string-to-number (match-string 1))) - sequence)) - - ;; various simple substitutions - ((looking-at (rx (or "." "\\w" "\\W" "\\`" "\\'" "\\=" - "\\b" "\\B" "\\<" "\\>"))) - (goto-char (match-end 0)) - (let ((sym (cdr (assoc - (match-string 0) - '(("." . nonl) - ("\\w" . wordchar) ("\\W" . not-wordchar) - ("\\`" . bos) ("\\'" . eos) - ("\\=" . point) - ("\\b" . word-boundary) ("\\B" . not-word-boundary) - ("\\<" . bow) ("\\>" . eow)))))) - (push sym sequence))) - - ;; symbol-start, symbol-end - ((looking-at (rx "\\_" (opt (group (any "<>"))))) - (let ((arg (match-string 1))) - (unless arg - (error "Invalid \\_ sequence")) - (forward-char 3) - (push (if (string-equal arg "<") 'symbol-start 'symbol-end) - sequence))) - - ;; character syntax - ((looking-at (rx "\\" (group (any "sS")) (opt (group anything)))) - (let ((negated (string-equal (match-string 1) "S")) - (syntax-code (match-string 2))) - (unless syntax-code - (error "Incomplete \\%s sequence" (match-string 1))) - (goto-char (match-end 0)) - (push (xr--char-syntax negated (string-to-char syntax-code)) - sequence))) - - ;; character categories - ((looking-at (rx "\\" (group (any "cC")) (opt (group anything)))) - (let ((negated (string-equal (match-string 1) "C")) - (category-code (match-string 2))) - (unless category-code - (error "Incomplete \\%s sequence" (match-string 1))) - (goto-char (match-end 0)) - (push (xr--char-category negated (string-to-char category-code)) - sequence))) - - ;; Escaped character. Only \*+?.^$[ really need escaping, but we accept - ;; any not otherwise handled character after the backslash since - ;; such sequences are found in the wild. - ((looking-at (rx "\\" (group (or (any "\\*+?.^$[]") - (group anything))))) - (forward-char 2) - (push (match-string 1) sequence) - (when (match-beginning 2) - ;; Note that we do not warn about \\], since the symmetry with \\[ - ;; makes it unlikely to be a serious error. - (xr--report warnings (match-beginning 0) - (format "Escaped non-special character `%s'" - (xr--escape-string (match-string 2) nil))))) - - (t (error "Backslash at end of regexp")))) - - (let ((item-seq (xr--rev-join-seq sequence))) - (cond ((null item-seq) - "") - ((null (cdr item-seq)) - (car item-seq)) - (t - (cons 'seq item-seq)))))) - -(defun xr--range-string-to-items (str) - "Convert a string of ranges to a list of pairs of their endpoints." - (let ((len (length str)) - (ranges nil) - (i 0)) - (while (< i len) - (push (cons (aref str i) (aref str (+ i 2))) - ranges) - (setq i (+ i 3))) - ranges)) - -(defun xr--any-arg-to-items (arg) - "Convert an `any' argument to a list of characters, ranges (as pairs), -and classes (symbols)." - ;; We know (since we built it) that x is either a symbol or - ;; a string, and that the string does not mix ranges and chars. - (cond ((symbolp arg) (list arg)) - ((and (>= (length arg) 3) - (eq (aref arg 1) ?-)) - (xr--range-string-to-items arg)) - (t (string-to-list arg)))) - -(defun xr--any-item-superset-p (a b) - "Whether A is a superset of B, both being `any' items: a character, -a range (pair of chars), or a class (symbol)." - (cond - ((symbolp a) - (cond ((symbolp b) (eq a b)) - ((eq b ?\n) - (memq a '(alnum alpha blank digit graph - lower multibyte nonascii print punct space - upper word xdigit))))) - ((consp a) - (or (and (characterp b) - (<= (car a) b (cdr a))) - (and (consp b) - (<= (car a) (car b) (cdr b) (cdr a))))) - (t - (and (characterp b) (eq a b))))) - -(defun xr--any-item-may-intersect-p (a b) - "Whether A intersects B, both being `any' items: a character, -a range (pair of chars), or a class (symbol). If in doubt, return t." - (cond - ((symbolp a) - (cond ((eq b ?\n) - (not (memq a '(alnum alpha blank digit graph - lower multibyte nonascii print punct space - upper word xdigit)))) - (t t))) - ((consp a) - (or (and (characterp b) - (<= (car a) b (cdr a))) - (and (consp b) - (<= (car a) (cdr b)) - (<= (car b) (cdr a))) - (symbolp b))) - ;; Now a must be a character. - ((characterp b) (eq a b)) - (t (xr--any-item-may-intersect-p b a)))) - -(defun xr--char-superset-of-char-set-p (a-sets negated b-sets) - "Whether A-SETS, possibly NEGATED, is a superset of B-SETS. -A-SETS and B-SETS are arguments to `any'." - (let ((a-items (mapcan #'xr--any-arg-to-items a-sets)) - (b-items (mapcan #'xr--any-arg-to-items b-sets))) - (cl-every (lambda (b-item) - (if negated - (not (cl-some - (lambda (a-item) - (xr--any-item-may-intersect-p b-item a-item)) - a-items)) - (cl-some (lambda (a-item) - (xr--any-item-superset-p a-item b-item)) - a-items))) - b-items))) - -(defun xr--char-superset-of-rx-p (sets negated rx) - "Whether SETS, possibly NEGATED, is a superset of RX." - (pcase rx - (`(any . ,b-sets) - (xr--char-superset-of-char-set-p sets negated b-sets)) - (`(not (any . ,b-sets)) - (and negated - (xr--char-superset-of-char-set-p b-sets nil sets))) - ((or 'ascii 'alnum 'alpha 'blank 'cntrl 'digit 'graph - 'lower 'multibyte 'nonascii 'print 'punct 'space - 'unibyte 'upper 'word 'xdigit) - (xr--char-superset-of-char-set-p sets negated `(any ,rx))) - ((pred stringp) - (and (= (length rx) 1) - (xr--char-superset-of-char-set-p sets negated (list rx)))))) - -(defun xr--single-non-newline-char-p (rx) - "Whether RX only matches single characters none of which is newline." - (pcase rx - ((or 'nonl 'wordchar) t) - (`(category ,_) t) - (`(syntax ,s) (not (eq s ?>))) ; comment-end often matches newline - (_ (xr--char-superset-of-rx-p '("\n") t rx)))) - -(defun xr--syntax-superset-of-rx-p (syntax negated rx) - "Whether SYNTAX, possibly NEGATED, is a superset of RX." - ;; Syntax tables vary, but we make a (quite conservative) guess. - (let* ((always-set - ;; Characters we think always will be in the syntax set. - '((whitespace " \t") - (word "A-Za-z0-9") - (open-parenthesis "([") - (close-parenthesis "])"))) - (never-set - ;; Characters we think never will be in the syntax set. - '((whitespace "!-~") - (punctuation "A-Za-z0-9") - (open-parenthesis "\x00- A-Za-z0-9") - (close-parenthesis "\x00- A-Za-z0-9"))) - (set (assq syntax (if negated never-set always-set)))) - (and set - (xr--char-superset-of-rx-p (cdr set) nil rx)))) - -(defun xr--string-to-chars (str) - (mapcar #'char-to-string (string-to-list str))) - -(defun xr--expand-strings (rx) - "If RX is a string or a seq of strings, convert them to seqs of -single-character strings." - (cond ((consp rx) - (if (eq (car rx) 'seq) - (cons 'seq (mapcan (lambda (x) - (if (and (stringp x) - (> (length x) 1)) - (xr--string-to-chars x) - (list x))) - (cdr rx))) - rx)) - ((and (stringp rx) - (> (length rx) 1)) - (cons 'seq (xr--string-to-chars rx))) - (t rx))) - -(defun xr--superset-seq-p (a b) - "Whether A matches all that B matches, both lists of expressions." - (while (and a b (xr--superset-p (car a) (car b))) - (setq a (cdr a)) - (setq b (cdr b))) - (and (not b) - (or (not a) - (xr--matches-empty-p (cons 'seq a))))) - -(defun xr--make-seq (body) - (if (> (length body) 1) - (cons 'seq body) - (car body))) - -(defun xr--superset-p (a b) - "Whether A matches all that B matches." - (setq a (xr--expand-strings a)) - (setq b (xr--expand-strings b)) - - (pcase b - (`(or . ,b-body) - (cl-every (lambda (b-expr) (xr--superset-p a b-expr)) b-body)) - (_ - (pcase a - (`(any . ,sets) - (xr--char-superset-of-rx-p sets nil b)) - (`(not (any . ,sets)) - (xr--char-superset-of-rx-p sets t b)) - ('nonl (xr--single-non-newline-char-p b)) - - (`(seq . ,a-body) - (pcase b - (`(seq . ,b-body) - (xr--superset-seq-p a-body b-body)) - (_ - (xr--superset-seq-p a-body (list b))))) - (`(or . ,a-body) - (cl-some (lambda (a-expr) (xr--superset-p a-expr b)) a-body)) - - (`(zero-or-more . ,a-body) - (pcase b - (`(,(or 'opt 'zero-or-more 'one-or-more) . ,b-body) - (xr--superset-p (xr--make-seq a-body) (xr--make-seq b-body))) - (_ (xr--superset-p (xr--make-seq a-body) b)))) - (`(one-or-more . ,a-body) - (pcase b - (`(one-or-more . ,b-body) - (xr--superset-p (xr--make-seq a-body) (xr--make-seq b-body))) - (_ (xr--superset-p (xr--make-seq a-body) b)))) - (`(opt . ,a-body) - (pcase b - (`(opt . ,b-body) - (xr--superset-p (xr--make-seq a-body) (xr--make-seq b-body))) - (_ (xr--superset-p (xr--make-seq a-body) b)))) - (`(repeat ,lo ,_ . ,a-body) - (if (<= lo 1) - (xr--superset-p (xr--make-seq a-body) b) - (equal a b))) - - ;; We do not expand through groups on the subset (b) side to - ;; avoid false positives; "\\(a\\)\\|." should be without warning. - (`(group . ,body) - (xr--superset-p (xr--make-seq body) b)) - (`(group-n ,_ . ,body) - (xr--superset-p (xr--make-seq body) b)) - - (`(syntax ,syn) - (or (equal a b) (xr--syntax-superset-of-rx-p syn nil b))) - (`(not (syntax ,syn)) - (or (equal a b) (xr--syntax-superset-of-rx-p syn t b))) - - ((or `(category ,_) `(not (category ,_))) - (or (equal a b) - (and (stringp b) - (string-match-p (rx-to-string a) b)))) - - (_ (equal a b)))))) - -(defun xr--parse-alt (warnings) - (let ((alternatives nil)) ; reversed - (push (xr--parse-seq warnings) alternatives) - (while (not (looking-at (rx (or "\\)" eos)))) - (forward-char 2) ; skip \| - (let ((pos (point)) - (seq (xr--parse-seq warnings))) - (when warnings - (cond - ((member seq alternatives) - (xr--report warnings pos "Duplicated alternative branch")) - ((cl-some (lambda (branch) (xr--superset-p seq branch)) - alternatives) - (xr--report warnings pos - "Branch matches superset of a previous branch")) - ((cl-some (lambda (branch) (xr--superset-p branch seq)) - alternatives) - (xr--report warnings pos - "Branch matches subset of a previous branch")))) - (push seq alternatives))) - (if (cdr alternatives) - ;; Simplify (or nonl "\n") to anything - (if (or (equal alternatives '(nonl "\n")) - (equal alternatives '("\n" nonl))) - 'anything - (cons 'or (reverse alternatives))) - (car alternatives)))) - -(defun xr--parse (re-string warnings) - (with-temp-buffer - (set-buffer-multibyte t) - (insert re-string) - (goto-char (point-min)) - (let* ((case-fold-search nil) - (rx (xr--parse-alt warnings))) - (when (looking-at (rx "\\)")) - (error "Unbalanced \\)")) - rx))) - -;; Grammar for skip-set strings: -;; -;; skip-set ::= `^'? item* dangling? -;; item ::= range | single -;; range ::= single `-' endpoint -;; single ::= {any char but `\'} -;; | `\' {any char} -;; endpoint ::= single | `\' -;; dangling ::= `\' -;; -;; Ambiguities in the above are resolved greedily left-to-right. - -(defun xr--parse-skip-set-buffer (warnings) - - ;; An ad-hoc check, but one that catches lots of mistakes. - (when (and (looking-at (rx "[" (one-or-more anything) "]" - (opt (any "+" "*" "?") - (opt "?")) - eos)) - (not (looking-at (rx "[:" (one-or-more anything) ":]" eos)))) - (xr--report warnings (point) "Suspect skip set framed in `[...]'")) - - (let ((negated (looking-at (rx "^"))) - (start-pos (point)) - (ranges nil) - (classes nil)) - (when negated - (forward-char 1) - (setq start-pos (point))) - (while (not (eobp)) - (cond - ((looking-at (rx "[:" (group (*? anything)) ":]")) - (let ((sym (intern (match-string 1)))) - (unless (memq sym - '(ascii alnum alpha blank cntrl digit graph - lower multibyte nonascii print punct space - unibyte upper word xdigit)) - (error "No character class `%s'" (match-string 0))) - ;; Another useful ad-hoc check. - (when (and (eq (char-before) ?\[) - (eq (char-after (match-end 0)) ?\])) - (xr--report warnings (1- (point)) - "Suspect character class framed in `[...]'")) - (when (memq sym classes) - (xr--report warnings (point) - (format "Duplicated character class `%s'" - (match-string 0)))) - (push sym classes))) - - ((looking-at (rx (or (seq "\\" (group anything)) - (group (not (any "\\")))) - (opt "-" - (or (seq "\\" (group anything)) - (group anything))))) - (let ((start (string-to-char (or (match-string 1) - (match-string 2)))) - (end (or (and (match-beginning 3) - (string-to-char (match-string 3))) - (and (match-beginning 4) - (string-to-char (match-string 4)))))) - (when (and (match-beginning 1) - (not (memq start '(?^ ?- ?\\)))) - (xr--report warnings (point) - (xr--escape-string - (format "Unnecessarily escaped `%c'" start) nil))) - (when (and (match-beginning 3) - (not (memq end '(?^ ?- ?\\)))) - (xr--report warnings (1- (match-beginning 3)) - (xr--escape-string - (format "Unnecessarily escaped `%c'" end) nil))) - (when (and (eq start ?-) - (not end) - (match-beginning 2) - (< start-pos (point) (1- (point-max)))) - (xr--report warnings (point) - "Literal `-' not first or last")) - (if (and end (> start end)) - (xr--report warnings (point) - (xr--escape-string - (format "Reversed range `%c-%c'" start end) nil)) - (cond - ((eq start end) - (xr--report warnings (point) - (xr--escape-string - (format "Single-element range `%c-%c'" start end) - nil))) - ((eq (1+ start) end) - (xr--report warnings (point) - (xr--escape-string - (format "Two-element range `%c-%c'" start end) - nil)))) - (let ((tail ranges)) - (while tail - (let ((range (car tail))) - (if (and (<= (car range) (or end start)) - (<= start (cdr range))) - (let ((msg - (cond - ((and end (< start end) - (< (car range) (cdr range))) - (format "Ranges `%c-%c' and `%c-%c' overlap" - (car range) (cdr range) start end)) - ((and end (< start end)) - (format "Range `%c-%c' includes character `%c'" - start end (car range))) - ((< (car range) (cdr range)) - (format - "Character `%c' included in range `%c-%c'" - start (car range) (cdr range))) - (t - (format "Duplicated character `%c'" - start))))) - (xr--report warnings (point) - (xr--escape-string msg nil)) - ;; Expand previous interval to include this range. - (setcar range (min (car range) start)) - (setcdr range (max (cdr range) (or end start))) - (setq start nil) - (setq tail nil)) - (setq tail (cdr tail)))))) - (when start - (push (cons start (or end start)) ranges))))) - - ((looking-at (rx "\\" eos)) - (xr--report warnings (point) - "Stray `\\' at end of string"))) - - (goto-char (match-end 0))) - - (when (and (null ranges) (null classes)) - (xr--report warnings (point-min) - (if negated - "Negated empty set matches anything" - "Empty set matches nothing"))) - - (cond - ;; Single non-negated character, like "-": make a string. - ((and (not negated) - (null classes) - (= (length ranges) 1) - (eq (caar ranges) (cdar ranges))) - (regexp-quote (char-to-string (caar ranges)))) - ;; Negated empty set, like "^": anything. - ((and negated - (null classes) - (null ranges)) - 'anything) - ;; Single named class, like "[:nonascii:]": use the symbol. - ((and (= (length classes) 1) - (null ranges)) - (if negated - (list 'not (car classes)) - (car classes))) - ;; Anything else: produce (any ...) - (t - (let ((intervals nil) - (chars nil)) - (dolist (range ranges) - (if (eq (car range) (cdr range)) - (push (car range) chars) - (push (string (car range) ?- (cdr range)) intervals))) - ;; Put a single `-' last. - (when (memq ?- chars) - (setq chars (append (delq ?- chars) (list ?-)))) - (let ((set (cons 'any - (append - (and intervals - (list (apply #'concat intervals))) - (and chars - (list (apply #'string chars))) - (nreverse classes))))) - (if negated - (list 'not set) - set))))))) - -(defun xr--parse-skip-set (skip-string warnings) - (with-temp-buffer - (set-buffer-multibyte t) - (insert skip-string) - (goto-char (point-min)) - (xr--parse-skip-set-buffer warnings))) - -(defun xr--substitute-keywords (head-alist body-alist rx) - "Substitute keywords in RX using HEAD-ALIST and BODY-ALIST in the -head and body positions, respectively." - (cond - ((symbolp rx) - (or (cdr (assq rx body-alist)) rx)) - ((consp rx) - (cons (or (cdr (assq (car rx) head-alist)) - (car rx)) - (mapcar (lambda (elem) (xr--substitute-keywords - head-alist body-alist elem)) - (cdr rx)))) - (t rx))) - -(defconst xr--keywords - '((medium . nil) - (brief . (((zero-or-more . 0+) - (one-or-more . 1+)) - . nil)) - (terse . (((seq . :) - (or . |) - (any . in) - (zero-or-more . *) - (one-or-more . +) - (opt . ? ) - (repeat . **)) - . nil)) - (verbose . (((opt . zero-or-one)) - . - ((nonl . not-newline) - (bol . line-start) - (eol . line-end) - (bos . string-start) - (eos . string-end) - (bow . word-start) - (eow . word-end))))) - "Alist mapping keyword dialect to (HEAD-ALIST . BODY-ALIST), -or to nil if no translation should take place. -The alists are mapping from the default choice.") - -(defun xr--in-dialect (rx dialect) - (let ((keywords (assq (or dialect 'medium) xr--keywords))) - (unless keywords - (error "Unknown dialect `%S'" dialect)) - (if (cdr keywords) - (xr--substitute-keywords (cadr keywords) (cddr keywords) rx) - rx))) - -;;;###autoload -(defun xr (re-string &optional dialect) - "Convert a regexp string to rx notation; the inverse of `rx'. -Passing the returned value to `rx' (or `rx-to-string') yields a regexp string -equivalent to RE-STRING. DIALECT controls the choice of keywords, -and is one of: -`verbose' -- verbose keywords -`brief' -- short keywords -`terse' -- very short keywords -`medium' or nil -- a compromise (the default)" - (xr--in-dialect (xr--parse re-string nil) dialect)) - -;;;###autoload -(defun xr-skip-set (skip-set-string &optional dialect) - "Convert a skip set string argument to rx notation. -SKIP-SET-STRING is interpreted according to the syntax of -`skip-chars-forward' and `skip-chars-backward' and converted to -a character class on `rx' form. -If desired, `rx' can then be used to convert the result to an -ordinary regexp. -See `xr' for a description of the DIALECT argument." - (xr--in-dialect (xr--parse-skip-set skip-set-string nil) dialect)) - -;;;###autoload -(defun xr-lint (re-string) - "Detect dubious practices and possible mistakes in RE-STRING. -This includes uses of tolerated but discouraged constructs. -Outright regexp syntax violations are signalled as errors. -Return a list of (OFFSET . COMMENT) where COMMENT applies at OFFSET -in RE-STRING." - (let ((warnings (list nil))) - (xr--parse re-string warnings) - (sort (car warnings) #'car-less-than-car))) - -;;;###autoload -(defun xr-skip-set-lint (skip-set-string) - "Detect dubious practices and possible mistakes in SKIP-SET-STRING. -This includes uses of tolerated but discouraged constructs. -Outright syntax violations are signalled as errors. -The argument is interpreted according to the syntax of -`skip-chars-forward' and `skip-chars-backward'. -Return a list of (OFFSET . COMMENT) where COMMENT applies at OFFSET -in SKIP-SET-STRING." - (let ((warnings (list nil))) - (xr--parse-skip-set skip-set-string warnings) - (sort (car warnings) #'car-less-than-car))) - -(defun xr--escape-string (string escape-printable) - "Escape non-printing characters in a string for maximum readability. -If ESCAPE-PRINTABLE, also escape \\ and \", otherwise don't." - (replace-regexp-in-string - "[\x00-\x1f\"\\\x7f\x80-\xff][[:xdigit:]]?" - (lambda (s) - (let* ((c (logand (string-to-char s) #xff)) - (xdigit (substring s 1)) - (transl (assq c - '((?\b . "\\b") - (?\t . "\\t") - (?\n . "\\n") - (?\v . "\\v") - (?\f . "\\f") - (?\r . "\\r") - (?\e . "\\e"))))) - ;; We prefer hex escapes (\xHH) because that is what most users - ;; want today, but use octal (\OOO) if the following character - ;; is a legitimate hex digit. - (concat - (cond (transl (cdr transl)) - ((memq c '(?\\ ?\")) - (if escape-printable (string ?\\ c) (string c))) - ((zerop (length xdigit)) (format "\\x%02x" c)) - (t (format (format "\\%03o" c)))) - xdigit))) - string 'fixedcase 'literal)) - -(defun xr--take (n list) - "The N first elements of LIST." - (butlast list (- (length list) n))) - -(defun xr--rx-list-to-string (rx plain-prefix) - "Print the list `rx' to a string, unformatted. -The first PLAIN-PREFIX elements are formatted using `prin1-to-string'; -the rest with `xr--rx-to-string'." - (concat "(" - (mapconcat #'identity - (append - (mapcar #'prin1-to-string (xr--take plain-prefix rx)) - (mapcar #'xr--rx-to-string (nthcdr plain-prefix rx))) - " ") - ")")) - -(defun xr--rx-to-string (rx) - "Print an rx expression to a string, unformatted." - (cond - ((eq rx '*?) "*?") ; Avoid unnecessary \ in symbol. - ((eq rx '+?) "+?") - ((eq rx '\??) "\\??") - ((stringp rx) (concat "\"" (xr--escape-string rx t) "\"")) - ((characterp rx) - (let ((esc (assq rx '((?\( . ?\() - (?\) . ?\)) - (?\[ . ?\[) - (?\] . ?\]) - (?\\ . ?\\) - (?\; . ?\;) - (?\" . ?\") - (?\s . ?s) - (?\n . ?n) - (?\r . ?r) - (?\t . ?t) - (?\e . ?e) - (?\b . ?b) - (?\f . ?f) - (?\v . ?v))))) - (cond (esc (format "?\\%c" (cdr esc))) - ;; Only base characters are displayed as ?char; this excludes - ;; controls, combining, surrogates, noncharacters etc. - ((aref (char-category-set rx) ?.) (format "?%c" rx)) - (t (format "#x%02x" rx))))) - ((atom rx) (prin1-to-string rx)) - ((nlistp (cdr rx)) - (format "(%s . %s)" - (xr--rx-to-string (car rx)) - (xr--rx-to-string (cdr rx)))) - ((or (eq (car rx) '**) - (and (eq (car rx) 'repeat) (> (length rx) 3))) - ;; First 2 args are integers. - (xr--rx-list-to-string rx 3)) - ((memq (car rx) '(= >= repeat group-n backref)) - ;; First arg is integer. - (xr--rx-list-to-string rx 2)) - (t - ;; Render the space character as ? when first in a list. - ;; Elsewhere, it's a character or integer. - (let ((first (if (eq (car rx) ?\s) - "?" - (xr--rx-to-string (car rx)))) - (rest (mapcar #'xr--rx-to-string (cdr rx)))) - (concat "(" (mapconcat #'identity (cons first rest) " ") ")"))))) - -(defun xr-pp-rx-to-str (rx) - "Pretty-print the regexp RX (in rx notation) to a string. -It does a slightly better job than standard `pp' for rx purposes." - (with-temp-buffer - (insert (xr--rx-to-string rx) "\n") - (pp-buffer) - - ;; Remove the line break after short operator names for - ;; readability and compactness. - (goto-char (point-min)) - (while (re-search-forward - (rx "(" (** 1 4 (any "a-z0-9" "+?:|*=>")) - (group "\n" (zero-or-more blank))) - nil t) - (replace-match " " t t nil 1)) - - ;; Reindent the buffer in case line breaks have been removed. - (goto-char (point-min)) - (indent-sexp) - - (buffer-string))) - -;;;###autoload -(defun xr-pp (re-string &optional dialect) - "Convert to `rx' notation and output the pretty-printed result. -This function uses `xr' to translate RE-STRING into DIALECT. -It is intended for use from an interactive elisp session. -See `xr' for a description of the DIALECT argument." - (insert (xr-pp-rx-to-str (xr re-string dialect)))) - -;;;###autoload -(defun xr-skip-set-pp (skip-set-string &optional dialect) - "Convert a skip set string to `rx' notation and pretty-print. -This function uses `xr-skip-set' to translate SKIP-SET-STRING -into DIALECT. -It is intended for use from an interactive elisp session. -See `xr' for a description of the DIALECT argument." - (insert (xr-pp-rx-to-str (xr-skip-set skip-set-string dialect)))) - -(provide 'xr) - -;;; xr.el ends here