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