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