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