]> code.delx.au - gnu-emacs-elpa/blob - packages/csv-mode/csv-mode.el
Add 'packages/async/' from commit '2a40355c3328e57102a9648c9108e19d67727dc1'
[gnu-emacs-elpa] / packages / csv-mode / csv-mode.el
1 ;;; csv-mode.el --- Major mode for editing comma/char separated values -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2003, 2004, 2012, 2013, 2014, 2015 Free Software Foundation, Inc
4
5 ;; Author: Francis J. Wright <F.J.Wright at qmul.ac.uk>
6 ;; Time-stamp: <23 August 2004>
7 ;; URL: http://centaur.maths.qmul.ac.uk/Emacs/
8 ;; Version: 1.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 <http://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 ;; finds with prefix ".csv" to `csv-mode' in `auto-mode-alist'.
29
30 ;; In CSV mode, the following commands are available:
31
32 ;; - C-c C-s (`csv-sort-fields') and C-c C-n (`csv-sort-numeric-fields')
33 ;; respectively sort lexicographically and numerically on a
34 ;; specified field or column.
35
36 ;; - C-c C-r (`csv-reverse-region') reverses the order. (These
37 ;; commands are based closely on, and use, code in `sort.el'.)
38
39 ;; - C-c C-k (`csv-kill-fields') and C-c C-y (`csv-yank-fields') kill
40 ;; and yank fields or columns, although they do not use the normal
41 ;; kill ring. C-c C-k can kill more than one field at once, but
42 ;; multiple killed fields can be yanked only as a fixed group
43 ;; equivalent to a single field.
44
45 ;; - C-c C-a (`csv-align-fields') aligns fields into columns
46
47 ;; - C-c C-u (`csv-unalign-fields') undoes such alignment; separators
48 ;; can be hidden within aligned records.
49
50 ;; - C-c C-t (`csv-transpose') interchanges rows and columns. For
51 ;; details, see the documentation for the individual commands.
52
53 ;; CSV mode can recognize fields separated by any of several single
54 ;; characters, specified by the value of the customizable user option
55 ;; `csv-separators'. CSV data fields can be delimited by quote
56 ;; characters (and must if they contain separator characters). This
57 ;; implementation supports quoted fields, where the quote characters
58 ;; allowed are specified by the value of the customizable user option
59 ;; `csv-field-quotes'. By default, the only separator is a comma and
60 ;; the only field quote is a double quote. These user options can be
61 ;; changed ONLY by customizing them, e.g. via M-x customize-variable.
62
63 ;; CSV mode commands ignore blank lines and comment lines beginning
64 ;; with the value of the buffer local variable `csv-comment-start',
65 ;; which by default is #. The user interface is similar to that of
66 ;; the standard commands `sort-fields' and `sort-numeric-fields', but
67 ;; see the major mode documentation below.
68
69 ;; The global minor mode `csv-field-index-mode' provides display of
70 ;; the current field index in the mode line, cf. `line-number-mode'
71 ;; and `column-number-mode'. It is on by default.
72
73 ;;; Installation:
74
75 ;; Put this file somewhere that Emacs can find it (i.e. in one of the
76 ;; directories in your `load-path' such as `site-lisp'), optionally
77 ;; byte-compile it (recommended), and put this in your .emacs file:
78 ;;
79 ;; (add-to-list 'auto-mode-alist '("\\.[Cc][Ss][Vv]\\'" . csv-mode))
80 ;; (autoload 'csv-mode "csv-mode"
81 ;; "Major mode for editing comma-separated value files." t)
82
83 ;;; History:
84
85 ;; Begun on 15 November 2003 to provide lexicographic sorting of
86 ;; simple CSV data by field and released as csv.el. Facilities to
87 ;; kill multiple fields and customize separator added on 9 April 2004.
88 ;; Converted to a major mode and renamed csv-mode.el on 10 April 2004,
89 ;; partly at the suggestion of Stefan Monnier <monnier at
90 ;; IRO.UMontreal.CA> to avoid conflict with csv.el by Ulf Jasper.
91 ;; Field alignment, comment support and CSV mode customization group
92 ;; added on 1 May 2004. Support for index ranges added on 6 June
93 ;; 2004. Multiple field separators added on 12 June 2004.
94 ;; Transposition added on 22 June 2004. Separator invisibility added
95 ;; on 23 June 2004.
96
97 ;;; See also:
98
99 ;; the standard GNU Emacs 21 packages align.el, which will align
100 ;; columns within a region, and delim-col.el, which helps to prettify
101 ;; columns in a text region or rectangle;
102
103 ;; csv.el by Ulf Jasper <ulf.jasper at web.de>, which provides
104 ;; functions for reading/parsing comma-separated value files and is
105 ;; available at http://de.geocities.com/ulf_jasper/emacs.html (and in
106 ;; the gnu.emacs.sources archives).
107
108 ;;; To do (maybe):
109
110 ;; Make separators and quotes buffer-local and locally settable.
111 ;; Support (La)TeX tables: set separator and comment; support record
112 ;; end string.
113 ;; Convert comma-separated to space- or tab-separated.
114
115 ;;; Code:
116
117 (defgroup CSV nil
118 "Major mode for editing files of comma-separated value type."
119 :group 'convenience)
120
121 (defvar csv-separator-chars nil
122 "Field separators as a list of character.
123 Set by customizing `csv-separators' -- do not set directly!")
124
125 (defvar csv-separator-regexp nil
126 "Regexp to match a field separator.
127 Set by customizing `csv-separators' -- do not set directly!")
128
129 (defvar csv--skip-regexp nil
130 "Regexp used by `skip-chars-forward' etc. to skip fields.
131 Set by customizing `csv-separators' -- do not set directly!")
132
133 (defvar csv-font-lock-keywords nil
134 "Font lock keywords to highlight the field separators in CSV mode.
135 Set by customizing `csv-separators' -- do not set directly!")
136
137 (defcustom csv-separators '("," "\t")
138 "Field separators: a list of *single-character* strings.
139 For example: (\",\"), the default, or (\",\" \";\" \":\").
140 Neighbouring fields may be separated by any one of these characters.
141 The first is used when inserting a field separator into the buffer.
142 All must be different from the field quote characters, `csv-field-quotes'."
143 ;; Suggested by Eckhard Neber <neber@mwt.e-technik.uni-ulm.de>
144 :type '(repeat string)
145 ;; FIXME: Character would be better, but in Emacs 21.3 does not display
146 ;; correctly in a customization buffer.
147 :set (lambda (variable value)
148 (mapc (lambda (x)
149 (if (/= (length x) 1)
150 (error "Non-single-char string %S" x))
151 (if (and (boundp 'csv-field-quotes)
152 (member x csv-field-quotes))
153 (error "%S is already a quote" x)))
154 value)
155 (custom-set-default variable value)
156 (setq csv-separator-chars (mapcar 'string-to-char value)
157 csv--skip-regexp (apply 'concat "^\n" csv-separators)
158 csv-separator-regexp (apply 'concat `("[" ,@value "]"))
159 csv-font-lock-keywords
160 ;; NB: csv-separator-face variable evaluates to itself.
161 `((,csv-separator-regexp (0 'csv-separator-face))))))
162
163 (defcustom csv-field-quotes '("\"")
164 "Field quotes: a list of *single-character* strings.
165 For example: (\"\\\"\"), the default, or (\"\\\"\" \"'\" \"`\").
166 A field can be delimited by a pair of any of these characters.
167 All must be different from the field separators, `csv-separators'."
168 :type '(repeat string)
169 ;; Character would be better, but in Emacs 21 does not display
170 ;; correctly in a customization buffer.
171 :set (lambda (variable value)
172 (mapc (lambda (x)
173 (if (/= (length x) 1)
174 (error "Non-single-char string %S" x))
175 (if (member x csv-separators)
176 (error "%S is already a separator" x)))
177 value)
178 (when (boundp 'csv-mode-syntax-table)
179 ;; FIRST remove old quote syntax:
180 (with-syntax-table text-mode-syntax-table
181 (mapc (lambda (x)
182 (modify-syntax-entry
183 (string-to-char x)
184 (string (char-syntax (string-to-char x)))
185 ;; symbol-value to avoid compiler warning:
186 (symbol-value 'csv-mode-syntax-table)))
187 csv-field-quotes))
188 ;; THEN set new quote syntax:
189 (csv-set-quote-syntax value))
190 ;; BEFORE setting new value of `csv-field-quotes':
191 (custom-set-default variable value)))
192
193 (defun csv-set-quote-syntax (field-quotes)
194 "Set syntax for field quote characters FIELD-QUOTES to be \"string\".
195 FIELD-QUOTES should be a list of single-character strings."
196 (mapc (lambda (x)
197 (modify-syntax-entry
198 (string-to-char x) "\""
199 ;; symbol-value to avoid compiler warning:
200 (symbol-value 'csv-mode-syntax-table)))
201 field-quotes))
202
203 (defvar csv-comment-start nil
204 "String that starts a comment line, or nil if no comment syntax.
205 Such comment lines are ignored by CSV mode commands.
206 This variable is buffer local\; its default value is that of
207 `csv-comment-start-default'. It is set by the function
208 `csv-set-comment-start' -- do not set it directly!")
209
210 (make-variable-buffer-local 'csv-comment-start)
211
212 (defcustom csv-comment-start-default "#"
213 "String that starts a comment line, or nil if no comment syntax.
214 Such comment lines are ignored by CSV mode commands.
215 Default value of buffer-local variable `csv-comment-start'.
216 Changing this variable does not affect any existing CSV mode buffer."
217 :type '(choice (const :tag "None" nil) string)
218 :set (lambda (variable value)
219 (custom-set-default variable value)
220 (set-default 'csv-comment-start value)))
221
222 (defcustom csv-align-style 'left
223 "Aligned field style: one of 'left, 'centre, 'right or 'auto.
224 Alignment style used by `csv-align-fields'.
225 Auto-alignment means left align text and right align numbers."
226 :type '(choice (const left) (const centre)
227 (const right) (const auto)))
228
229 (defcustom csv-align-padding 1
230 "Aligned field spacing: must be a positive integer.
231 Number of spaces used by `csv-align-fields' after separators."
232 :type 'integer)
233
234 (defcustom csv-header-lines 0
235 "Header lines to skip when setting region automatically."
236 :type 'integer)
237
238 (defcustom csv-invisibility-default t
239 "If non-nil, make separators in aligned records invisible."
240 :type 'boolean)
241
242 (defface csv-separator-face
243 '((t :inherit escape-glyph))
244 "CSV mode face used to highlight separators.")
245 \f
246 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
247 ;;; Mode definition, key bindings and menu
248 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
249
250
251 (defconst csv-mode-line-format
252 '(csv-field-index-string ("" csv-field-index-string))
253 "Mode line format string for CSV mode.")
254
255 (defvar csv-mode-map
256 (let ((map (make-sparse-keymap)))
257 (define-key map [(control ?c) (control ?v)] 'csv-toggle-invisibility)
258 (define-key map [(control ?c) (control ?t)] 'csv-transpose)
259 (define-key map [(control ?c) (control ?c)] 'csv-set-comment-start)
260 (define-key map [(control ?c) (control ?u)] 'csv-unalign-fields)
261 (define-key map [(control ?c) (control ?a)] 'csv-align-fields)
262 (define-key map [(control ?c) (control ?z)] 'csv-yank-as-new-table)
263 (define-key map [(control ?c) (control ?y)] 'csv-yank-fields)
264 (define-key map [(control ?c) (control ?k)] 'csv-kill-fields)
265 (define-key map [(control ?c) (control ?d)] 'csv-toggle-descending)
266 (define-key map [(control ?c) (control ?r)] 'csv-reverse-region)
267 (define-key map [(control ?c) (control ?n)] 'csv-sort-numeric-fields)
268 (define-key map [(control ?c) (control ?s)] 'csv-sort-fields)
269 map))
270
271 ;;;###autoload
272 (define-derived-mode csv-mode text-mode "CSV"
273 "Major mode for editing files of comma-separated value type.
274
275 CSV mode is derived from `text-mode', and runs `text-mode-hook' before
276 running `csv-mode-hook'. It turns `auto-fill-mode' off by default.
277 CSV mode can be customized by user options in the CSV customization
278 group. The separators are specified by the value of `csv-separators'.
279
280 CSV mode commands ignore blank lines and comment lines beginning with
281 the value of `csv-comment-start', which delimit \"paragraphs\".
282 \"Sexp\" is re-interpreted to mean \"field\", so that `forward-sexp'
283 \(\\[forward-sexp]), `kill-sexp' (\\[kill-sexp]), etc. all apply to fields.
284 Standard comment commands apply, such as `comment-dwim' (\\[comment-dwim]).
285
286 If `font-lock-mode' is enabled then separators, quoted values and
287 comment lines are highlighted using respectively `csv-separator-face',
288 `font-lock-string-face' and `font-lock-comment-face'.
289
290 The user interface (UI) for CSV mode commands is similar to that of
291 the standard commands `sort-fields' and `sort-numeric-fields', except
292 that if there is no prefix argument then the UI prompts for the field
293 index or indices. In `transient-mark-mode' only: if the region is not
294 set then the UI attempts to set it to include all consecutive CSV
295 records around point, and prompts for confirmation; if there is no
296 prefix argument then the UI prompts for it, offering as a default the
297 index of the field containing point if the region was not set
298 explicitly. The region set automatically is delimited by blank lines
299 and comment lines, and the number of header lines at the beginning of
300 the region given by the value of `csv-header-lines' are skipped.
301
302 Sort order is controlled by `csv-descending'.
303
304 CSV mode provides the following specific keyboard key bindings:
305
306 \\{csv-mode-map}"
307 (turn-off-auto-fill)
308 ;; Set syntax for field quotes:
309 (csv-set-quote-syntax csv-field-quotes)
310 ;; Make sexp functions apply to fields:
311 (set (make-local-variable 'forward-sexp-function) 'csv-forward-field)
312 (csv-set-comment-start csv-comment-start)
313 (setq
314 ;; Font locking -- separator plus syntactic:
315 font-lock-defaults '(csv-font-lock-keywords)
316 buffer-invisibility-spec csv-invisibility-default)
317 ;; Mode line to support `csv-field-index-mode':
318 (set (make-local-variable 'mode-line-position)
319 (pcase mode-line-position
320 (`(,(or (pred consp) (pred stringp)) . ,_)
321 `(,@mode-line-position ,csv-mode-line-format))
322 (_ `("" ,mode-line-position ,csv-mode-line-format))))
323 (set (make-local-variable 'truncate-lines) t)
324 ;; Enable or disable `csv-field-index-mode' (could probably do this
325 ;; a bit more efficiently):
326 (csv-field-index-mode (symbol-value 'csv-field-index-mode)))
327
328 (defun csv-set-comment-start (string)
329 "Set comment start for this CSV mode buffer to STRING.
330 It must be either a string or nil."
331 (interactive
332 (list (edit-and-eval-command
333 "Comment start (string or nil): " csv-comment-start)))
334 ;; Paragraph means a group of contiguous records:
335 (set (make-local-variable 'paragraph-separate) "[:space:]*$") ; White space.
336 (set (make-local-variable 'paragraph-start) "\n");Must include \n explicitly!
337 ;; Remove old comment-start/end if available
338 (with-syntax-table text-mode-syntax-table
339 (when comment-start
340 (modify-syntax-entry (string-to-char comment-start)
341 (string (char-syntax (string-to-char comment-start)))
342 csv-mode-syntax-table))
343 (modify-syntax-entry ?\n
344 (string (char-syntax ?\n))
345 csv-mode-syntax-table))
346 (when string
347 (setq paragraph-separate (concat paragraph-separate "\\|" string)
348 paragraph-start (concat paragraph-start "\\|" string))
349 (set (make-local-variable 'comment-start) string)
350 (modify-syntax-entry
351 (string-to-char string) "<" csv-mode-syntax-table)
352 (modify-syntax-entry ?\n ">" csv-mode-syntax-table))
353 (setq csv-comment-start string))
354
355 ;;;###autoload
356 (add-to-list 'auto-mode-alist '("\\.[Cc][Ss][Vv]\\'" . csv-mode))
357
358 (defvar csv-descending nil
359 "If non-nil, CSV mode sort functions sort in order of descending sort key.
360 Usually they sort in order of ascending sort key.")
361
362 (defun csv-toggle-descending ()
363 "Toggle `csv-descending'."
364 (interactive)
365 (setq csv-descending (not csv-descending))
366 (message "Sort order is %sscending" (if csv-descending "de" "a")))
367
368 (defun csv-toggle-invisibility ()
369 "Toggle `buffer-invisibility-spec'."
370 (interactive)
371 (setq buffer-invisibility-spec (not buffer-invisibility-spec))
372 (message "Separators in aligned records will be %svisible \
373 \(after re-aligning if soft\)"
374 (if buffer-invisibility-spec "in" ""))
375 (redraw-frame (selected-frame)))
376
377 (easy-menu-define
378 csv-menu
379 csv-mode-map
380 "CSV major mode menu keymap"
381 '("CSV"
382 ["Sort By Field Lexicographically" csv-sort-fields :active t
383 :help "Sort lines in region lexicographically by the specified field"]
384 ["Sort By Field Numerically" csv-sort-numeric-fields :active t
385 :help "Sort lines in region numerically by the specified field"]
386 ["Reverse Order of Lines" csv-reverse-region :active t
387 :help "Reverse the order of the lines in the region"]
388 ["Use Descending Sort Order" csv-toggle-descending :active t
389 :style toggle :selected csv-descending
390 :help "If selected, use descending order when sorting"]
391 "--"
392 ["Kill Fields (Columns)" csv-kill-fields :active t
393 :help "Kill specified fields of each line in the region"]
394 ["Yank Fields (Columns)" csv-yank-fields :active t
395 :help "Yank killed fields as specified field of each line in region"]
396 ["Yank As New Table" csv-yank-as-new-table :active t
397 :help "Yank killed fields as a new table at point"]
398 ["Align Fields into Columns" csv-align-fields :active t
399 :help "Align the start of every field of each line in the region"]
400 ["Unalign Columns into Fields" csv-unalign-fields :active t
401 :help "Undo soft alignment and optionally remove redundant white space"]
402 ["Transpose Rows and Columns" csv-transpose :active t
403 :help "Rewrite rows (which may have different lengths) as columns"]
404 "--"
405 ["Forward Field" forward-sexp :active t
406 :help "Move forward across one field\; with ARG, do it that many times"]
407 ["Backward Field" backward-sexp :active t
408 :help "Move backward across one field\; with ARG, do it that many times"]
409 ["Kill Field Forward" kill-sexp :active t
410 :help "Kill field following cursor\; with ARG, do it that many times"]
411 ["Kill Field Backward" backward-kill-sexp :active t
412 :help "Kill field preceding cursor\; with ARG, do it that many times"]
413 "--"
414 ("Alignment Style"
415 ["Left" (setq csv-align-style 'left) :active t
416 :style radio :selected (eq csv-align-style 'left)
417 :help "If selected, `csv-align-fields' left aligns fields"]
418 ["Centre" (setq csv-align-style 'centre) :active t
419 :style radio :selected (eq csv-align-style 'centre)
420 :help "If selected, `csv-align-fields' centres fields"]
421 ["Right" (setq csv-align-style 'right) :active t
422 :style radio :selected (eq csv-align-style 'right)
423 :help "If selected, `csv-align-fields' right aligns fields"]
424 ["Auto" (setq csv-align-style 'auto) :active t
425 :style radio :selected (eq csv-align-style 'auto)
426 :help "\
427 If selected, `csv-align-fields' left aligns text and right aligns numbers"]
428 )
429 ["Show Current Field Index" csv-field-index-mode :active t
430 :style toggle :selected csv-field-index-mode
431 :help "If selected, display current field index in mode line"]
432 ["Make Separators Invisible" csv-toggle-invisibility :active t
433 :style toggle :selected buffer-invisibility-spec
434 :help "If selected, separators in aligned records are invisible"]
435 ["Set Buffer's Comment Start" csv-set-comment-start :active t
436 :help "Set comment start string for this buffer"]
437 ["Customize CSV Mode" (customize-group 'CSV) :active t
438 :help "Open a customization buffer to change CSV mode options"]
439 ))
440
441 (require 'sort)
442
443 (defsubst csv-not-looking-at-record ()
444 "Return t if looking at blank or comment line, nil otherwise.
445 Assumes point is at beginning of line."
446 (looking-at paragraph-separate))
447
448 (defun csv-interactive-args (&optional type)
449 "Get arg or field(s) and region interactively, offering sensible defaults.
450 Signal an error if the buffer is read-only.
451 If TYPE is noarg then return a list `(beg end)'.
452 Otherwise, return a list `(arg beg end)', where arg is:
453 the raw prefix argument by default\;
454 a single field index if TYPE is single\;
455 a list of field indices or index ranges if TYPE is multiple.
456 Field defaults to the current prefix arg\; if not set, prompt user.
457
458 A field index list consists of positive or negative integers or ranges,
459 separated by any non-integer characters. A range has the form m-n,
460 where m and n are positive or negative integers, m < n, and n defaults
461 to the last field index if omitted.
462
463 In transient mark mode, if the mark is not active then automatically
464 select and highlight CSV records around point, and query user.
465 The default field when read interactively is the current field."
466 ;; Must be run interactively to activate mark!
467 (let* ((arg current-prefix-arg) (default-field 1)
468 (region
469 (if (not (use-region-p))
470 ;; Set region automatically:
471 (save-excursion
472 (if arg
473 (beginning-of-line)
474 (let ((lbp (line-beginning-position)))
475 (while (re-search-backward csv-separator-regexp lbp 1)
476 ;; Move as far as possible, i.e. to beginning of line.
477 (setq default-field (1+ default-field)))))
478 (if (csv-not-looking-at-record)
479 (error "Point must be within CSV records"))
480 (let ((startline (point)))
481 ;; Set mark at beginning of region:
482 (while (not (or (bobp) (csv-not-looking-at-record)))
483 (forward-line -1))
484 (if (csv-not-looking-at-record) (forward-line 1))
485 ;; Skip header lines:
486 (forward-line csv-header-lines)
487 (set-mark (point)) ; OK since in save-excursion
488 ;; Move point to end of region:
489 (goto-char startline)
490 (beginning-of-line)
491 (while (not (or (eobp) (csv-not-looking-at-record)))
492 (forward-line 1))
493 ;; Show mark briefly if necessary:
494 (unless (and (pos-visible-in-window-p)
495 (pos-visible-in-window-p (mark)))
496 (exchange-point-and-mark)
497 (sit-for 1)
498 (exchange-point-and-mark))
499 (or (y-or-n-p "Region OK? ")
500 (error "Action aborted by user"))
501 (message nil) ; clear y-or-n-p message
502 (list (region-beginning) (region-end))))
503 ;; Use region set by user:
504 (list (region-beginning) (region-end)))))
505 (setq default-field (number-to-string default-field))
506 (cond
507 ((eq type 'multiple)
508 (if arg
509 ;; Ensure that field is a list:
510 (or (consp arg)
511 (setq arg (list (prefix-numeric-value arg))))
512 ;; Read field interactively, ignoring non-integers:
513 (setq arg
514 (mapcar
515 (lambda (x)
516 (if (string-match "-" x 1) ; not first character
517 ;; Return a range as a pair - the cdr may be nil:
518 (let ((m (substring x 0 (match-beginning 0)))
519 (n (substring x (match-end 0))))
520 (cons (car (read-from-string m))
521 (and (not (string= n ""))
522 (car (read-from-string n)))))
523 ;; Return a number as a number:
524 (car (read-from-string x))))
525 (split-string
526 (read-string
527 "Fields (sequence of integers or ranges): " default-field)
528 "[^-+0-9]+")))))
529 ((eq type 'single)
530 (if arg
531 (setq arg (prefix-numeric-value arg))
532 (while (not (integerp arg))
533 (setq arg (eval-minibuffer "Field (integer): " default-field))))))
534 (if (eq type 'noarg) region (cons arg region))))
535 \f
536 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
537 ;;; Sorting by field
538 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
539
540 (defun csv-nextrecfun ()
541 "Called by `csv-sort-fields-1' with point at end of previous record.
542 It moves point to the start of the next record.
543 It should move point to the end of the buffer if there are no more records."
544 (forward-line)
545 (while (and (not (eobp)) (csv-not-looking-at-record))
546 (forward-line)))
547
548 (defun csv-sort-fields-1 (field beg end startkeyfun endkeyfun)
549 "Modified version of `sort-fields-1' that skips blank or comment lines.
550
551 FIELD is a single field index, and BEG and END specify the region to
552 sort.
553
554 STARTKEYFUN moves from the start of the record to the start of the key.
555 It may return either a non-nil value to be used as the key, or
556 else the key is the substring between the values of point after
557 STARTKEYFUN and ENDKEYFUN are called. If STARTKEYFUN is nil, the key
558 starts at the beginning of the record.
559
560 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
561 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
562 same as ENDRECFUN."
563 (let ((tbl (syntax-table)))
564 (if (zerop field) (setq field 1))
565 (unwind-protect
566 (save-excursion
567 (save-restriction
568 (narrow-to-region beg end)
569 (goto-char (point-min))
570 (set-syntax-table sort-fields-syntax-table)
571 (sort-subr csv-descending
572 'csv-nextrecfun 'end-of-line
573 startkeyfun endkeyfun)))
574 (set-syntax-table tbl))))
575
576 (defun csv-sort-fields (field beg end)
577 "Sort lines in region lexicographically by the ARGth field of each line.
578 If not set, the region defaults to the CSV records around point.
579 Fields are separated by `csv-separators' and null fields are allowed anywhere.
580 Field indices increase from 1 on the left or decrease from -1 on the right.
581 A prefix argument specifies a single field, otherwise prompt for field index.
582 Ignore blank and comment lines. The variable `sort-fold-case'
583 determines whether alphabetic case affects the sort order.
584 When called non-interactively, FIELD is a single field index\;
585 BEG and END specify the region to sort."
586 ;; (interactive "*P\nr")
587 (interactive (csv-interactive-args 'single))
588 (barf-if-buffer-read-only)
589 (csv-sort-fields-1 field beg end
590 (lambda () (csv-sort-skip-fields field) nil)
591 (lambda () (skip-chars-forward csv--skip-regexp))))
592
593 (defun csv-sort-numeric-fields (field beg end)
594 "Sort lines in region numerically by the ARGth field of each line.
595 If not set, the region defaults to the CSV records around point.
596 Fields are separated by `csv-separators'.
597 Null fields are allowed anywhere and sort as zeros.
598 Field indices increase from 1 on the left or decrease from -1 on the right.
599 A prefix argument specifies a single field, otherwise prompt for field index.
600 Specified non-null field must contain a number in each line of the region,
601 which may begin with \"0x\" or \"0\" for hexadecimal and octal values.
602 Otherwise, the number is interpreted according to sort-numeric-base.
603 Ignore blank and comment lines.
604 When called non-interactively, FIELD is a single field index\;
605 BEG and END specify the region to sort."
606 ;; (interactive "*P\nr")
607 (interactive (csv-interactive-args 'single))
608 (barf-if-buffer-read-only)
609 (csv-sort-fields-1 field beg end
610 (lambda ()
611 (csv-sort-skip-fields field)
612 (let* ((case-fold-search t)
613 (base
614 (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
615 (cond ((match-beginning 1)
616 (goto-char (match-end 1))
617 16)
618 ((match-beginning 2)
619 (goto-char (match-end 2))
620 8)
621 (t nil)))))
622 (string-to-number (buffer-substring (point)
623 (save-excursion
624 (forward-sexp 1)
625 (point)))
626 (or base sort-numeric-base))))
627 nil))
628
629 (defun csv-reverse-region (beg end)
630 "Reverse the order of the lines in the region.
631 This is just a CSV-mode style interface to `reverse-region', which is
632 the function that should be used non-interactively. It takes two
633 point or marker arguments, BEG and END, delimiting the region."
634 ;; (interactive "*P\nr")
635 (interactive (csv-interactive-args 'noarg))
636 (barf-if-buffer-read-only)
637 (reverse-region beg end))
638 \f
639 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
640 ;;; Moving by field
641 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
642
643 (defsubst csv-end-of-field ()
644 "Skip forward over one field."
645 (skip-chars-forward " ")
646 (if (eq (char-syntax (following-char)) ?\")
647 (goto-char (scan-sexps (point) 1)))
648 (skip-chars-forward csv--skip-regexp))
649
650 (defsubst csv-beginning-of-field ()
651 "Skip backward over one field."
652 (skip-syntax-backward " ")
653 (if (eq (char-syntax (preceding-char)) ?\")
654 (goto-char (scan-sexps (point) -1)))
655 (skip-chars-backward csv--skip-regexp))
656
657 (defun csv-forward-field (arg)
658 "Move forward across one field, cf. `forward-sexp'.
659 With ARG, do it that many times. Negative arg -N means
660 move backward across N fields."
661 (interactive "p")
662 (if (< arg 0)
663 (csv-backward-field (- arg))
664 (while (>= (setq arg (1- arg)) 0)
665 (if (or (bolp)
666 (when (and (not (eobp)) (eolp)) (forward-char) t))
667 (while (and (not (eobp)) (csv-not-looking-at-record))
668 (forward-line 1)))
669 (if (memq (following-char) csv-separator-chars) (forward-char))
670 (csv-end-of-field))))
671
672 (defun csv-backward-field (arg)
673 "Move backward across one field, cf. `backward-sexp'.
674 With ARG, do it that many times. Negative arg -N means
675 move forward across N fields."
676 (interactive "p")
677 (if (< arg 0)
678 (csv-forward-field (- arg))
679 (while (>= (setq arg (1- arg)) 0)
680 (when (or (eolp)
681 (when (and (not (bobp)) (bolp)) (backward-char) t))
682 (while (progn
683 (beginning-of-line)
684 (csv-not-looking-at-record))
685 (backward-char))
686 (end-of-line))
687 (if (memq (preceding-char) csv-separator-chars) (backward-char))
688 (csv-beginning-of-field))))
689
690 (defun csv-sort-skip-fields (n &optional yank)
691 "Position point at the beginning of field N on the current line.
692 Fields are separated by `csv-separators'\; null terminal field allowed.
693 Assumes point is initially at the beginning of the line.
694 YANK non-nil allows N to be greater than the number of fields, in
695 which case extend the record as necessary."
696 (if (> n 0)
697 ;; Skip across N - 1 fields.
698 (let ((i (1- n)))
699 (while (> i 0)
700 (csv-end-of-field)
701 (if (eolp)
702 (if yank
703 (if (> i 1) (insert (car csv-separators)))
704 (error "Line has too few fields: %s"
705 (buffer-substring
706 (save-excursion (beginning-of-line) (point))
707 (save-excursion (end-of-line) (point)))))
708 (forward-char)) ; skip separator
709 (setq i (1- i))))
710 (end-of-line)
711 ;; Skip back across -N - 1 fields.
712 (let ((i (1- (- n))))
713 (while (> i 0)
714 (csv-beginning-of-field)
715 (if (bolp)
716 (error "Line has too few fields: %s"
717 (buffer-substring
718 (save-excursion (beginning-of-line) (point))
719 (save-excursion (end-of-line) (point)))))
720 (backward-char) ; skip separator
721 (setq i (1- i)))
722 ;; Position at the front of the field
723 ;; even if moving backwards.
724 (csv-beginning-of-field))))
725 \f
726 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
727 ;;; Field index mode
728 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
729
730 ;; Based partly on paren.el
731
732 (defcustom csv-field-index-delay 0.125
733 "Time in seconds to delay before updating field index display."
734 :type '(number :tag "seconds"))
735
736 (defvar csv-field-index-idle-timer nil)
737
738 (defvar csv-field-index-string nil)
739 (make-variable-buffer-local 'csv-field-index-string)
740
741 (defvar csv-field-index-old nil)
742 (make-variable-buffer-local 'csv-field-index-old)
743
744 (define-minor-mode csv-field-index-mode
745 "Toggle CSV-Field-Index mode.
746 With prefix ARG, turn CSV-Field-Index mode on if and only if ARG is positive.
747 Returns the new status of CSV-Field-Index mode (non-nil means on).
748 When CSV-Field-Index mode is enabled, the current field index appears in
749 the mode line after `csv-field-index-delay' seconds of Emacs idle time."
750 :global t
751 :init-value t ; for documentation, since default is t
752 ;; This macro generates a function that first sets the mode
753 ;; variable, then runs the following code, runs the mode hooks,
754 ;; displays a message if interactive, updates the mode line and
755 ;; finally returns the variable value.
756
757 ;; First, always disable the mechanism (to avoid having two timers):
758 (when csv-field-index-idle-timer
759 (cancel-timer csv-field-index-idle-timer)
760 (setq csv-field-index-idle-timer nil))
761 ;; Now, if the mode is on and any buffer is in CSV mode then
762 ;; re-initialize and enable the mechanism by setting up a new timer:
763 (if csv-field-index-mode
764 (if (memq t (mapcar (lambda (buffer)
765 (with-current-buffer buffer
766 (when (derived-mode-p 'csv-mode)
767 (setq csv-field-index-string nil
768 csv-field-index-old nil)
769 t)))
770 (buffer-list)))
771 (setq csv-field-index-idle-timer
772 (run-with-idle-timer csv-field-index-delay t
773 'csv-field-index)))
774 ;; but if the mode is off then remove the display from the mode
775 ;; lines of all CSV buffers:
776 (mapc (lambda (buffer)
777 (with-current-buffer buffer
778 (when (derived-mode-p 'csv-mode)
779 (setq csv-field-index-string nil
780 csv-field-index-old nil)
781 (force-mode-line-update))))
782 (buffer-list))))
783
784 (defun csv-field-index ()
785 "Construct `csv-field-index-string' to display in mode line.
786 Called by `csv-field-index-idle-timer'."
787 (if (derived-mode-p 'csv-mode)
788 (save-excursion
789 (let ((lbp (line-beginning-position)) (field 1))
790 (while (re-search-backward csv-separator-regexp lbp 1)
791 ;; Move as far as possible, i.e. to beginning of line.
792 (setq field (1+ field)))
793 (if (csv-not-looking-at-record) (setq field nil))
794 (when (not (eq field csv-field-index-old))
795 (setq csv-field-index-old field
796 csv-field-index-string
797 (and field (format "F%d" field)))
798 (force-mode-line-update))))))
799 \f
800 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
801 ;;; Killing and yanking fields
802 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
803
804 (defvar csv-killed-fields nil
805 "A list of the fields or sub-records last killed by `csv-kill-fields'.")
806
807 (defun csv-kill-fields (fields beg end)
808 "Kill specified fields of each line in the region.
809 If not set, the region defaults to the CSV records around point.
810 Fields are separated by `csv-separators' and null fields are allowed anywhere.
811 Field indices increase from 1 on the left or decrease from -1 on the right.
812 The fields are stored for use by `csv-yank-fields'. Fields can be
813 specified in any order but are saved in increasing index order.
814 Ignore blank and comment lines.
815
816 When called interactively, a prefix argument specifies a single field,
817 otherwise prompt for a field list, which may include ranges in the form
818 m-n, where m < n and n defaults to the last field index if omitted.
819
820 When called non-interactively, FIELDS is a single field index or a
821 list of field indices, with ranges specified as (m.n) or (m), and BEG
822 and END specify the region to process."
823 ;; (interactive "*P\nr")
824 (interactive (csv-interactive-args 'multiple))
825 (barf-if-buffer-read-only)
826 ;; Kill the field(s):
827 (setq csv-killed-fields nil)
828 (save-excursion
829 (save-restriction
830 (narrow-to-region beg end)
831 (goto-char (point-min))
832 (if (or (cdr fields) (consp (car fields)))
833 (csv-kill-many-columns fields)
834 (csv-kill-one-column (car fields)))))
835 (setq csv-killed-fields (nreverse csv-killed-fields)))
836
837 (defun csv-kill-one-field (field)
838 "Kill field with index FIELD in current line.
839 Return killed text. Assumes point is at beginning of line."
840 ;; Move to start of field to kill:
841 (csv-sort-skip-fields field)
842 ;; Kill to end of field (cf. `kill-region'):
843 (prog1 (delete-and-extract-region
844 (point)
845 (progn (csv-end-of-field) (point)))
846 (if (eolp)
847 (unless (bolp) (delete-char -1)) ; Delete trailing separator at eol
848 (delete-char 1)))) ; or following separator otherwise.
849
850 (defun csv-kill-one-column (field)
851 "Kill field with index FIELD in all lines in (narrowed) buffer.
852 Save killed fields in `csv-killed-fields'.
853 Assumes point is at `point-min'. Called by `csv-kill-fields'.
854 Ignore blank and comment lines."
855 (while (not (eobp))
856 (or (csv-not-looking-at-record)
857 (push (csv-kill-one-field field) csv-killed-fields))
858 (forward-line)))
859
860 (defun csv-kill-many-columns (fields)
861 "Kill several fields in all lines in (narrowed) buffer.
862 FIELDS is an unordered list of field indices.
863 Save killed fields in increasing index order in `csv-killed-fields'.
864 Assumes point is at `point-min'. Called by `csv-kill-fields'.
865 Ignore blank and comment lines."
866 (if (eolp) (error "First record is empty"))
867 ;; Convert non-positive to positive field numbers:
868 (let ((last 1) (f fields))
869 (csv-end-of-field)
870 (while (not (eolp))
871 (forward-char) ; skip separator
872 (csv-end-of-field)
873 (setq last (1+ last))) ; last = # fields in first record
874 (while f
875 (cond ((consp (car f))
876 ;; Expand a field range: (m.n) -> m m+1 ... n-1 n.
877 ;; If n is nil then it defaults to the number of fields.
878 (let* ((range (car f)) (cdrf (cdr f))
879 (m (car range)) (n (cdr range)))
880 (if (< m 0) (setq m (+ m last 1)))
881 (if n
882 (if (< n 0) (setq n (+ n last 1)))
883 (setq n last))
884 (setq range (list n))
885 (while (> n m) (push (setq n (1- n)) range))
886 (setcar f (car range))
887 (setcdr f (cdr range))
888 (setcdr (setq f (last range)) cdrf)))
889 ((zerop (car f)) (setcar f 1))
890 ((< (car f) 0) (setcar f (+ f last 1))))
891 (setq f (cdr f))))
892 (goto-char (point-min))
893 ;; Kill from right to avoid miscounting:
894 (setq fields (sort fields '>))
895 (while (not (eobp))
896 (or (csv-not-looking-at-record)
897 (let ((fields fields) killed-fields field)
898 (while fields
899 (setq field (car fields)
900 fields (cdr fields))
901 (beginning-of-line)
902 (push (csv-kill-one-field field) killed-fields))
903 (push (mapconcat 'identity killed-fields (car csv-separators))
904 csv-killed-fields)))
905 (forward-line)))
906
907 (defun csv-yank-fields (field beg end)
908 "Yank fields as the ARGth field of each line in the region.
909 ARG may be arbitrarily large and records are extended as necessary.
910 If not set, the region defaults to the CSV records around point\;
911 if point is not in a CSV record then offer to yank as a new table.
912 The fields yanked are those last killed by `csv-kill-fields'.
913 Fields are separated by `csv-separators' and null fields are allowed anywhere.
914 Field indices increase from 1 on the left or decrease from -1 on the right.
915 A prefix argument specifies a single field, otherwise prompt for field index.
916 Ignore blank and comment lines. When called non-interactively, FIELD
917 is a single field index\; BEG and END specify the region to process."
918 ;; (interactive "*P\nr")
919 (interactive (condition-case err
920 (csv-interactive-args 'single)
921 (error (list nil nil err))))
922 (barf-if-buffer-read-only)
923 (if (null beg)
924 (if (y-or-n-p (concat (error-message-string end)
925 ". Yank as a new table? "))
926 (csv-yank-as-new-table)
927 (error (error-message-string end)))
928 (if (<= field 0) (setq field (1+ field)))
929 (save-excursion
930 (save-restriction
931 (narrow-to-region beg end)
932 (goto-char (point-min))
933 (let ((fields csv-killed-fields))
934 (while (not (eobp))
935 (unless (csv-not-looking-at-record)
936 ;; Yank at start of specified field if possible,
937 ;; otherwise yank at end of record:
938 (if (zerop field)
939 (end-of-line)
940 (csv-sort-skip-fields field 'yank))
941 (and (eolp) (insert (car csv-separators)))
942 (when fields
943 (insert (car fields))
944 (setq fields (cdr fields)))
945 (or (eolp) (insert (car csv-separators))))
946 (forward-line)))))))
947
948 (defun csv-yank-as-new-table ()
949 "Yank fields as a new table starting at point.
950 The fields yanked are those last killed by `csv-kill-fields'."
951 (interactive "*")
952 (let ((fields csv-killed-fields))
953 (while fields
954 (insert (car fields) ?\n)
955 (setq fields (cdr fields)))))
956 \f
957 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
958 ;;; Aligning fields
959 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
960
961 (defun csv--column-widths ()
962 (let ((widths '()))
963 ;; Construct list of column widths:
964 (while (not (eobp)) ; for each record...
965 (or (csv-not-looking-at-record)
966 (let ((w widths)
967 (col (current-column))
968 x)
969 (while (not (eolp))
970 (csv-end-of-field)
971 (setq x (- (current-column) col)) ; Field width.
972 (if w
973 (if (> x (car w)) (setcar w x))
974 (setq w (list x)
975 widths (nconc widths w)))
976 (or (eolp) (forward-char)) ; Skip separator.
977 (setq w (cdr w) col (current-column)))))
978 (forward-line))
979 widths))
980
981 (defun csv-align-fields (hard beg end)
982 "Align all the fields in the region to form columns.
983 The alignment style is specified by `csv-align-style'. The number of
984 spaces specified by `csv-align-fields' appears after each separator.
985 Use soft alignment done by displaying virtual white space after the
986 separators unless invoked with an argument, in which case insert real
987 space characters into the buffer after the separators.
988 Unalign first (see `csv-unalign-fields'). Ignore blank and comment lines.
989
990 In hard-aligned records, separators become invisible whenever
991 `buffer-invisibility-spec' is non-nil. In soft-aligned records, make
992 separators invisible if and only if `buffer-invisibility-spec' is
993 non-nil when the records are aligned\; this can be changed only by
994 re-aligning. \(Unaligning always makes separators visible.)
995
996 When called non-interactively, use hard alignment if HARD is non-nil\;
997 BEG and END specify the region to align.
998 If there is no selected region, default to the whole buffer."
999 (interactive (cons current-prefix-arg
1000 (if (use-region-p)
1001 (list (region-beginning) (region-end))
1002 (list (point-min) (point-max)))))
1003 (setq end (copy-marker end))
1004 (csv-unalign-fields hard beg end) ; If hard then barfs if buffer read only.
1005 (save-excursion
1006 (save-restriction
1007 (narrow-to-region beg end)
1008 (set-marker end nil)
1009 (goto-char (point-min))
1010 (let ((widths (csv--column-widths)))
1011
1012 ;; Align fields:
1013 (goto-char (point-min))
1014 (while (not (eobp)) ; for each record...
1015 (unless (csv-not-looking-at-record)
1016 (let ((w widths)
1017 (column 0)) ;Desired position of left-side of this column.
1018 (while (and w (not (eolp)))
1019 (let* ((beg (point))
1020 (align-padding (if (bolp) 0 csv-align-padding))
1021 (left-padding 0) (right-padding 0)
1022 (field-width
1023 (- (- (current-column)
1024 (progn (csv-end-of-field) (current-column)))))
1025 (column-width (pop w))
1026 (x (- column-width field-width))) ; Required padding.
1027 (set-marker end (point)) ; End of current field.
1028 ;; beg = beginning of current field
1029 ;; end = (point) = end of current field
1030
1031 ;; Compute required padding:
1032 (cond
1033 ((eq csv-align-style 'left)
1034 ;; Left align -- pad on the right:
1035 (setq left-padding align-padding
1036 right-padding x))
1037 ((eq csv-align-style 'right)
1038 ;; Right align -- pad on the left:
1039 (setq left-padding (+ align-padding x)))
1040 ((eq csv-align-style 'auto)
1041 ;; Auto align -- left align text, right align numbers:
1042 (if (string-match "\\`[-+.[:digit:]]+\\'"
1043 (buffer-substring beg (point)))
1044 ;; Right align -- pad on the left:
1045 (setq left-padding (+ align-padding x))
1046 ;; Left align -- pad on the right:
1047 (setq left-padding align-padding
1048 right-padding x)))
1049 ((eq csv-align-style 'centre)
1050 ;; Centre -- pad on both left and right:
1051 (let ((y (/ x 2))) ; truncated integer quotient
1052 (setq left-padding (+ align-padding y)
1053 right-padding (- x y)))))
1054
1055 (cond
1056 (hard ;; Hard alignment...
1057 (when (> left-padding 0) ; Pad on the left.
1058 ;; Insert spaces before field:
1059 (if (= beg end) ; null field
1060 (insert (make-string left-padding ?\ ))
1061 (goto-char beg) ; beginning of current field
1062 (insert (make-string left-padding ?\ ))
1063 (goto-char end))) ; end of current field
1064 (unless (eolp)
1065 (if (> right-padding 0) ; pad on the right
1066 ;; Insert spaces after field:
1067 (insert (make-string right-padding ?\ )))
1068 ;; Make separator (potentially) invisible;
1069 ;; in Emacs 21.3, neighbouring overlays
1070 ;; conflict, so use the following only
1071 ;; with hard alignment:
1072 (let ((ol (make-overlay (point) (1+ (point)) nil t)))
1073 (overlay-put ol 'invisible t)
1074 (overlay-put ol 'evaporate t))
1075 (forward-char))) ; skip separator
1076
1077 ;; Soft alignment...
1078 (buffer-invisibility-spec ; csv-invisibility-default
1079
1080 ;; Hide separators...
1081 ;; Merge right-padding from previous field
1082 ;; with left-padding from this field:
1083 (if (zerop column)
1084 (when (> left-padding 0)
1085 ;; Display spaces before first field
1086 ;; by overlaying first character:
1087 (overlay-put
1088 (make-overlay beg (1+ beg))
1089 'before-string
1090 (make-string left-padding ?\ )))
1091 ;; Display separator as spaces:
1092 (with-silent-modifications
1093 (put-text-property
1094 (1- beg) beg
1095 'display `(space :align-to
1096 ,(+ left-padding column)))))
1097 (unless (eolp) (forward-char)) ; Skip separator.
1098 (setq column (+ column column-width align-padding)))
1099
1100 (t ;; Do not hide separators...
1101 (let ((overlay (make-overlay beg (point) nil nil t)))
1102 (when (> left-padding 0) ; Pad on the left.
1103 ;; Display spaces before field:
1104 (overlay-put overlay 'before-string
1105 (make-string left-padding ?\ )))
1106 (unless (eolp)
1107 (if (> right-padding 0) ; Pad on the right.
1108 ;; Display spaces after field:
1109 (overlay-put
1110 overlay
1111 'after-string (make-string right-padding ?\ )))
1112 (forward-char)))) ; Skip separator.
1113
1114 )))))
1115 (forward-line)))))
1116 (set-marker end nil))
1117
1118 (defun csv-unalign-fields (hard beg end)
1119 "Undo soft alignment and optionally remove redundant white space.
1120 Undo soft alignment introduced by `csv-align-fields'. If invoked with
1121 an argument then also remove all spaces and tabs around separators.
1122 Also make all invisible separators visible again.
1123 Ignore blank and comment lines. When called non-interactively, remove
1124 spaces and tabs if HARD non-nil\; BEG and END specify region to unalign.
1125 If there is no selected region, default to the whole buffer."
1126 (interactive (cons current-prefix-arg
1127 (if (use-region-p)
1128 (list (region-beginning) (region-end))
1129 (list (point-min) (point-max)))))
1130 ;; Remove any soft alignment:
1131 (mapc 'delete-overlay (overlays-in beg end))
1132 (with-silent-modifications
1133 (remove-list-of-text-properties beg end '(display)))
1134 (when hard
1135 (barf-if-buffer-read-only)
1136 ;; Remove any white-space padding around separators:
1137 (save-excursion
1138 (save-restriction
1139 (narrow-to-region beg end)
1140 (goto-char (point-min))
1141 (while (not (eobp))
1142 (or (csv-not-looking-at-record)
1143 (while (not (eolp))
1144 ;; Delete horizontal white space forward:
1145 ;; (delete-horizontal-space)
1146 ;; This relies on left-to-right argument evaluation;
1147 ;; see info node (elisp) Function Forms.
1148 (delete-region (point)
1149 (+ (point) (skip-chars-forward " \t")))
1150 (csv-end-of-field)
1151 ;; Delete horizontal white space backward:
1152 ;; (delete-horizontal-space t)
1153 (delete-region (point)
1154 (+ (point) (skip-chars-backward " \t")))
1155 (or (eolp) (forward-char))))
1156 (forward-line))))))
1157 \f
1158 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1159 ;;; Transposing rows and columns
1160 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1161
1162 (defun csv-transpose (beg end)
1163 "Rewrite rows (which may have different lengths) as columns.
1164 Null fields are introduced as necessary within records but are
1165 stripped from the ends of records. Preserve soft alignment.
1166 This function is its own inverse. Ignore blank and comment lines.
1167 When called non-interactively, BEG and END specify region to process."
1168 ;; (interactive "*P\nr")
1169 (interactive (csv-interactive-args 'noarg))
1170 (barf-if-buffer-read-only)
1171 (save-excursion
1172 (save-restriction
1173 (narrow-to-region beg end)
1174 (goto-char (point-min))
1175 ;; Delete rows and collect them as a reversed list of lists of
1176 ;; fields, skipping comment and blank lines:
1177 (let ((sep (car csv-separators))
1178 (align (overlays-in beg end))
1179 rows columns)
1180 ;; Remove soft alignment if necessary:
1181 (when align
1182 (mapc 'delete-overlay align)
1183 (setq align t))
1184 (while (not (eobp))
1185 (if (csv-not-looking-at-record)
1186 ;; Skip blank and comment lines:
1187 (forward-line)
1188 (let ((lep (line-end-position)))
1189 (push
1190 (csv-split-string
1191 (buffer-substring-no-properties (point) lep)
1192 csv-separator-regexp nil t)
1193 rows)
1194 (delete-region (point) lep)
1195 (or (eobp) (delete-char 1)))))
1196 ;; Rows must have monotonic decreasing lengths to be
1197 ;; transposable, so ensure this by padding with null fields.
1198 ;; rows is currently a reversed list of field lists, which
1199 ;; must therefore have monotonic increasing lengths.
1200 (let ((oldlen (length (car rows))) newlen
1201 (r (cdr rows)))
1202 (while r
1203 (setq newlen (length (car r)))
1204 (if (< newlen oldlen)
1205 (nconc (car r) (make-list (- oldlen newlen) nil))
1206 (setq oldlen newlen))
1207 (setq r (cdr r))))
1208 ;; Collect columns as a reversed list of lists of fields:
1209 (while rows
1210 (let (column (r rows) row)
1211 (while r
1212 (setq row (car r))
1213 ;; Provided it would not be a trailing null field, push
1214 ;; field onto column:
1215 (if (or column (string< "" (car row)))
1216 (push (car row) column))
1217 ;; Pop field off row:
1218 (setcar r (cdr row))
1219 ;; If row is now empty then remove it:
1220 (or (car r) (setq rows (cdr rows)))
1221 (setq r (cdr r)))
1222 (push column columns)))
1223 ;; Insert columns into buffer as rows:
1224 (setq columns (nreverse columns))
1225 (while columns
1226 (insert (mapconcat 'identity (car columns) sep) ?\n)
1227 (setq columns (cdr columns)))
1228 ;; Re-do soft alignment if necessary:
1229 (if align (csv-align-fields nil (point-min) (point-max)))))))
1230
1231 ;; The following generalised version of `split-string' is taken from
1232 ;; the development version of WoMan and should probably replace the
1233 ;; standard version in subr.el. However, CSV mode (currently) needs
1234 ;; only the `allowbeg' option.
1235
1236 (defun csv-split-string
1237 (string &optional separators subexp allowbeg allowend)
1238 "Splits STRING into substrings where there are matches for SEPARATORS.
1239 Each match for SEPARATORS is a splitting point.
1240 The substrings between the splitting points are made into a list
1241 which is returned.
1242 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1243 SUBEXP specifies a subexpression of SEPARATORS to be the splitting
1244 point\; it defaults to 0.
1245
1246 If there is a match for SEPARATORS at the beginning of STRING, we do
1247 not include a null substring for that, unless ALLOWBEG is non-nil.
1248 Likewise, if there is a match at the end of STRING, we do not include
1249 a null substring for that, unless ALLOWEND is non-nil.
1250
1251 Modifies the match data; use `save-match-data' if necessary."
1252 (or subexp (setq subexp 0))
1253 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1254 (start 0)
1255 notfirst
1256 (list nil))
1257 (while (and (string-match rexp string
1258 (if (and notfirst
1259 (= start (match-beginning subexp))
1260 (< start (length string)))
1261 (1+ start) start))
1262 (< (match-beginning subexp) (length string)))
1263 (setq notfirst t)
1264 (or (and (not allowbeg) (eq (match-beginning subexp) 0))
1265 (and (eq (match-beginning subexp) (match-end subexp))
1266 (eq (match-beginning subexp) start))
1267 (push (substring string start (match-beginning subexp)) list))
1268 (setq start (match-end subexp)))
1269 (or (and (not allowend) (eq start (length string)))
1270 (push (substring string start) list))
1271 (nreverse list)))
1272
1273 (provide 'csv-mode)
1274
1275 ;;; csv-mode.el ends here