config

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

csv-mode.el (82637B)


      1 ;;; csv-mode.el --- Major mode for editing comma/char separated values  -*- lexical-binding: t -*-
      2 
      3 ;; Copyright (C) 2003-2023  Free Software Foundation, Inc
      4 
      5 ;; Author: "Francis J. Wright" <F.J.Wright@qmul.ac.uk>
      6 ;; Maintainer: emacs-devel@gnu.org
      7 ;; Version: 1.23
      8 ;; Package-Requires: ((emacs "27.1") (cl-lib "0.5"))
      9 ;; Keywords: convenience
     10 
     11 ;; This package is free software; you can redistribute it and/or modify
     12 ;; it under the terms of the GNU General Public License as published by
     13 ;; the Free Software Foundation; either version 3, or (at your option)
     14 ;; any later version.
     15 
     16 ;; This package is distributed in the hope that it will be useful,
     17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     19 ;; GNU General Public License for more details.
     20 
     21 ;; You should have received a copy of the GNU General Public License
     22 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     23 
     24 ;;; Commentary:
     25 
     26 ;; This package implements CSV mode, a major mode for editing records
     27 ;; in a generalized CSV (character-separated values) format.  It binds
     28 ;; files with prefix ".csv" to `csv-mode' (and ".tsv" to `tsv-mode') in
     29 ;; `auto-mode-alist'.
     30 
     31 ;; In CSV mode, the following commands are available:
     32 
     33 ;; - C-c C-s (`csv-sort-fields') and C-c C-n (`csv-sort-numeric-fields')
     34 ;;   respectively sort lexicographically and numerically on a
     35 ;;   specified field or column.
     36 
     37 ;; - C-c C-r (`csv-reverse-region') reverses the order.  (These
     38 ;;   commands are based closely on, and use, code in `sort.el'.)
     39 
     40 ;; - C-c C-k (`csv-kill-fields') and C-c C-y (`csv-yank-fields') kill
     41 ;;   and yank fields or columns, although they do not use the normal
     42 ;;   kill ring.  C-c C-k can kill more than one field at once, but
     43 ;;   multiple killed fields can be yanked only as a fixed group
     44 ;;   equivalent to a single field.
     45 
     46 ;; - `csv-align-mode' keeps fields visually aligned, on-the-fly.
     47 ;;   It truncates fields to a maximum width that can be changed per-column
     48 ;;   with `csv-align-set-column-width'.
     49 ;;   Alternatively, C-c C-a (`csv-align-fields') aligns fields into columns
     50 ;;   and C-c C-u (`csv-unalign-fields') undoes such alignment;
     51 ;;   separators can be hidden within aligned records (controlled by
     52 ;;   `csv-invisibility-default' and `csv-toggle-invisibility').
     53 
     54 ;; - C-c C-t (`csv-transpose') interchanges rows and columns.  For
     55 ;;   details, see the documentation for the individual commands.
     56 
     57 ;; - `csv-set-separator' sets the CSV separator of the current buffer,
     58 ;;   while `csv-guess-set-separator' guesses and sets the separator
     59 ;;   based on the current buffer's contents.
     60 ;;   `csv-guess-set-separator' can be useful to add to the mode hook
     61 ;;   to have CSV mode guess and set the separator automatically when
     62 ;;   visiting a buffer:
     63 ;;
     64 ;;     (add-hook 'csv-mode-hook 'csv-guess-set-separator)
     65 
     66 ;; CSV mode can recognize fields separated by any of several single
     67 ;; characters, specified by the value of the customizable user option
     68 ;; `csv-separators'.  CSV data fields can be delimited by quote
     69 ;; characters (and must if they contain separator characters).  This
     70 ;; implementation supports quoted fields, where the quote characters
     71 ;; allowed are specified by the value of the customizable user option
     72 ;; `csv-field-quotes'.  By default, the both commas and tabs are considered
     73 ;; as separators and the only field quote is a double quote.
     74 ;; These user options can be changed ONLY by customizing them, e.g. via M-x
     75 ;; customize-variable.
     76 
     77 ;; CSV mode commands ignore blank lines and comment lines beginning
     78 ;; with the value of the buffer local variable `csv-comment-start',
     79 ;; which by default is #.  The user interface is similar to that of
     80 ;; the standard commands `sort-fields' and `sort-numeric-fields', but
     81 ;; see the major mode documentation below.
     82 
     83 ;; The global minor mode `csv-field-index-mode' provides display of
     84 ;; the current field index in the mode line, cf. `line-number-mode'
     85 ;; and `column-number-mode'.  It is on by default.
     86 
     87 ;;;; See also:
     88 
     89 ;; the standard GNU Emacs 21 packages align.el, which will align
     90 ;; columns within a region, and delim-col.el, which helps to prettify
     91 ;; columns in a text region or rectangle;
     92 
     93 ;; csv.el by Ulf Jasper <ulf.jasper at web.de>, which provides
     94 ;; functions for reading/parsing comma-separated value files and is
     95 ;; available at http://de.geocities.com/ulf_jasper/emacs.html (and in
     96 ;; the gnu.emacs.sources archives).
     97 
     98 ;;; Installation:
     99 
    100 ;; Put this file somewhere that Emacs can find it (i.e. in one of the
    101 ;; directories in your `load-path' such as `site-lisp'), optionally
    102 ;; byte-compile it (recommended), and put this in your .emacs file:
    103 ;;
    104 ;; (add-to-list 'auto-mode-alist '("\\.[Cc][Ss][Vv]\\'" . csv-mode))
    105 ;; (autoload 'csv-mode "csv-mode"
    106 ;;   "Major mode for editing comma-separated value files." t)
    107 
    108 ;;; News:
    109 
    110 ;; Since 1.21:
    111 ;; - New command `csv-insert-column'.
    112 ;; - New config var `csv-align-min-width' for `csv-align-mode'.
    113 ;; - New option `csv-confirm-region'.
    114 
    115 ;; Since 1.9:
    116 ;; - `csv-align-mode' auto-aligns columns dynamically (on screen).
    117 
    118 ;; Before that:
    119 ;; Begun on 15 November 2003 to provide lexicographic sorting of
    120 ;; simple CSV data by field and released as csv.el.  Facilities to
    121 ;; kill multiple fields and customize separator added on 9 April 2004.
    122 ;; Converted to a major mode and renamed csv-mode.el on 10 April 2004,
    123 ;; partly at the suggestion of Stefan Monnier <monnier at
    124 ;; IRO.UMontreal.CA> to avoid conflict with csv.el by Ulf Jasper.
    125 ;; Field alignment, comment support and CSV mode customization group
    126 ;; added on 1 May 2004.  Support for index ranges added on 6 June
    127 ;; 2004.  Multiple field separators added on 12 June 2004.
    128 ;; Transposition added on 22 June 2004.  Separator invisibility added
    129 ;; on 23 June 2004.
    130 
    131 ;;; To do (maybe):
    132 
    133 ;; Make separators and quotes buffer-local and locally settable.
    134 ;; Support (La)TeX tables: set separator and comment; support record
    135 ;; end string.
    136 ;; Convert comma-separated to space- or tab-separated.
    137 
    138 ;;; Code:
    139 
    140 (eval-when-compile
    141   (require 'cl-lib)
    142   (require 'subr-x))
    143 
    144 (defgroup CSV nil
    145   "Major mode for editing files of comma-separated value type."
    146   :group 'convenience)
    147 
    148 (defvar csv-separator-chars nil
    149   "Field separators as a list of character.
    150 Set by customizing `csv-separators' -- do not set directly!")
    151 
    152 (defvar csv-separator-regexp nil
    153   "Regexp to match a field separator.
    154 Set by customizing `csv-separators' -- do not set directly!")
    155 
    156 (defvar csv--skip-chars nil
    157   "Char set used by `skip-chars-forward' etc. to skip fields.
    158 Set by customizing `csv-separators' -- do not set directly!")
    159 
    160 (defvar csv-font-lock-keywords nil
    161   "Font lock keywords to highlight the field separators in CSV mode.
    162 Set by customizing `csv-separators' -- do not set directly!")
    163 
    164 (defcustom csv-separators '("," "\t")
    165   "Field separators: a list of *single-character* strings.
    166 For example: (\",\"), the default, or (\",\" \";\" \":\").
    167 Neighbouring fields may be separated by any one of these characters.
    168 The first is used when inserting a field separator into the buffer.
    169 All must be different from the field quote characters, `csv-field-quotes'.
    170 
    171 Changing this variable with `setq' won't affect the current Emacs
    172 session.  Use `customize-set-variable' instead if that is required."
    173   ;; Suggested by Eckhard Neber <neber@mwt.e-technik.uni-ulm.de>
    174   :type '(repeat string)
    175   ;; FIXME: Character would be better, but in Emacs 21.3 does not display
    176   ;; correctly in a customization buffer.
    177   :set (lambda (variable value)
    178 	 (mapc (lambda (x)
    179 		 (if (/= (length x) 1)
    180 		     (error "Non-single-char string %S" x))
    181                  (if (and (boundp 'csv-field-quotes)
    182                           (member x csv-field-quotes))
    183                      (error "%S is already a quote" x)))
    184 	       value)
    185 	 (custom-set-default variable value)
    186          (setq csv-separator-chars (mapcar #'string-to-char value))
    187          (setq csv--skip-chars
    188                (apply #'concat "^\n"
    189                       (mapcar (lambda (s) (concat "\\" s)) value)))
    190          (setq csv-separator-regexp (regexp-opt value))
    191          (setq csv-font-lock-keywords
    192                ;; NB: csv-separator-face variable evaluates to itself.
    193                `((,csv-separator-regexp (0 'csv-separator-face))))))
    194 
    195 (defcustom csv-field-quotes '("\"")
    196   "Field quotes: a list of *single-character* strings.
    197 For example: (\"\\\"\"), the default, or (\"\\\"\" \"\\='\" \"\\=`\").
    198 A field can be delimited by a pair of any of these characters.
    199 All must be different from the field separators, `csv-separators'."
    200   :type '(repeat string)
    201   ;; Character would be better, but in Emacs 21 does not display
    202   ;; correctly in a customization buffer.
    203   :set (lambda (variable value)
    204 	 (mapc (lambda (x)
    205 		 (if (/= (length x) 1)
    206 		     (error "Non-single-char string %S" x))
    207 		 (if (member x csv-separators)
    208 		     (error "%S is already a separator" x)))
    209 	       value)
    210 	 (when (boundp 'csv-mode-syntax-table)
    211 	   ;; FIRST remove old quote syntax:
    212 	   (with-syntax-table text-mode-syntax-table
    213 	     (mapc (lambda (x)
    214 		     (modify-syntax-entry
    215 		      (string-to-char x)
    216 		      (string (char-syntax (string-to-char x)))
    217 		      ;; symbol-value to avoid compiler warning:
    218 		      (symbol-value 'csv-mode-syntax-table)))
    219 		   csv-field-quotes))
    220 	   ;; THEN set new quote syntax:
    221 	   (csv-set-quote-syntax value))
    222 	 ;; BEFORE setting new value of `csv-field-quotes':
    223 	 (custom-set-default variable value)))
    224 
    225 (defun csv-set-quote-syntax (field-quotes)
    226   "Set syntax for field quote characters FIELD-QUOTES to be \"string\".
    227 FIELD-QUOTES should be a list of single-character strings."
    228   (mapc (lambda (x)
    229 	  (modify-syntax-entry
    230 	   (string-to-char x) "\""
    231 	   ;; symbol-value to avoid compiler warning:
    232 	   (symbol-value 'csv-mode-syntax-table)))
    233 	field-quotes))
    234 
    235 (defvar csv-comment-start nil
    236   "String that starts a comment line, or nil if no comment syntax.
    237 Such comment lines are ignored by CSV mode commands.
    238 This variable is buffer local; its default value is that of
    239 `csv-comment-start-default'.  It is set by the function
    240 `csv-set-comment-start' -- do not set it directly!")
    241 
    242 (make-variable-buffer-local 'csv-comment-start)
    243 
    244 (defcustom csv-comment-start-default "#"
    245   "String that starts a comment line, or nil if no comment syntax.
    246 Such comment lines are ignored by CSV mode commands.
    247 Default value of buffer-local variable `csv-comment-start'.
    248 Changing this variable does not affect any existing CSV mode buffer."
    249   :type '(choice (const :tag "None" nil) string)
    250   :set (lambda (variable value)
    251 	 (custom-set-default variable value)
    252 	 (setq-default csv-comment-start value)))
    253 
    254 (defcustom csv-align-style 'left
    255   "Aligned field style: one of `left', `centre', `right' or `auto'.
    256 Alignment style used by `csv-align-mode' and `csv-align-fields'.
    257 Auto-alignment means left align text and right align numbers."
    258   :type '(choice (const left) (const centre)
    259 		 (const right) (const auto)))
    260 
    261 (defcustom csv-align-padding 1
    262   "Aligned field spacing: must be a positive integer.
    263 Number of spaces used by `csv-align-mode' and `csv-align-fields'
    264 after separators."
    265   :type 'integer)
    266 
    267 (defcustom csv-header-lines 0
    268   "Header lines to skip when setting region automatically."
    269   :type 'integer)
    270 
    271 (defcustom csv-invisibility-default t
    272   "If non-nil, make separators in aligned records invisible."
    273   :type 'boolean)
    274 
    275 (defcustom csv-confirm-region t
    276   "If non-nil, confirm that region is OK in interactive commands."
    277   :type 'boolean)
    278 
    279 (defface csv-separator-face
    280   '((t :inherit escape-glyph))
    281   "CSV mode face used to highlight separators.")
    282 
    283 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    284 ;;;  Mode definition, key bindings and menu
    285 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    286 
    287 
    288 (defconst csv-mode-line-format
    289   '(csv-field-index-string ("" csv-field-index-string))
    290   "Mode line format string for CSV mode.")
    291 
    292 (defvar csv-mode-map
    293   (let ((map (make-sparse-keymap)))
    294     (define-key map [(control ?c) (control ?v)] #'csv-toggle-invisibility)
    295     (define-key map [(control ?c) (control ?t)] #'csv-transpose)
    296     (define-key map [(control ?c) (control ?c)] #'csv-set-comment-start)
    297     (define-key map [(control ?c) (control ?u)] #'csv-unalign-fields)
    298     (define-key map [(control ?c) (control ?a)] #'csv-align-fields)
    299     (define-key map [(control ?c) (control ?z)] #'csv-yank-as-new-table)
    300     (define-key map [(control ?c) (control ?y)] #'csv-yank-fields)
    301     (define-key map [(control ?c) (control ?k)] #'csv-kill-fields)
    302     (define-key map [(control ?c) (control ?d)] #'csv-toggle-descending)
    303     (define-key map [(control ?c) (control ?r)] #'csv-reverse-region)
    304     (define-key map [(control ?c) (control ?n)] #'csv-sort-numeric-fields)
    305     (define-key map [(control ?c) (control ?s)] #'csv-sort-fields)
    306     (define-key map "\t"      #'csv-tab-command)
    307     (define-key map [backtab] #'csv-backtab-command)
    308     map))
    309 
    310 ;;;###autoload
    311 (define-derived-mode csv-mode text-mode "CSV"
    312   "Major mode for editing files of comma-separated value type.
    313 
    314 CSV mode is derived from `text-mode', and runs `text-mode-hook' before
    315 running `csv-mode-hook'.  It turns `auto-fill-mode' off by default.
    316 CSV mode can be customized by user options in the CSV customization
    317 group.  The separators are specified by the value of `csv-separators'.
    318 
    319 CSV mode commands ignore blank lines and comment lines beginning with
    320 the value of `csv-comment-start', which delimit \"paragraphs\".
    321 \"Sexp\" is re-interpreted to mean \"field\", so that `forward-sexp'
    322 \(\\[forward-sexp]), `kill-sexp' (\\[kill-sexp]), etc. all apply to fields.
    323 Standard comment commands apply, such as `comment-dwim' (\\[comment-dwim]).
    324 
    325 If `font-lock-mode' is enabled then separators, quoted values and
    326 comment lines are highlighted using respectively `csv-separator-face',
    327 `font-lock-string-face' and `font-lock-comment-face'.
    328 
    329 The user interface (UI) for CSV mode commands is similar to that of
    330 the standard commands `sort-fields' and `sort-numeric-fields', except
    331 that if there is no prefix argument then the UI prompts for the field
    332 index or indices.  In `transient-mark-mode' only: if the region is not
    333 set then the UI attempts to set it to include all consecutive CSV
    334 records around point, and prompts for confirmation; if there is no
    335 prefix argument then the UI prompts for it, offering as a default the
    336 index of the field containing point if the region was not set
    337 explicitly.  The region set automatically is delimited by blank lines
    338 and comment lines, and the number of header lines at the beginning of
    339 the region given by the value of `csv-header-lines' are skipped.
    340 
    341 Sort order is controlled by `csv-descending'.
    342 
    343 CSV mode provides the following specific keyboard key bindings:
    344 
    345 \\{csv-mode-map}"
    346   :group 'CSV
    347   ;; We used to `turn-off-auto-fill' here instead, but that's not very
    348   ;; effective since text-mode-hook is run afterwards anyway!
    349   (setq-local normal-auto-fill-function nil)
    350   ;; Set syntax for field quotes:
    351   (csv-set-quote-syntax csv-field-quotes)
    352   ;; Make sexp functions apply to fields:
    353   (set (make-local-variable 'forward-sexp-function) #'csv-forward-field)
    354   (csv-set-comment-start csv-comment-start)
    355   ;; Font locking -- separator plus syntactic:
    356   (setq font-lock-defaults '(csv-font-lock-keywords))
    357   (setq-local jit-lock-contextually nil) ;Each line should be independent.
    358   (if csv-invisibility-default (add-to-invisibility-spec 'csv))
    359   ;; Mode line to support `csv-field-index-mode':
    360   (set (make-local-variable 'mode-line-position)
    361        (pcase mode-line-position
    362          (`(,(or (pred consp) (pred stringp)) . ,_)
    363           `(,@mode-line-position ,csv-mode-line-format))
    364          (_ `("" ,mode-line-position ,csv-mode-line-format))))
    365   (set (make-local-variable 'truncate-lines) t)
    366   ;; Enable or disable `csv-field-index-mode' (could probably do this
    367   ;; a bit more efficiently):
    368   (csv-field-index-mode (symbol-value 'csv-field-index-mode)))
    369 
    370 (defun csv-set-comment-start (string)
    371   "Set comment start for this CSV mode buffer to STRING.
    372 It must be either a string or nil."
    373   (interactive
    374    (list (edit-and-eval-command
    375 	  "Comment start (string or nil): " csv-comment-start)))
    376   ;; Paragraph means a group of contiguous records:
    377   (set (make-local-variable 'paragraph-separate) "[[:space:]]*$") ; White space.
    378   (set (make-local-variable 'paragraph-start) "\n");Must include \n explicitly!
    379   ;; Remove old comment-start/end if available
    380   (with-syntax-table text-mode-syntax-table
    381     (when comment-start
    382       (modify-syntax-entry (string-to-char comment-start)
    383 			   (string (char-syntax (string-to-char comment-start)))
    384 			   csv-mode-syntax-table))
    385     (modify-syntax-entry ?\n
    386 			 (string (char-syntax ?\n))
    387 			 csv-mode-syntax-table))
    388   (when string
    389     (setq paragraph-separate (concat paragraph-separate "\\|" string)
    390 	  paragraph-start (concat paragraph-start "\\|" string))
    391     (set (make-local-variable 'comment-start) string)
    392     (modify-syntax-entry
    393      (string-to-char string) "<" csv-mode-syntax-table)
    394     (modify-syntax-entry ?\n ">" csv-mode-syntax-table))
    395   (setq csv-comment-start string))
    396 
    397 (defvar csv--set-separator-history nil)
    398 
    399 (defun csv-set-separator (sep)
    400   "Set the CSV separator in the current buffer to SEP."
    401   (interactive (list (read-char-from-minibuffer
    402                       "Separator: " nil 'csv--set-separator-history)))
    403   (when (and (boundp 'csv-field-quotes)
    404              (member (string sep) csv-field-quotes))
    405     (error "%c is already a quote" sep))
    406   (setq-local csv-separators (list (string sep)))
    407   (setq-local csv-separator-chars (list sep))
    408   (setq-local csv--skip-chars (format "^\n\\%c" sep))
    409   (setq-local csv-separator-regexp (regexp-quote (string sep)))
    410   (setq-local csv-font-lock-keywords
    411               `((,csv-separator-regexp (0 'csv-separator-face))))
    412   (font-lock-refresh-defaults))
    413 
    414 ;;;###autoload
    415 (add-to-list 'auto-mode-alist '("\\.[Cc][Ss][Vv]\\'" . csv-mode))
    416 
    417 (defvar csv-descending nil
    418   "If non-nil, CSV mode sort functions sort in order of descending sort key.
    419 Usually they sort in order of ascending sort key.")
    420 
    421 (defun csv-toggle-descending ()
    422   "Toggle `csv-descending'."
    423   (interactive)
    424   (setq csv-descending (not csv-descending))
    425   (message "Sort order is %sscending" (if csv-descending "de" "a")))
    426 
    427 (defun csv-toggle-invisibility ()
    428   ;; FIXME: Make it into a proper minor mode?
    429   "Toggle `buffer-invisibility-spec'."
    430   (interactive)
    431   (if (memq 'csv buffer-invisibility-spec)
    432       (remove-from-invisibility-spec 'csv)
    433     (add-to-invisibility-spec 'csv))
    434   (message "Separators in aligned records will be %svisible \
    435 \(after re-aligning if soft)"
    436 	   (if (memq 'csv buffer-invisibility-spec) "in" ""))
    437   (redraw-frame (selected-frame)))
    438 
    439 (easy-menu-define
    440   csv-menu
    441   csv-mode-map
    442   "CSV major mode menu keymap"
    443   '("CSV"
    444     ["Sort By Field Lexicographically" csv-sort-fields :active t
    445      :help "Sort lines in region lexicographically by the specified field"]
    446     ["Sort By Field Numerically" csv-sort-numeric-fields :active t
    447      :help "Sort lines in region numerically by the specified field"]
    448     ["Reverse Order of Lines" csv-reverse-region :active t
    449      :help "Reverse the order of the lines in the region"]
    450     ["Use Descending Sort Order" csv-toggle-descending :active t
    451      :style toggle :selected csv-descending
    452      :help "If selected, use descending order when sorting"]
    453     "--"
    454     ["Kill Fields (Columns)" csv-kill-fields :active t
    455      :help "Kill specified fields of each line in the region"]
    456     ["Yank Fields (Columns)" csv-yank-fields :active t
    457      :help "Yank killed fields as specified field of each line in region"]
    458     ["Yank As New Table" csv-yank-as-new-table :active t
    459      :help "Yank killed fields as a new table at point"]
    460     ["Align Fields into Columns" csv-align-fields :active t
    461      :help "Align the start of every field of each line in the region"]
    462     ["Unalign Columns into Fields" csv-unalign-fields :active t
    463      :help "Undo soft alignment and optionally remove redundant white space"]
    464     ["Transpose Rows and Columns" csv-transpose :active t
    465      :help "Rewrite rows (which may have different lengths) as columns"]
    466     "--"
    467     ["Forward Field" forward-sexp :active t
    468      :help "Move forward across one field; with ARG, do it that many times"]
    469     ["Backward Field" backward-sexp :active t
    470      :help "Move backward across one field; with ARG, do it that many times"]
    471     ["Kill Field Forward" kill-sexp :active t
    472      :help "Kill field following cursor; with ARG, do it that many times"]
    473     ["Kill Field Backward" backward-kill-sexp :active t
    474      :help "Kill field preceding cursor; with ARG, do it that many times"]
    475     "--"
    476     ("Alignment Style"
    477      ["Left" (setq csv-align-style 'left) :active t
    478       :style radio :selected (eq csv-align-style 'left)
    479       :help "If selected, `csv-align' left aligns fields"]
    480      ["Centre" (setq csv-align-style 'centre) :active t
    481       :style radio :selected (eq csv-align-style 'centre)
    482       :help "If selected, `csv-align' centres fields"]
    483      ["Right" (setq csv-align-style 'right) :active t
    484       :style radio :selected (eq csv-align-style 'right)
    485       :help "If selected, `csv-align' right aligns fields"]
    486      ["Auto" (setq csv-align-style 'auto) :active t
    487       :style radio :selected (eq csv-align-style 'auto)
    488       :help "\
    489 If selected, `csv-align' left aligns text and right aligns numbers"]
    490      )
    491     ["Set header line" csv-header-line :active t]
    492     ["Auto-(re)align fields" csv-align-mode
    493      :style toggle :selected csv-align-mode]
    494     ["Show Current Field Index" csv-field-index-mode :active t
    495      :style toggle :selected csv-field-index-mode
    496      :help "If selected, display current field index in mode line"]
    497     ["Make Separators Invisible" csv-toggle-invisibility :active t
    498      :style toggle :selected (memq 'csv buffer-invisibility-spec)
    499      :visible (not (tsv--mode-p))
    500      :help "If selected, separators in aligned records are invisible"]
    501     ["Set Buffer's Comment Start" csv-set-comment-start :active t
    502      :help "Set comment start string for this buffer"]
    503     ["Customize CSV Mode" (customize-group 'CSV) :active t
    504      :help "Open a customization buffer to change CSV mode options"]
    505     ))
    506 
    507 (require 'sort)
    508 
    509 (defsubst csv-not-looking-at-record ()
    510   "Return t if looking at blank or comment line, nil otherwise.
    511 Assumes point is at beginning of line."
    512   (looking-at paragraph-separate))
    513 
    514 (defun csv-interactive-args (&optional type)
    515   "Get arg or field(s) and region interactively, offering sensible defaults.
    516 Signal an error if the buffer is read-only.
    517 If TYPE is noarg then return a list (beg end).
    518 Otherwise, return a list (arg beg end), where arg is:
    519   the raw prefix argument by default;
    520   a single field index if TYPE is single;
    521   a list of field indices or index ranges if TYPE is multiple.
    522 Field defaults to the current prefix arg; if not set, prompt user.
    523 
    524 A field index list consists of positive or negative integers or ranges,
    525 separated by any non-integer characters.  A range has the form m-n,
    526 where m and n are positive or negative integers, m < n, and n defaults
    527 to the last field index if omitted.
    528 
    529 In transient mark mode, if the mark is not active then automatically
    530 select and highlight CSV records around point, and query user.
    531 The default field when read interactively is the current field."
    532   ;; Must be run interactively to activate mark!
    533   (let* ((arg current-prefix-arg) (default-field 1)
    534 	 (region
    535 	  (if (not (use-region-p))
    536 	      ;; Set region automatically:
    537 	      (save-excursion
    538                 (if arg
    539                     (beginning-of-line)
    540                   (let ((lbp (line-beginning-position)))
    541                     (while (re-search-backward csv-separator-regexp lbp 1)
    542                       ;; Move as far as possible, i.e. to beginning of line.
    543                       (setq default-field (1+ default-field)))))
    544                 (if (csv-not-looking-at-record)
    545                     (error "Point must be within CSV records"))
    546 		(let ((startline (point)))
    547 		  ;; Set mark at beginning of region:
    548 		  (while (not (or (bobp) (csv-not-looking-at-record)))
    549 		    (forward-line -1))
    550 		  (if (csv-not-looking-at-record) (forward-line 1))
    551 		  ;; Skip header lines:
    552 		  (forward-line csv-header-lines)
    553 		  (set-mark (point))	; OK since in save-excursion
    554 		  ;; Move point to end of region:
    555 		  (goto-char startline)
    556 		  (beginning-of-line)
    557 		  (while (not (or (eobp) (csv-not-looking-at-record)))
    558 		    (forward-line 1))
    559 		  ;; Show mark briefly if necessary:
    560 		  (unless (and (pos-visible-in-window-p)
    561 			       (pos-visible-in-window-p (mark)))
    562 		    (exchange-point-and-mark)
    563 		    (sit-for 1)
    564 		    (exchange-point-and-mark))
    565                   (when csv-confirm-region
    566                     (or (y-or-n-p "Region OK? ")
    567                         (error "Action aborted by user"))
    568                     (message nil))      ; clear y-or-n-p message
    569 		  (list (region-beginning) (region-end))))
    570 	    ;; Use region set by user:
    571 	    (list (region-beginning) (region-end)))))
    572     (setq default-field (number-to-string default-field))
    573     (cond
    574      ((eq type 'multiple)
    575       (if arg
    576 	  ;; Ensure that field is a list:
    577 	  (or (consp arg)
    578 	      (setq arg (list (prefix-numeric-value arg))))
    579 	;; Read field interactively, ignoring non-integers:
    580 	(setq arg
    581 	      (mapcar
    582 	       (lambda (x)
    583 		 (if (string-match "-" x 1) ; not first character
    584 		     ;; Return a range as a pair - the cdr may be nil:
    585 		     (let ((m (substring x 0 (match-beginning 0)))
    586 			   (n (substring x (match-end 0))))
    587 		       (cons (car (read-from-string m))
    588 			     (and (not (string= n ""))
    589 				  (car (read-from-string n)))))
    590 		   ;; Return a number as a number:
    591 		   (car (read-from-string x))))
    592 	       (split-string
    593 		(read-string
    594 		 "Fields (sequence of integers or ranges): " default-field)
    595 		"[^-+0-9]+")))))
    596      ((eq type 'single)
    597       (if arg
    598 	  (setq arg (prefix-numeric-value arg))
    599 	(while (not (integerp arg))
    600 	  (setq arg (eval-minibuffer "Field (integer): " default-field))))))
    601     (if (eq type 'noarg) region (cons arg region))))
    602 
    603 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    604 ;;;  Sorting by field
    605 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    606 
    607 (defun csv-nextrecfun ()
    608   "Called by `csv-sort-fields-1' with point at end of previous record.
    609 It moves point to the start of the next record.
    610 It should move point to the end of the buffer if there are no more records."
    611   (forward-line)
    612   (while (and (not (eobp)) (csv-not-looking-at-record))
    613     (forward-line)))
    614 
    615 (defun csv-sort-fields-1 (field beg end startkeyfun endkeyfun)
    616   "Modified version of `sort-fields-1' that skips blank or comment lines.
    617 
    618 FIELD is a single field index, and BEG and END specify the region to
    619 sort.
    620 
    621 STARTKEYFUN moves from the start of the record to the start of the key.
    622 It may return either a non-nil value to be used as the key, or
    623 else the key is the substring between the values of point after
    624 STARTKEYFUN and ENDKEYFUN are called.  If STARTKEYFUN is nil, the key
    625 starts at the beginning of the record.
    626 
    627 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
    628 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
    629 same as ENDRECFUN."
    630   (let ((tbl (syntax-table)))
    631     (if (zerop field) (setq field 1))
    632     (unwind-protect
    633 	(save-excursion
    634 	  (save-restriction
    635 	    (narrow-to-region beg end)
    636 	    (goto-char (point-min))
    637 	    (set-syntax-table sort-fields-syntax-table)
    638 	    (sort-subr csv-descending
    639 		       'csv-nextrecfun 'end-of-line
    640 		       startkeyfun endkeyfun)))
    641       (set-syntax-table tbl))))
    642 
    643 (defun csv-sort-fields (field beg end)
    644   "Sort lines in region lexicographically by the ARGth field of each line.
    645 If not set, the region defaults to the CSV records around point.
    646 Fields are separated by `csv-separators' and null fields are allowed anywhere.
    647 Field indices increase from 1 on the left or decrease from -1 on the right.
    648 A prefix argument specifies a single field, otherwise prompt for field index.
    649 Ignore blank and comment lines.  The variable `sort-fold-case'
    650 determines whether alphabetic case affects the sort order.
    651 When called non-interactively, FIELD is a single field index;
    652 BEG and END specify the region to sort."
    653   ;; (interactive "*P\nr")
    654   (interactive (csv-interactive-args 'single))
    655   (barf-if-buffer-read-only)
    656   (csv-sort-fields-1 field beg end
    657 		     (lambda () (csv-sort-skip-fields field) nil)
    658 		     (lambda () (skip-chars-forward csv--skip-chars))))
    659 
    660 (defun csv-sort-numeric-fields (field beg end)
    661   "Sort lines in region numerically by the ARGth field of each line.
    662 If not set, the region defaults to the CSV records around point.
    663 Fields are separated by `csv-separators'.
    664 Null fields are allowed anywhere and sort as zeros.
    665 Field indices increase from 1 on the left or decrease from -1 on the right.
    666 A prefix argument specifies a single field, otherwise prompt for field index.
    667 Specified non-null field must contain a number in each line of the region,
    668 which may begin with \"0x\" or \"0\" for hexadecimal and octal values.
    669 Otherwise, the number is interpreted according to sort-numeric-base.
    670 Ignore blank and comment lines.
    671 When called non-interactively, FIELD is a single field index;
    672 BEG and END specify the region to sort."
    673   ;; (interactive "*P\nr")
    674   (interactive (csv-interactive-args 'single))
    675   (barf-if-buffer-read-only)
    676   (csv-sort-fields-1 field beg end
    677 		 (lambda ()
    678 		   (csv-sort-skip-fields field)
    679 		   (let* ((case-fold-search t)
    680 			  (base
    681 			   (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
    682 			       (cond ((match-beginning 1)
    683 				      (goto-char (match-end 1))
    684 				      16)
    685 				     ((match-beginning 2)
    686 				      (goto-char (match-end 2))
    687 				      8)
    688 				     (t nil)))))
    689 		     (string-to-number (buffer-substring (point)
    690 							 (save-excursion
    691 							   (forward-sexp 1)
    692 							   (point)))
    693 				       (or base sort-numeric-base))))
    694 		 nil))
    695 
    696 (defun csv-reverse-region (beg end)
    697   "Reverse the order of the lines in the region.
    698 This is just a CSV-mode style interface to `reverse-region', which is
    699 the function that should be used non-interactively.  It takes two
    700 point or marker arguments, BEG and END, delimiting the region."
    701   ;; (interactive "*P\nr")
    702   (interactive (csv-interactive-args 'noarg))
    703   (barf-if-buffer-read-only)
    704   (reverse-region beg end))
    705 
    706 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    707 ;;;  Moving by field
    708 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    709 
    710 (defun csv-end-of-field ()
    711   "Skip forward over one field."
    712   (skip-chars-forward " ")
    713   ;; If the first character is a double quote, then we have a quoted
    714   ;; value.
    715   (when (eq (char-syntax (following-char)) ?\")
    716     (forward-char)
    717     (let ((ended nil))
    718       (while (not ended)
    719 	(cond ((not (eq (char-syntax (following-char)) ?\"))
    720 	       (forward-char 1))
    721 	      ;; According to RFC-4180 (sec 2.7), quotes inside quoted strings
    722 	      ;; are quoted by doubling the quote char: a,"b""c,",d
    723 	      ;; FIXME: Maybe we should handle this via syntax-propertize?
    724               ((let ((c (char-after (1+ (point)))))
    725                  (and c (eq (char-syntax c) ?\")))
    726 	       (forward-char 2))
    727 	      (t
    728 	       (setq ended t))))))
    729   (skip-chars-forward csv--skip-chars))
    730 
    731 (defun csv--bof-p ()
    732   (or (bolp)
    733       (memq (preceding-char) csv-separator-chars)))
    734 
    735 (defun csv--eof-p ()
    736   (or (eolp)
    737       (memq (following-char) csv-separator-chars)))
    738 
    739 (defun csv-beginning-of-field ()
    740   "Skip backward over one field."
    741   (skip-syntax-backward " ")
    742   (if (eq (char-syntax (preceding-char)) ?\")
    743       (goto-char (scan-sexps (point) -1)))
    744   (skip-chars-backward csv--skip-chars))
    745 
    746 (defun csv-forward-field (arg)
    747   "Move forward across one field, cf. `forward-sexp'.
    748 With ARG, do it that many times.  Negative arg -N means
    749 move backward across N fields."
    750   (interactive "p")
    751   (if (< arg 0)
    752       (csv-backward-field (- arg))
    753     (while (>= (setq arg (1- arg)) 0)
    754       (if (or (bolp)
    755 	      (when (and (not (eobp)) (eolp)) (forward-char) t))
    756 	  (while (and (not (eobp)) (csv-not-looking-at-record))
    757 	    (forward-line 1)))
    758       (if (memq (following-char) csv-separator-chars) (forward-char))
    759       (csv-end-of-field))))
    760 
    761 (defun csv-backward-field (arg)
    762   "Move backward across one field, cf. `backward-sexp'.
    763 With ARG, do it that many times.  Negative arg -N means
    764 move forward across N fields."
    765   (interactive "p")
    766   (if (< arg 0)
    767       (csv-forward-field (- arg))
    768     (while (>= (setq arg (1- arg)) 0)
    769       (when (or (eolp)
    770 		(when (and (not (bobp)) (bolp)) (backward-char) t))
    771 	(while (progn
    772 		 (beginning-of-line)
    773 		 (csv-not-looking-at-record))
    774 	  (backward-char))
    775 	(end-of-line))
    776       (if (memq (preceding-char) csv-separator-chars) (backward-char))
    777       (csv-beginning-of-field))))
    778 
    779 (defun csv-tab-command ()
    780   "Skip to the next field on the same line.
    781 Create a new field at end of line, if needed."
    782   (interactive)
    783   (skip-chars-forward csv--skip-chars)
    784   (if (eolp)
    785       (insert (car csv-separators))
    786     (forward-char 1)))
    787 
    788 (defun csv-backtab-command ()
    789   "Skip to the beginning of the previous field."
    790   (interactive)
    791   (skip-chars-backward csv--skip-chars)
    792   (forward-char -1)
    793   (skip-chars-backward csv--skip-chars))
    794 
    795 (defun csv-sort-skip-fields (n &optional yank)
    796   "Position point at the beginning of field N on the current line.
    797 Fields are separated by `csv-separators'; null terminal field allowed.
    798 Assumes point is initially at the beginning of the line.
    799 YANK non-nil allows N to be greater than the number of fields, in
    800 which case extend the record as necessary."
    801   (if (> n 0)
    802       ;; Skip across N - 1 fields.
    803       (let ((i (1- n)))
    804 	(while (> i 0)
    805 	  (csv-end-of-field)
    806 	  (if (eolp)
    807 	      (if yank
    808 		  (if (> i 1) (insert (car csv-separators)))
    809 		(error "Line has too few fields: %s"
    810 		       (buffer-substring
    811 			(save-excursion (beginning-of-line) (point))
    812 			(save-excursion (end-of-line) (point)))))
    813 	    (forward-char))		; skip separator
    814 	  (setq i (1- i))))
    815     (end-of-line)
    816     ;; Skip back across -N - 1 fields.
    817     (let ((i (1- (- n))))
    818       (while (> i 0)
    819 	(csv-beginning-of-field)
    820 	(if (bolp)
    821 	    (error "Line has too few fields: %s"
    822 		   (buffer-substring
    823 		    (save-excursion (beginning-of-line) (point))
    824 		    (save-excursion (end-of-line) (point)))))
    825 	(backward-char)			; skip separator
    826 	(setq i (1- i)))
    827       ;; Position at the front of the field
    828       ;; even if moving backwards.
    829       (csv-beginning-of-field))))
    830 
    831 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    832 ;;;  Field index mode
    833 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    834 
    835 ;; Based partly on paren.el
    836 
    837 (defcustom csv-field-index-delay 0.125
    838   "Time in seconds to delay before updating field index display."
    839   :type '(number :tag "seconds"))
    840 
    841 (defvar csv-field-index-idle-timer nil)
    842 
    843 (defvar csv-field-index-string nil)
    844 (make-variable-buffer-local 'csv-field-index-string)
    845 
    846 (defvar csv-field-index-old nil)
    847 (make-variable-buffer-local 'csv-field-index-old)
    848 
    849 (define-minor-mode csv-field-index-mode
    850   "Toggle CSV-Field-Index mode.
    851 With prefix ARG, turn CSV-Field-Index mode on if and only if ARG is positive.
    852 Returns the new status of CSV-Field-Index mode (non-nil means on).
    853 When CSV-Field-Index mode is enabled, the current field index appears in
    854 the mode line after `csv-field-index-delay' seconds of Emacs idle time."
    855   :global t
    856   :init-value t		       ; for documentation, since default is t
    857   ;; This macro generates a function that first sets the mode
    858   ;; variable, then runs the following code, runs the mode hooks,
    859   ;; displays a message if interactive, updates the mode line and
    860   ;; finally returns the variable value.
    861 
    862   ;; First, always disable the mechanism (to avoid having two timers):
    863   (when csv-field-index-idle-timer
    864     (cancel-timer csv-field-index-idle-timer)
    865     (setq csv-field-index-idle-timer nil))
    866   ;; Now, if the mode is on and any buffer is in CSV mode then
    867   ;; re-initialize and enable the mechanism by setting up a new timer:
    868   (if csv-field-index-mode
    869       (if (memq t (mapcar (lambda (buffer)
    870 			    (with-current-buffer buffer
    871 			      (when (derived-mode-p 'csv-mode)
    872 				(setq csv-field-index-string nil
    873 				      csv-field-index-old nil)
    874 				t)))
    875 			  (buffer-list)))
    876 	  (setq csv-field-index-idle-timer
    877 		(run-with-idle-timer csv-field-index-delay t
    878 				     #'csv-field-index)))
    879     ;; but if the mode is off then remove the display from the mode
    880     ;; lines of all CSV buffers:
    881     (mapc (lambda (buffer)
    882 	    (with-current-buffer buffer
    883 	      (when (derived-mode-p 'csv-mode)
    884 		(setq csv-field-index-string nil
    885 		      csv-field-index-old nil)
    886 		(force-mode-line-update))))
    887 	    (buffer-list))))
    888 
    889 (defun csv--field-index ()
    890   (save-excursion
    891     (let ((start (point))
    892 	  (field 0))
    893       (beginning-of-line)
    894       (while (and (<= (point) start)
    895                   (not (eolp)))
    896 	(csv-end-of-field)
    897 	(unless (eolp)
    898 	  (forward-char 1))
    899 	(setq field (1+ field)))
    900       field)))
    901 
    902 (defun csv-field-index ()
    903   "Construct `csv-field-index-string' to display in mode line.
    904 Called by `csv-field-index-idle-timer'."
    905   (if (derived-mode-p 'csv-mode)
    906       (let ((field (csv--field-index)))
    907 	(when (not (eq field csv-field-index-old))
    908 	  (setq csv-field-index-old field
    909 		csv-field-index-string
    910 		(and field (format "F%d" field)))
    911 	  (force-mode-line-update)))))
    912 
    913 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    914 ;;;  Killing and yanking fields
    915 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    916 
    917 (defvar csv-killed-fields nil
    918   "A list of the fields or sub-records last killed by `csv-kill-fields'.")
    919 
    920 (defun csv-kill-fields (fields beg end)
    921   "Kill specified fields of each line in the region.
    922 If not set, the region defaults to the CSV records around point.
    923 Fields are separated by `csv-separators' and null fields are allowed anywhere.
    924 Field indices increase from 1 on the left or decrease from -1 on the right.
    925 The fields are stored for use by `csv-yank-fields'.  Fields can be
    926 specified in any order but are saved in increasing index order.
    927 Ignore blank and comment lines.
    928 
    929 When called interactively, a prefix argument specifies a single field,
    930 otherwise prompt for a field list, which may include ranges in the form
    931 m-n, where m < n and n defaults to the last field index if omitted.
    932 
    933 When called non-interactively, FIELDS is a single field index or a
    934 list of field indices, with ranges specified as (m.n) or (m), and BEG
    935 and END specify the region to process."
    936   ;; (interactive "*P\nr")
    937   (interactive (csv-interactive-args 'multiple))
    938   (barf-if-buffer-read-only)
    939   ;; Kill the field(s):
    940   (setq csv-killed-fields nil)
    941   (save-excursion
    942     (save-restriction
    943       (narrow-to-region beg end)
    944       (goto-char (point-min))
    945       (if (or (cdr fields) (consp (car fields)))
    946 	  (csv-kill-many-columns fields)
    947 	(csv-kill-one-column (car fields)))))
    948   (setq csv-killed-fields (nreverse csv-killed-fields)))
    949 
    950 (defun csv-kill-one-field (field)
    951   "Kill field with index FIELD in current line.
    952 Return killed text.  Assumes point is at beginning of line."
    953   ;; Move to start of field to kill:
    954   (csv-sort-skip-fields field)
    955   ;; Kill to end of field (cf. `kill-region'):
    956   (prog1 (delete-and-extract-region
    957           (point)
    958           (progn (csv-end-of-field) (point)))
    959     (if (eolp)
    960         (unless (bolp) (delete-char -1)) ; Delete trailing separator at eol
    961       (delete-char 1))))                 ; or following separator otherwise.
    962 
    963 (defun csv-kill-one-column (field)
    964   "Kill field with index FIELD in all lines in (narrowed) buffer.
    965 Save killed fields in `csv-killed-fields'.
    966 Assumes point is at `point-min'.  Called by `csv-kill-fields'.
    967 Ignore blank and comment lines."
    968   (while (not (eobp))
    969     (or (csv-not-looking-at-record)
    970 	(push (csv-kill-one-field field) csv-killed-fields))
    971     (forward-line)))
    972 
    973 (defun csv-insert-column (field)
    974   "Insert an empty column at point."
    975   (interactive
    976    (let ((cur (csv--field-index)))
    977      (list (if (and (csv--eof-p) (not (csv--bof-p))) (1+ cur) cur))))
    978   (save-excursion
    979     (goto-char (point-min))
    980     (while (not (eobp))
    981       (or (csv-not-looking-at-record)
    982 	  (progn
    983 	    (csv-sort-skip-fields field t)
    984 	    (insert (car csv-separators))))
    985       (forward-line 1))
    986     (csv--jit-flush-columns)))
    987 
    988 (defun csv-kill-many-columns (fields)
    989   "Kill several fields in all lines in (narrowed) buffer.
    990 FIELDS is an unordered list of field indices.
    991 Save killed fields in increasing index order in `csv-killed-fields'.
    992 Assumes point is at `point-min'.  Called by `csv-kill-fields'.
    993 Ignore blank and comment lines."
    994   (if (eolp) (error "First record is empty"))
    995   ;; Convert non-positive to positive field numbers:
    996   (let ((last 1) (f fields))
    997     (csv-end-of-field)
    998     (while (not (eolp))
    999       (forward-char)			; skip separator
   1000       (csv-end-of-field)
   1001       (setq last (1+ last)))	     ; last = # fields in first record
   1002     (while f
   1003       (cond ((consp (car f))
   1004 	     ;; Expand a field range: (m.n) -> m m+1 ... n-1 n.
   1005 	     ;; If n is nil then it defaults to the number of fields.
   1006 	     (let* ((range (car f)) (cdrf (cdr f))
   1007 		    (m (car range)) (n (cdr range)))
   1008 	       (if (< m 0) (setq m (+ m last 1)))
   1009 	       (if n
   1010 		   (if (< n 0) (setq n (+ n last 1)))
   1011 		 (setq n last))
   1012 	       (setq range (list n))
   1013 	       (while (> n m) (push (setq n (1- n)) range))
   1014 	       (setcar f (car range))
   1015 	       (setcdr f (cdr range))
   1016 	       (setcdr (setq f (last range)) cdrf)))
   1017 	    ((zerop (car f)) (setcar f 1))
   1018 	    ((< (car f) 0) (setcar f (+ f last 1))))
   1019       (setq f (cdr f))))
   1020   (goto-char (point-min))
   1021   ;; Kill from right to avoid miscounting:
   1022   (setq fields (sort fields #'>))
   1023   (while (not (eobp))
   1024     (or (csv-not-looking-at-record)
   1025 	(let ((fields fields) killed-fields field)
   1026 	  (while fields
   1027 	    (setq field (car fields)
   1028 		  fields (cdr fields))
   1029 	    (beginning-of-line)
   1030 	    (push (csv-kill-one-field field) killed-fields))
   1031 	  (push (mapconcat #'identity killed-fields (car csv-separators))
   1032 		csv-killed-fields)))
   1033     (forward-line)))
   1034 
   1035 (defun csv-yank-fields (field beg end)
   1036   "Yank fields as the ARGth field of each line in the region.
   1037 ARG may be arbitrarily large and records are extended as necessary.
   1038 If not set, the region defaults to the CSV records around point;
   1039 if point is not in a CSV record then offer to yank as a new table.
   1040 The fields yanked are those last killed by `csv-kill-fields'.
   1041 Fields are separated by `csv-separators' and null fields are allowed anywhere.
   1042 Field indices increase from 1 on the left or decrease from -1 on the right.
   1043 A prefix argument specifies a single field, otherwise prompt for field index.
   1044 Ignore blank and comment lines.  When called non-interactively, FIELD
   1045 is a single field index; BEG and END specify the region to process."
   1046   ;; (interactive "*P\nr")
   1047   (interactive (condition-case err
   1048 		   (csv-interactive-args 'single)
   1049 		 (error (list nil nil err))))
   1050   (barf-if-buffer-read-only)
   1051   (if (null beg)
   1052       (if (y-or-n-p (concat (error-message-string end)
   1053 			    ".  Yank as a new table? "))
   1054 	  (csv-yank-as-new-table)
   1055 	(error (error-message-string end)))
   1056     (if (<= field 0) (setq field (1+ field)))
   1057     (save-excursion
   1058       (save-restriction
   1059 	(narrow-to-region beg end)
   1060 	(goto-char (point-min))
   1061 	(let ((fields csv-killed-fields))
   1062 	  (while (not (eobp))
   1063 	    (unless (csv-not-looking-at-record)
   1064 	      ;; Yank at start of specified field if possible,
   1065 	      ;; otherwise yank at end of record:
   1066 	      (if (zerop field)
   1067 		  (end-of-line)
   1068 		(csv-sort-skip-fields field 'yank))
   1069 	      (and (eolp) (insert (car csv-separators)))
   1070 	      (when fields
   1071 		(insert (car fields))
   1072 		(setq fields (cdr fields)))
   1073 	      (or (eolp) (insert (car csv-separators))))
   1074 	    (forward-line)))))))
   1075 
   1076 (defun csv-yank-as-new-table ()
   1077   "Yank fields as a new table starting at point.
   1078 The fields yanked are those last killed by `csv-kill-fields'."
   1079   (interactive "*")
   1080   (let ((fields csv-killed-fields))
   1081     (while fields
   1082       (insert (car fields) ?\n)
   1083       (setq fields (cdr fields)))))
   1084 
   1085 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   1086 ;;;  Aligning fields
   1087 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   1088 
   1089 (defun csv--make-overlay (beg end &optional buffer front-advance rear-advance props)
   1090   (let ((o (make-overlay beg end buffer front-advance rear-advance)))
   1091     (overlay-put o 'csv t)
   1092     (while props
   1093       (overlay-put o (pop props) (pop props)))
   1094     o))
   1095 
   1096 (defun csv--delete-overlay (o)
   1097   (and (overlay-get o 'csv) (delete-overlay o)))
   1098 
   1099 (defun csv--column-widths (beg end)
   1100   "Return a list of two lists (COLUMN-WIDTHS FIELD-WIDTHS).
   1101 COLUMN-WIDTHS is a list of elements (WIDTH START END)
   1102 indicating the widths of the columns after point (and the position of the
   1103 widest field that determined the overall width).
   1104 FIELD-WIDTHS contains the widths of each individual field after
   1105 point."
   1106   (let ((column-widths '())
   1107         (field-widths '()))
   1108     (goto-char beg)
   1109     ;; Construct list of column widths:
   1110     (while (< (point) end)              ; for each record...
   1111       (or (csv-not-looking-at-record)
   1112           (let ((w column-widths)
   1113                 (col (current-column))
   1114                 (beg (point))
   1115                 field-width)
   1116             (while (not (eolp))
   1117               (csv-end-of-field)
   1118               (setq field-width (- (current-column) col))
   1119               (push field-width field-widths)
   1120               (if w
   1121                   (if (> field-width (caar w))
   1122                       (setcar w (list field-width beg (point))))
   1123                 (setq w (list (list field-width beg (point)))
   1124                       column-widths (nconc column-widths w)))
   1125               (or (eolp) (forward-char)) ; Skip separator.
   1126               (setq w (cdr w) col (current-column) beg (point)))))
   1127       (forward-line))
   1128     (list column-widths (nreverse field-widths))))
   1129 
   1130 (defun csv-align-fields (hard beg end)
   1131   "Align all the fields in the region to form columns.
   1132 The alignment style is specified by `csv-align-style'.  The number of
   1133 spaces specified by `csv-align-padding' appears after each separator.
   1134 Use soft alignment done by displaying virtual white space after the
   1135 separators unless invoked with an argument, in which case insert real
   1136 space characters into the buffer after the separators.
   1137 Unalign first (see `csv-unalign-fields').  Ignore blank and comment lines.
   1138 
   1139 In hard-aligned records, separators become invisible whenever
   1140 `buffer-invisibility-spec' is non-nil.  In soft-aligned records, make
   1141 separators invisible if and only if `buffer-invisibility-spec' is
   1142 non-nil when the records are aligned; this can be changed only by
   1143 re-aligning.  \(Unaligning always makes separators visible.)
   1144 
   1145 When called non-interactively, use hard alignment if HARD is non-nil;
   1146 BEG and END specify the region to align.
   1147 If there is no selected region, default to the whole buffer."
   1148   (interactive (cons current-prefix-arg
   1149                      (if (use-region-p)
   1150                          (list (region-beginning) (region-end))
   1151                        (list (point-min) (point-max)))))
   1152   ;; FIXME: Use csv--jit-align when applicable!
   1153   (setq end (copy-marker end))
   1154   (csv-unalign-fields hard beg end) ; If hard then barfs if buffer read only.
   1155   (save-excursion
   1156     (pcase-let ((`(,column-widths ,field-widths) (csv--column-widths beg end)))
   1157       (save-restriction
   1158         (narrow-to-region beg end)
   1159         (set-marker end nil)
   1160 
   1161 	;; Align fields:
   1162 	(goto-char (point-min))
   1163 	(while (not (eobp))		; for each record...
   1164 	  (unless (csv-not-looking-at-record)
   1165             (let ((w column-widths)
   1166                   (column 0))    ;Desired position of left-side of this column.
   1167               (while (and w (not (eolp)))
   1168                 (let* ((beg (point))
   1169                        (align-padding (if (bolp) 0 csv-align-padding))
   1170                        (left-padding 0) (right-padding 0)
   1171                        (field-width (pop field-widths))
   1172                        (column-width (car (pop w)))
   1173                        (x (- column-width field-width))) ; Required padding.
   1174                   (csv-end-of-field)
   1175                   (set-marker end (point)) ; End of current field.
   1176                   ;; beg = beginning of current field
   1177                   ;; end = (point) = end of current field
   1178 
   1179                   ;; Compute required padding:
   1180                   (cond
   1181                    ((eq csv-align-style 'left)
   1182                     ;; Left align -- pad on the right:
   1183                     (setq left-padding align-padding
   1184                           right-padding x))
   1185                    ((eq csv-align-style 'right)
   1186                     ;; Right align -- pad on the left:
   1187                     (setq left-padding (+ align-padding x)))
   1188                    ((eq csv-align-style 'auto)
   1189                     ;; Auto align -- left align text, right align numbers:
   1190                     (if (string-match "\\`[-+.[:digit:]]+\\'"
   1191                                       (buffer-substring beg (point)))
   1192                         ;; Right align -- pad on the left:
   1193                         (setq left-padding (+ align-padding x))
   1194                       ;; Left align -- pad on the right:
   1195                       (setq left-padding align-padding
   1196                             right-padding x)))
   1197                    ((eq csv-align-style 'centre)
   1198                     ;; Centre -- pad on both left and right:
   1199                     (let ((y (/ x 2)))  ; truncated integer quotient
   1200                       (setq left-padding (+ align-padding y)
   1201                             right-padding (- x y)))))
   1202 
   1203                   (cond
   1204                    (hard ;; Hard alignment...
   1205                     (when (> left-padding 0) ; Pad on the left.
   1206                       ;; Insert spaces before field:
   1207                       (if (= beg end)   ; null field
   1208                           (insert (make-string left-padding ?\ ))
   1209                         (goto-char beg) ; beginning of current field
   1210                         (insert (make-string left-padding ?\ ))
   1211                         (goto-char end))) ; end of current field
   1212                     (unless (eolp)
   1213                       (if (> right-padding 0) ; pad on the right
   1214                           ;; Insert spaces after field:
   1215                           (insert (make-string right-padding ?\ )))
   1216                       ;; Make separator (potentially) invisible;
   1217                       ;; in Emacs 21.3, neighbouring overlays
   1218                       ;; conflict, so use the following only
   1219                       ;; with hard alignment:
   1220 		      (csv--make-overlay (point) (1+ (point)) nil t nil
   1221 					 '(invisible csv evaporate t))
   1222                       (forward-char)))  ; skip separator
   1223 
   1224                    ;; Soft alignment...
   1225                    ((or (memq 'csv buffer-invisibility-spec)
   1226                         ;; For TSV, hidden or not doesn't make much difference,
   1227                         ;; but the behavior is slightly better when we "hide"
   1228                         ;; the TABs with a `display' property than if we add
   1229                         ;; before/after-strings.
   1230                         (tsv--mode-p))
   1231 
   1232                     ;; Hide separators...
   1233                     ;; Merge right-padding from previous field
   1234                     ;; with left-padding from this field:
   1235                     (if (zerop column)
   1236                         (when (> left-padding 0)
   1237                           ;; Display spaces before first field
   1238                           ;; by overlaying first character:
   1239 			  (csv--make-overlay
   1240 			   beg (1+ beg) nil nil nil
   1241 			   `(before-string ,(make-string left-padding ?\ ))))
   1242                       ;; Display separator as spaces:
   1243                       (with-silent-modifications
   1244                         (put-text-property
   1245                          (1- beg) beg
   1246                          'display `(space :align-to
   1247                                           ,(+ left-padding column)))))
   1248                     (unless (eolp) (forward-char)) ; Skip separator.
   1249                     (setq column (+ column column-width align-padding)))
   1250 
   1251                    (t ;; Do not hide separators...
   1252                     (let ((overlay (csv--make-overlay beg (point) nil nil t)))
   1253                       (when (> left-padding 0) ; Pad on the left.
   1254                         ;; Display spaces before field:
   1255                         (overlay-put overlay 'before-string
   1256                                      (make-string left-padding ?\ )))
   1257                       (unless (eolp)
   1258                         (if (> right-padding 0) ; Pad on the right.
   1259                             ;; Display spaces after field:
   1260                             (overlay-put
   1261                              overlay
   1262                              'after-string (make-string right-padding ?\ )))
   1263                         (forward-char)))) ; Skip separator.
   1264 
   1265                    )))))
   1266 	  (forward-line)))))
   1267   (set-marker end nil))
   1268 
   1269 (defun csv-unalign-fields (hard beg end)
   1270   "Undo soft alignment and optionally remove redundant white space.
   1271 Undo soft alignment introduced by `csv-align-fields'.  If invoked with
   1272 an argument then also remove all spaces and tabs around separators.
   1273 Also make all invisible separators visible again.
   1274 Ignore blank and comment lines.  When called non-interactively, remove
   1275 spaces and tabs if HARD non-nil; BEG and END specify region to unalign.
   1276 If there is no selected region, default to the whole buffer."
   1277   (interactive (cons current-prefix-arg
   1278                      (if (use-region-p)
   1279                          (list (region-beginning) (region-end))
   1280                        (list (point-min) (point-max)))))
   1281   ;; Remove any soft alignment:
   1282   (mapc #'csv--delete-overlay (overlays-in beg end))
   1283   (with-silent-modifications
   1284     (remove-list-of-text-properties beg end '(display invisible)))
   1285   (when hard
   1286     (barf-if-buffer-read-only)
   1287     ;; Remove any white-space padding around separators:
   1288     (save-excursion
   1289       (save-restriction
   1290 	(narrow-to-region beg end)
   1291 	(goto-char (point-min))
   1292 	(while (not (eobp))
   1293 	  (or (csv-not-looking-at-record)
   1294 	      (while (not (eolp))
   1295 		;; Delete horizontal white space forward:
   1296 		;; (delete-horizontal-space)
   1297 		;; This relies on left-to-right argument evaluation;
   1298 		;; see info node (elisp) Function Forms.
   1299 		(delete-region (point)
   1300 			       (+ (point) (skip-chars-forward " \t")))
   1301 		(csv-end-of-field)
   1302 		;; Delete horizontal white space backward:
   1303 		;; (delete-horizontal-space t)
   1304 		(delete-region (point)
   1305 			       (+ (point) (skip-chars-backward " \t")))
   1306 		(or (eolp) (forward-char))))
   1307 	  (forward-line))))))
   1308 
   1309 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   1310 ;;;  Transposing rows and columns
   1311 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   1312 
   1313 (defun csv-transpose (beg end)
   1314   "Rewrite rows (which may have different lengths) as columns.
   1315 Null fields are introduced as necessary within records but are
   1316 stripped from the ends of records.  Preserve soft alignment.
   1317 This function is its own inverse.  Ignore blank and comment lines.
   1318 When called non-interactively, BEG and END specify region to process."
   1319   ;; (interactive "*P\nr")
   1320   (interactive (csv-interactive-args 'noarg))
   1321   (barf-if-buffer-read-only)
   1322   (save-excursion
   1323     (save-restriction
   1324       (narrow-to-region beg end)
   1325       (goto-char (point-min))
   1326       ;; Delete rows and collect them as a reversed list of lists of
   1327       ;; fields, skipping comment and blank lines:
   1328       (let ((sep (car csv-separators))
   1329 	    (align (overlays-in beg end))
   1330 	    rows columns)
   1331 	;; Remove soft alignment if necessary:
   1332 	(when align
   1333 	  (mapc #'csv--delete-overlay align)
   1334 	  (setq align t))
   1335 	(while (not (eobp))
   1336 	  (if (csv-not-looking-at-record)
   1337 	      ;; Skip blank and comment lines:
   1338 	      (forward-line)
   1339 	    (let ((lep (line-end-position)))
   1340 	      (push
   1341 	       (csv--collect-fields lep)
   1342 	       rows)
   1343 	      (delete-region (point) lep)
   1344 	      (or (eobp) (delete-char 1)))))
   1345 	;; Rows must have monotonic decreasing lengths to be
   1346 	;; transposable, so ensure this by padding with null fields.
   1347 	;; rows is currently a reversed list of field lists, which
   1348 	;; must therefore have monotonic increasing lengths.
   1349 	(let ((oldlen (length (car rows))) newlen
   1350 	      (r (cdr rows)))
   1351 	  (while r
   1352 	    (setq newlen (length (car r)))
   1353 	    (if (< newlen oldlen)
   1354 		(nconc (car r) (make-list (- oldlen newlen) nil))
   1355 	      (setq oldlen newlen))
   1356 	    (setq r (cdr r))))
   1357 	;; Collect columns as a reversed list of lists of fields:
   1358 	(while rows
   1359 	  (let (column (r rows) row)
   1360 	    (while r
   1361 	      (setq row (car r))
   1362 	      ;; Provided it would not be a trailing null field, push
   1363 	      ;; field onto column:
   1364 	      (if (or column (string< "" (car row)))
   1365 		  (push (car row) column))
   1366 	      ;; Pop field off row:
   1367 	      (setcar r (cdr row))
   1368 	      ;; If row is now empty then remove it:
   1369 	      (or (car r) (setq rows (cdr rows)))
   1370 	      (setq r (cdr r)))
   1371 	    (push column columns)))
   1372 	;; Insert columns into buffer as rows:
   1373 	(setq columns (nreverse columns))
   1374 	(while columns
   1375 	  (insert (mapconcat #'identity (car columns) sep) ?\n)
   1376 	  (setq columns (cdr columns)))
   1377 	;; Re-do soft alignment if necessary:
   1378 	(if align (csv-align-fields nil (point-min) (point-max)))))))
   1379 
   1380 (defun csv--collect-fields (row-end-position)
   1381   "Collect the fields of a row.
   1382 Splits a row into fields, honoring quoted fields, and returns
   1383 the list of fields.  ROW-END-POSITION is the end-of-line position.
   1384 point is assumed to be at the beginning of the line."
   1385   (let ((csv-field-quotes-regexp (apply #'concat `("[" ,@csv-field-quotes "]")))
   1386 	(row-text (buffer-substring-no-properties (point) row-end-position))
   1387 	fields field-start)
   1388     (if (not (string-match csv-field-quotes-regexp row-text))
   1389 	(split-string row-text csv-separator-regexp)
   1390       (save-excursion
   1391 	(while (< (setq field-start (point)) row-end-position)
   1392           ;; csv-forward-field will skip a separator if point is on
   1393           ;; it, and we'll miss an empty field
   1394           (unless (memq (following-char) csv-separator-chars)
   1395 	    (csv-forward-field 1))
   1396 	  (push
   1397 	   (buffer-substring-no-properties field-start (point))
   1398 	   fields)
   1399 	  (if (memq (following-char) csv-separator-chars)
   1400 	      (forward-char)))
   1401 	(nreverse fields)))))
   1402 
   1403 (defvar-local csv--header-line nil)
   1404 (defvar-local csv--header-hscroll nil)
   1405 (defvar-local csv--header-string nil)
   1406 
   1407 (defun csv-header-line (&optional use-current-line)
   1408   "Set/unset the header line.
   1409 If the optional prefix arg USE-CURRENT-LINE is nil, use the first line
   1410 as the header line.
   1411 If there is already a header line, then unset the header line."
   1412   (interactive "P")
   1413   (if csv--header-line
   1414       (progn
   1415         (delete-overlay csv--header-line)
   1416         (setq csv--header-line nil)
   1417         (kill-local-variable 'header-line-format))
   1418     (save-excursion
   1419       (unless use-current-line (goto-char (point-min)))
   1420       (setq csv--header-line (make-overlay (line-beginning-position)
   1421                                            (line-end-position)
   1422                                            nil nil t))
   1423       (overlay-put csv--header-line 'modification-hooks
   1424                    '(csv--header-flush)))
   1425     (csv--header-flush)
   1426     ;; These are introduced in Emacs 29.
   1427     (unless (boundp 'header-line-indent)
   1428       (setq-local header-line-indent ""
   1429                   header-line-indent-width 0))
   1430     (setq header-line-format
   1431           '("" header-line-indent (:eval (csv--header-string))))))
   1432 
   1433 (defun csv--header-flush (&rest _)
   1434   ;; Force re-computation of the header-line.
   1435   (setq csv--header-hscroll nil))
   1436 
   1437 (defun csv--header-string ()
   1438   ;; FIXME: Won't work with multiple windows showing that same buffer.
   1439   (if (eql (window-hscroll) csv--header-hscroll)
   1440       csv--header-string
   1441     (setq csv--header-hscroll (window-hscroll))
   1442     (setq csv--header-string
   1443           (csv--compute-header-string))))
   1444 
   1445 (defun csv--compute-header-string ()
   1446   (with-demoted-errors "csv--compute-header-string %S"
   1447     (save-excursion
   1448       (goto-char (overlay-start csv--header-line))
   1449       ;; Re-set the line-end-position, just in case.
   1450       (move-overlay csv--header-line (point) (line-end-position))
   1451       (jit-lock-fontify-now (point) (line-end-position))
   1452       ;; Not sure why it is sometimes nil!
   1453       (move-to-column (or csv--header-hscroll 0))
   1454       (let ((str (replace-regexp-in-string
   1455 		  "%" "%%" (buffer-substring (point) (line-end-position))))
   1456             (i 0))
   1457         (while (and i (< i (length str)))
   1458           (let ((prop (get-text-property i 'display str)))
   1459             (and (eq (car-safe prop) 'space)
   1460                  (eq (car-safe (cdr prop)) :align-to)
   1461                  (let* ((x (nth 2 prop))
   1462                         (nexti (next-single-property-change i 'display str))
   1463                         (newprop
   1464                          `(space :align-to
   1465                                  (+ ,(if (numberp x)
   1466                                          (- x (or csv--header-hscroll 0))
   1467                                        `(- ,x csv--header-hscroll))
   1468                                     header-line-indent-width))))
   1469                    (put-text-property i (or nexti (length str))
   1470                                       'display newprop str)
   1471                    (setq i nexti))))
   1472           (setq i (next-single-property-change i 'display str)))
   1473         (concat (propertize " " 'display '((space :align-to 0))) str)))))
   1474 
   1475 ;;; Auto-alignment
   1476 
   1477 (defcustom csv-align-max-width 40
   1478   "Maximum width of a column in `csv-align-mode'.
   1479 This does not apply to the last column (for which the usual `truncate-lines'
   1480 setting works better)."
   1481   :type 'integer)
   1482 
   1483 (defcustom csv-align-min-width 1
   1484   "Minimum width of a column in `csv-align-mode'."
   1485   :type 'integer)
   1486 
   1487 (defvar-local csv--config-column-widths nil
   1488   "Settings per column, stored as a list indexed by the column.")
   1489 
   1490 (defun csv-align--set-column (column value)
   1491   (let ((len (length csv--config-column-widths)))
   1492     (if (< len column)
   1493         (setq csv--config-column-widths
   1494               (nconc csv--config-column-widths (make-list (- column len) nil))))
   1495     (setf (nth (1- column) csv--config-column-widths) value)))
   1496 
   1497 (defun csv-align-set-column-width (column width)
   1498   "Set the max WIDTH to use for COLUMN."
   1499   (interactive
   1500    (let* ((field (or (csv--field-index) 1))
   1501           (curwidth (nth (1- field) csv--config-column-widths)))
   1502      (list field
   1503            (cond
   1504             ((numberp current-prefix-arg)
   1505              current-prefix-arg)
   1506             (current-prefix-arg
   1507              (read-number (format "Column width (for field %d): " field)
   1508                           curwidth))
   1509             (t (if curwidth nil (csv--ellipsis-width)))))))
   1510   (when (eql width csv-align-max-width)
   1511     (setq width nil))
   1512   (csv-align--set-column column width)
   1513   (jit-lock-refontify))
   1514 
   1515 (defvar-local csv--jit-columns nil)
   1516 
   1517 (defun csv--jit-flush-columns ()
   1518   "Throw away all cached info about column widths."
   1519   ;; FIXME: Maybe we should kill its overlays as well.
   1520   (setq csv--jit-columns nil))
   1521 
   1522 (defun csv--jit-merge-columns (column-widths)
   1523   ;; FIXME: The incremental update (delayed by jit-lock-context-time) of column
   1524   ;; width is a bit jarring at times.  It's OK while scrolling or when
   1525   ;; extending a column, but not right when enabling the csv-align-mode or
   1526   ;; when shortening the longest field (or deleting the line containing it),
   1527   ;; because in that case we have *several* cascaded updates, e.g.:
   1528   ;; - Remove the line with the longest field of column N.
   1529   ;; - Edit some line: this line is updated as if its field was the widest,
   1530   ;;   hence its subsequent fields are too much to the left.
   1531   ;; - The rest is updated starting from the first few lines (according
   1532   ;;   to jit-lock-chunk-size).
   1533   ;; - After the first few lines, come the next set of few lines,
   1534   ;;   which may cause the previous few lines to need refresh again.
   1535   ;; - etc.. until arriving again at the edited line which is re-aligned
   1536   ;;   again.
   1537   ;; - etc.. until the end of the windows, potentially causing yet more
   1538   ;;   refreshes as we discover yet-wider fields for this column.
   1539   (let ((old-columns csv--jit-columns)
   1540         (changed nil))
   1541     (while (and old-columns column-widths)
   1542       (when (or (> (caar column-widths) (caar old-columns))
   1543                 ;; Apparently modification-hooks aren't run when the
   1544                 ;; whole text containing the overlay is deleted (e.g.
   1545                 ;; the whole line), so detect this case here.
   1546                 ;; It's a bit too late, but better than never.
   1547                 (null (overlay-buffer (cdar old-columns))))
   1548         (setq changed t) ;; Return non-nil if some existing column changed.
   1549         (pcase-let ((`(,width ,beg ,end) (car column-widths)))
   1550           (setf (caar old-columns) width)
   1551           (move-overlay (cdar old-columns) beg end)))
   1552       (setq old-columns (cdr old-columns))
   1553       (setq column-widths (cdr column-widths)))
   1554     (when column-widths
   1555       ;; New columns appeared.
   1556       (setq csv--jit-columns
   1557             (nconc csv--jit-columns
   1558                    (mapcar (lambda (x)
   1559                              (pcase-let*
   1560                                  ((`(,width ,beg ,end) x)
   1561                                   (ol (make-overlay beg end)))
   1562                                (overlay-put ol 'csv-width t)
   1563                                (overlay-put ol 'evaporate t)
   1564                                (overlay-put ol 'modification-hooks
   1565                                             (list #'csv--jit-width-change))
   1566                                (cons width ol)))
   1567                            column-widths))))
   1568     changed))
   1569 
   1570 (defun csv--jit-width-change (ol after _beg _end &optional len)
   1571   (when (and after (> len 0))
   1572     ;; (let ((x (rassq ol csv--jit-columns)))
   1573     ;;   (when x (setf (car x) -1)))
   1574     (delete-overlay ol)))
   1575 
   1576 (defun csv--jit-unalign (beg end)
   1577   (with-silent-modifications
   1578     (remove-text-properties beg end
   1579                             '( display nil csv--jit nil invisible nil
   1580                                cursor-sensor-functions nil csv--revealed nil))
   1581     (remove-overlays beg end 'csv--jit t)))
   1582 
   1583 (defun csv--jit-flush (beg end)
   1584   "Cause all the buffer (except for the BEG...END region) to be re-aligned."
   1585   (cl-assert (>= end beg))
   1586   ;; The buffer shouldn't have changed since beg/end were computed,
   1587   ;; but just in case, let's make sure they're still sane.
   1588   (when (< beg (point-min))
   1589     (setq beg (point-min) end (max end beg)))
   1590   (when (< (point-max) end)
   1591     (setq end (point-max) beg (min end beg)))
   1592   (let ((pos (point-min)))
   1593     (while (and (< pos beg)
   1594                 (setq pos (text-property-any pos beg 'csv--jit t)))
   1595       (jit-lock-refontify
   1596        pos (setq pos (or (text-property-any pos beg 'csv--jit nil) beg))))
   1597     (setq pos end)
   1598     (while (and (< pos (point-max))
   1599                 (setq pos (text-property-any pos (point-max) 'csv--jit t)))
   1600       (jit-lock-refontify
   1601        pos (setq pos (or (text-property-any pos (point-max) 'csv--jit nil)
   1602                          (point-max))))))
   1603   (csv--header-flush))
   1604 
   1605 (defun csv--ellipsis-width ()
   1606   (let ((ellipsis
   1607          (when standard-display-table
   1608            (display-table-slot standard-display-table
   1609                                'selective-display))))
   1610     (if ellipsis (length ellipsis) 3)))
   1611 
   1612 (defun csv-align--cursor-truncated (window oldpos dir)
   1613   ;; FIXME: Neither the `entered' nor the `left' event are guaranteed
   1614   ;; to be sent, and for the `left' case, even when we do get called,
   1615   ;; it may be unclear where the revealed text was (it's somewhere around
   1616   ;; `oldpos', but that position can be stale).
   1617   ;; Worse, if we have several windows displaying the buffer, when one
   1618   ;; cursor leaves we may need to keep the text revealed because of
   1619   ;; another window's cursor.
   1620   (let* ((prop (if (eq dir 'entered) 'invisible 'csv--revealed))
   1621          (pos (cond
   1622                ((eq dir 'entered) (window-point window))
   1623                (t (max (point-min)
   1624                        (min (point-max)
   1625                             (or oldpos (window-point window)))))))
   1626          (start (cond
   1627                  ((and (> pos (point-min))
   1628                        (eq (get-text-property (1- pos) prop) 'csv-truncate))
   1629                   (or (previous-single-property-change pos prop) (point-min)))
   1630                  (t pos)))
   1631          (end (if (eq (get-text-property pos prop) 'csv-truncate)
   1632                   (or (next-single-property-change pos prop) (point-max))
   1633                 pos)))
   1634     (unless (eql start end)
   1635       (with-silent-modifications
   1636         (put-text-property start end
   1637                            (if (eq dir 'entered) 'csv--revealed 'invisible)
   1638                            'csv-truncate)
   1639         (remove-text-properties start end (list prop))))))
   1640 
   1641 (defun csv--jit-align (beg end)
   1642   (save-excursion
   1643     ;; This is run with inhibit-modification-hooks set, so the overlays'
   1644     ;; modification-hook doesn't work :-(
   1645     (and csv--header-line
   1646          (<= beg (overlay-end csv--header-line))
   1647          (>= end (overlay-start csv--header-line))
   1648          (csv--header-flush))
   1649     ;; First, round up to a whole number of lines.
   1650     (goto-char end)
   1651     (unless (bolp) (forward-line 1) (setq end (point)))
   1652     (goto-char beg)
   1653     (unless (bolp) (forward-line 1) (setq beg (point)))
   1654     (csv--jit-unalign beg end)
   1655     (put-text-property beg end 'csv--jit t)
   1656 
   1657     (pcase-let* ((`(,column-widths ,field-widths) (csv--column-widths beg end))
   1658                  (changed (csv--jit-merge-columns column-widths))
   1659                  (ellipsis-width (csv--ellipsis-width)))
   1660       (when changed
   1661         ;; Do it after the current redisplay is over.
   1662         (run-with-timer jit-lock-context-time nil #'csv--jit-flush beg end))
   1663 
   1664       ;; Align fields:
   1665       (goto-char beg)
   1666       (while (< (point) end)
   1667 	(unless (csv-not-looking-at-record)
   1668           (let ((w csv--jit-columns)
   1669                 (widths-config csv--config-column-widths)
   1670                 (column 0))      ;Desired position of left-side of this column.
   1671             (while (and w (not (eolp)))
   1672               (let* ((field-beg (point))
   1673                      (width-config (pop widths-config))
   1674                      (align-padding (if (bolp) 0 csv-align-padding))
   1675                      (left-padding 0) (right-padding 0)
   1676                      (field-width (pop field-widths))
   1677                      (column-width
   1678                       (min (max csv-align-min-width
   1679                                 (car (pop w)))
   1680                            (or width-config
   1681                                ;; Don't apply csv-align-max-width
   1682                                ;; to the last field!
   1683                                (if w csv-align-max-width
   1684                                  most-positive-fixnum))))
   1685                      (x (- column-width field-width)) ; Required padding.
   1686                      (truncate nil))
   1687                 (csv-end-of-field)
   1688                 ;; beg = beginning of current field
   1689                 ;; end = (point) = end of current field
   1690                 (when (< x 0)
   1691                   (setq truncate (max column
   1692                                       (+ column column-width
   1693                                          align-padding (- ellipsis-width))))
   1694                   (setq x 0))
   1695                 ;; Compute required padding:
   1696                 (pcase csv-align-style
   1697                   ('left
   1698                    ;; Left align -- pad on the right:
   1699                    (setq left-padding align-padding
   1700                          right-padding x))
   1701                   ('right
   1702                    ;; Right align -- pad on the left:
   1703                    (setq left-padding (+ align-padding x)))
   1704                   ('auto
   1705                    ;; Auto align -- left align text, right align numbers:
   1706                    (if (string-match "\\`[-+.[:digit:]]+\\'"
   1707                                      (buffer-substring field-beg (point)))
   1708                        ;; Right align -- pad on the left:
   1709                        (setq left-padding (+ align-padding x))
   1710                      ;; Left align -- pad on the right:
   1711                      (setq left-padding align-padding
   1712                            right-padding x)))
   1713                   ('centre
   1714                    ;; Centre -- pad on both left and right:
   1715                    (let ((y (/ x 2)))   ; truncated integer quotient
   1716                      (setq left-padding (+ align-padding y)
   1717                            right-padding (- x y)))))
   1718 
   1719                 (cond
   1720 
   1721                  ((or (memq 'csv buffer-invisibility-spec)
   1722                       ;; For TSV, hidden or not doesn't make much difference,
   1723                       ;; but the behavior is slightly better when we "hide"
   1724                       ;; the TABs with a `display' property than if we add
   1725                       ;; before/after-strings.
   1726                       (tsv--mode-p))
   1727 
   1728                   ;; Hide separators...
   1729                   ;; Merge right-padding from previous field
   1730                   ;; with left-padding from this field:
   1731                   (if (zerop column)
   1732                       (when (> left-padding 0)
   1733                         ;; Display spaces before first field
   1734                         ;; by overlaying first character:
   1735 			(csv--make-overlay
   1736 			 field-beg (1+ field-beg) nil nil nil
   1737 			 `(before-string ,(make-string left-padding ?\ )
   1738 			                 csv--jit t)))
   1739                     ;; Display separator as spaces:
   1740                     (with-silent-modifications
   1741                       (put-text-property
   1742                        (1- field-beg) field-beg
   1743                        'display `(space :align-to
   1744                                         ,(+ left-padding column))))))
   1745 
   1746                  (t ;; Do not hide separators...
   1747                   (let ((overlay (csv--make-overlay field-beg (point)
   1748                                                     nil nil t
   1749                                                     '(csv--jit t))))
   1750                     (when (> left-padding 0) ; Pad on the left.
   1751                       ;; Display spaces before field:
   1752                       (overlay-put overlay 'before-string
   1753                                    (make-string left-padding ?\ )))
   1754                     (unless (eolp)
   1755                       (if (> right-padding 0) ; Pad on the right.
   1756                           ;; Display spaces after field:
   1757                           (overlay-put
   1758                            overlay
   1759                            'after-string (make-string right-padding ?\ )))))))
   1760                 (setq column (+ column column-width align-padding))
   1761                 ;; Do it after applying the property, so `move-to-column' can
   1762                 ;; take it into account.
   1763                 (when truncate
   1764                   (let ((trunc-pos
   1765                          (save-excursion
   1766                            ;; ¡¡ BIG UGLY HACK !!
   1767                            ;; `current-column' and `move-to-column' count
   1768                            ;; text hidden with an ellipsis "as if" it were
   1769                            ;; fully visible, which is completely wrong here,
   1770                            ;; so circumvent this by temporarily pretending
   1771                            ;; that `csv-truncate' is fully invisible (which
   1772                            ;; isn't quite right either, but should work
   1773                            ;; just well enough for us here).
   1774                            (let ((buffer-invisibility-spec
   1775                                   buffer-invisibility-spec))
   1776                              (add-to-invisibility-spec 'csv-truncate)
   1777                              (move-to-column truncate))
   1778                            (point))))
   1779                     (put-text-property trunc-pos (point)
   1780                                        'invisible 'csv-truncate)
   1781                     (when (> (- (point) trunc-pos) 1)
   1782                       ;; Arrange to temporarily untruncate the string when
   1783                       ;; cursor moves into it.
   1784                       ;; FIXME: This only works if
   1785                       ;; `global-disable-point-adjustment' is non-nil!
   1786                       ;; Arguably this should be fixed by making
   1787                       ;; point-adjustment code pay attention to
   1788                       ;; cursor-sensor-functions!
   1789                       (put-text-property
   1790                        (1+ trunc-pos) (point)
   1791                        'cursor-sensor-functions
   1792                        (list #'csv-align--cursor-truncated)))))
   1793                 (unless (eolp) (forward-char)) ; Skip separator.
   1794                 ))))
   1795 	(forward-line)))
   1796     `(jit-lock-bounds ,beg . ,end)))
   1797 
   1798 (define-minor-mode csv-align-mode
   1799   "Align columns on the fly."
   1800   :global nil
   1801   (csv-unalign-fields nil (point-min) (point-max)) ;Just in case.
   1802   (cond
   1803    (csv-align-mode
   1804     (add-to-invisibility-spec '(csv-truncate . t))
   1805     (kill-local-variable 'csv--jit-columns)
   1806     (cursor-sensor-mode 1)
   1807     (when (fboundp 'header-line-indent-mode)
   1808       (header-line-indent-mode))
   1809     (jit-lock-register #'csv--jit-align)
   1810     (jit-lock-refontify))
   1811    (t
   1812     (remove-from-invisibility-spec '(csv-truncate . t))
   1813     (jit-lock-unregister #'csv--jit-align)
   1814     (csv--jit-unalign (point-min) (point-max))))
   1815   (csv--header-flush))
   1816 
   1817 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   1818 ;;;  Separator guessing
   1819 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
   1820 
   1821 (defvar csv--preferred-separators
   1822   '(?, ?\; ?\t)
   1823   "Preferred separator characters in case of a tied score.")
   1824 
   1825 (defun csv-guess-set-separator ()
   1826   "Guess and set the CSV separator of the current buffer.
   1827 
   1828 Add it to the mode hook to have CSV mode guess and set the
   1829 separator automatically when visiting a buffer:
   1830 
   1831   (add-hook \\='csv-mode-hook \\='csv-guess-set-separator)"
   1832   (interactive)
   1833   (let ((sep (csv-guess-separator
   1834               (buffer-substring-no-properties
   1835                (point-min)
   1836                ;; We're probably only going to look at the first 2048
   1837                ;; or so chars, but take more than we probably need to
   1838                ;; minimize the chance of breaking the input in the
   1839                ;; middle of a (long) row.
   1840                (min 8192 (point-max)))
   1841               2048)))
   1842     (when sep
   1843       (csv-set-separator sep))))
   1844 
   1845 (defun csv-guess-separator (text &optional cutoff)
   1846   "Return a guess of which character is the CSV separator in TEXT."
   1847   (let ((best-separator nil)
   1848         (best-score 0))
   1849     (dolist (candidate (csv--separator-candidates text cutoff))
   1850       (let ((candidate-score
   1851              (csv--separator-score candidate text cutoff)))
   1852         (when (or (> candidate-score best-score)
   1853                   (and (= candidate-score best-score)
   1854                        (member candidate csv--preferred-separators)))
   1855           (setq best-separator candidate)
   1856           (setq best-score candidate-score))))
   1857     best-separator))
   1858 
   1859 (defun csv--separator-candidates (text &optional cutoff)
   1860   "Return a list of candidate CSV separators in TEXT.
   1861 When CUTOFF is passed, look only at the first CUTOFF number of characters."
   1862   (let ((chars (make-hash-table)))
   1863     (dolist (c (string-to-list
   1864                 (if cutoff
   1865                     (substring text 0 (min cutoff (length text)))
   1866                   text)))
   1867       (when (and (not (gethash c chars))
   1868                  (or (= c ?\t)
   1869                      (and (not (member c '(?. ?/ ?\" ?')))
   1870                           (not (member (get-char-code-property c 'general-category)
   1871                                        '(Lu Ll Lt Lm Lo Nd Nl No Ps Pe Cc Co))))))
   1872         (puthash c t chars)))
   1873     (hash-table-keys chars)))
   1874 
   1875 (defun csv--separator-score (separator text &optional cutoff)
   1876   "Return a score on how likely SEPARATOR is a separator in TEXT.
   1877 
   1878 When CUTOFF is passed, stop the calculation at the next whole
   1879 line after having read CUTOFF number of characters.
   1880 
   1881 The scoring is based on the idea that most CSV data is tabular,
   1882 i.e. separators should appear equally often on each line.
   1883 Furthermore, more commonly appearing characters are scored higher
   1884 than those who appear less often.
   1885 
   1886 Adapted from the paper \"Wrangling Messy CSV Files by Detecting
   1887 Row and Type Patterns\" by Gerrit J.J. van den Burg , Alfredo
   1888 Nazábal, and Charles Sutton: https://arxiv.org/abs/1811.11242."
   1889   (let ((groups
   1890          (with-temp-buffer
   1891            (csv-set-separator separator)
   1892            (save-excursion
   1893              (insert text))
   1894            (let ((groups (make-hash-table))
   1895                  (chars-read 0))
   1896              (while (and (/= (point) (point-max))
   1897                          (or (not cutoff)
   1898                              (< chars-read cutoff)))
   1899                (let* ((lep (line-end-position))
   1900                       (nfields (length (csv--collect-fields lep))))
   1901                  (cl-incf (gethash nfields groups 0))
   1902                  (cl-incf chars-read (- lep (point)))
   1903                  (goto-char (+ lep 1))))
   1904              groups)))
   1905         (sum 0))
   1906     (maphash
   1907      (lambda (length num)
   1908        (cl-incf sum (* num (/ (- length 1) (float length)))))
   1909      groups)
   1910     (let ((unique-groups (hash-table-count groups)))
   1911       (if (= 0 unique-groups)
   1912           0
   1913         (/ sum unique-groups)))))
   1914 
   1915 ;;; TSV support
   1916 
   1917 ;; Since "the" CSV format is really a bunch of different formats, it includes
   1918 ;; TSV as a subcase, but this subcase is sufficiently interesting that it has
   1919 ;; its own mime-type and mostly standard file extension, also it suffers
   1920 ;; less from the usual quoting problems of CSV (because the only problematic
   1921 ;; chars are LF and TAB, really, which are much less common inside fields than
   1922 ;; commas, space, and semi-colons) so it's "better behaved".
   1923 
   1924 (defvar tsv-mode-syntax-table
   1925   ;; Inherit from `text-mode-syntax-table' rather than from
   1926   ;; `csv-mode-syntax-table' so as not to inherit the
   1927   ;; `csv-field-quotes' settings.
   1928   (let ((st (make-syntax-table text-mode-syntax-table)))
   1929     st))
   1930 
   1931 (defvar tsv-mode-map
   1932   (let ((map (make-sparse-keymap)))
   1933     ;; In `tsv-mode', the `csv-invisibility-default/csv-toggle-invisibility'
   1934     ;; business doesn't make much sense.
   1935     (define-key map [remap csv-toggle-invisibility] #'undefined)
   1936     map))
   1937 
   1938 ;;;###autoload
   1939 (add-to-list 'auto-mode-alist '("\\.tsv\\'" . tsv-mode))
   1940 
   1941 (defun tsv--mode-p ()
   1942   (equal csv-separator-chars '(?\t)))
   1943 
   1944 ;;;###autoload
   1945 (define-derived-mode tsv-mode csv-mode "TSV"
   1946   "Major mode for editing files of tab-separated value type."
   1947   :group 'CSV
   1948   ;; In TSV we know TAB is the only possible separator.
   1949   (setq-local csv-separators '("\t"))
   1950   ;; FIXME: Copy&pasted from the `:set'ter of csv-separators!
   1951   (setq-local csv-separator-chars '(?\t))
   1952   (setq-local csv--skip-chars "^\n\t")
   1953   (setq-local csv-separator-regexp "\t")
   1954   (setq-local csv-font-lock-keywords
   1955 	      ;; NB: csv-separator-face variable evaluates to itself.
   1956 	      `((,csv-separator-regexp (0 'csv-separator-face))))
   1957 
   1958   ;; According to wikipedia, TSV doesn't use quotes but uses backslash escapes
   1959   ;; of the form \n, \t, \r, and \\ instead.
   1960   (setq-local csv-field-quotes nil))
   1961 
   1962 
   1963 (provide 'csv-mode)
   1964 
   1965 ;;; csv-mode.el ends here