stf-parse.c 29.3 KB
Newer Older
1 2 3 4
/*
 * stf-parse.c : Structured Text Format parser. (STF)
 *               A general purpose engine for parsing data
 *               in CSV and Fixed width format.
5
 *
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * Copyright (C) Almer. S. Tigelaar.
 * EMail: almer1@dds.nl or almer-t@bigfoot.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

25 26
#include <gnumeric-config.h>
#include "gnumeric.h"
27
#include "stf-parse.h"
28

29
#include "clipboard.h"
30

31
#include <ctype.h>
32 33
#include <wctype.h>
#include <stdlib.h>
34

35 36
#define WARN_TOO_MANY_ROWS _("Too many rows in data to parse: %d")
#define WARN_TOO_MANY_COLS _("Too many columns in data to parse: %d")
37 38 39

/* Source_t struct, used for interchanging parsing information between the low level parse functions */
typedef struct {
40
	char const *position;  /* Indicates the current position within data */
41 42 43 44 45 46

	/* Used internally for fixed width parsing */
	int splitpos;          /* Indicates current position in splitpositions array */
	int linepos;           /* Position on the current line */
} Source_t;

47 48 49 50 51 52
/* Struct used for autodiscovery */
typedef struct {
	int start;
	int stop;
} AutoDiscovery_t;

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
/*
 * Some silly dude make the length field an unsigned int.  C just does
 * not deal very well with that.
 */
static inline int
my_garray_len (const GArray *a)
{
	return (int)a->len;
}

static inline int
my_gptrarray_len (const GPtrArray *a)
{
	return (int)a->len;
}


70 71 72 73 74
/*******************************************************************************************************
 * STF PARSE OPTIONS : StfParseOptions related
 *******************************************************************************************************/

/**
75
 * stf_parse_options_new:
76 77 78 79
 *
 * This will return a new StfParseOptions_t struct.
 * The struct should, after being used, freed with stf_parse_options_free.
 **/
80
StfParseOptions_t *
81 82 83 84
stf_parse_options_new (void)
{
	StfParseOptions_t* parseoptions = g_new0 (StfParseOptions_t, 1);

85 86 87 88
	parseoptions->parsetype   = PARSE_TYPE_NOTSET;
	parseoptions->terminator  = '\n';
	parseoptions->parselines  = -1;
	parseoptions->trim_spaces = (TRIM_TYPE_RIGHT | TRIM_TYPE_LEFT);
89

90
	parseoptions->splitpositions    = g_array_new (FALSE, FALSE, sizeof (int));
91 92

	parseoptions->indicator_2x_is_single = TRUE;
93
	parseoptions->duplicates             = FALSE;
94

95 96 97
	parseoptions->sep.str = NULL;
	parseoptions->sep.chr = NULL;
	
98 99 100 101
	return parseoptions;
}

/**
102
 * stf_parse_options_free:
103 104
 *
 * will free @parseoptions, note that this will not free the splitpositions
105
 * member (GArray) of the struct, the caller is responsible for that.
106 107 108 109 110 111
 **/
void
stf_parse_options_free (StfParseOptions_t *parseoptions)
{
	g_return_if_fail (parseoptions != NULL);

112 113 114 115
	if (parseoptions->sep.chr)
		g_free (parseoptions->sep.chr);
	if (parseoptions->sep.str) {
		GSList *l;
116
		
117 118 119 120 121
		for (l = parseoptions->sep.str; l != NULL; l = l->next)
			g_free ((char *) l->data);
		g_slist_free (parseoptions->sep.str);
	}
	
122 123 124 125 126 127
	g_array_free (parseoptions->splitpositions, TRUE);

	g_free (parseoptions);
}

void
128
stf_parse_options_set_type (StfParseOptions_t *parseoptions, StfParseType_t const parsetype)
129 130
{
	g_return_if_fail (parseoptions != NULL);
131
	g_return_if_fail (parsetype == PARSE_TYPE_CSV || parsetype == PARSE_TYPE_FIXED);
132 133 134 135 136

	parseoptions->parsetype = parsetype;
}

/**
137
 * stf_parse_options_set_line_terminator:
138 139 140 141 142 143 144
 *
 * This will set the line terminator, in both the Fixed width and CSV delimited importers
 * this indicates the end of a row. If you set this to '\0' the whole data will be treated
 * as on big line, note that '\n' (newlines) will not be parsed out if you set the
 * terminator to anything other than a newline
 **/
void
145
stf_parse_options_set_line_terminator (StfParseOptions_t *parseoptions, char const terminator)
146 147 148 149 150 151 152
{
	g_return_if_fail (parseoptions != NULL);

	parseoptions->terminator = terminator;
}

/**
153
 * stf_parse_options_set_lines_to_parse:
154
 *
155 156
 * This forces the parser to stop after parsing @lines lines, if you set @lines
 * to -1, which is the default, the parser will parse until it encounters a '\0'
157 158
 **/
void
159
stf_parse_options_set_lines_to_parse (StfParseOptions_t *parseoptions, int const lines)
160 161 162
{
	g_return_if_fail (parseoptions != NULL);

163
	if (lines != -1)
Almer S. Tigelaar's avatar
Almer S. Tigelaar committed
164
		parseoptions->parselines = lines;
165 166
	else
		parseoptions->parselines = -1;
167 168
}

169 170
/**
 * stf_parse_options_set_trim_spaces:
171
 *
172
 * If enabled will trim spaces in every parsed field on left and/or right
173 174 175
 * sides.
 **/
void
176
stf_parse_options_set_trim_spaces (StfParseOptions_t *parseoptions, StfTrimType_t const trim_spaces)
177 178 179 180 181 182
{
	g_return_if_fail (parseoptions != NULL);

	parseoptions->trim_spaces = trim_spaces;
}

183
/**
184
 * stf_parse_options_csv_set_separators:
185
 *
186
 * A copy is made of the parameters.
187 188
 **/
void
189 190
stf_parse_options_csv_set_separators (StfParseOptions_t *parseoptions, char const *character,
				      GSList const *string)
191
{
192 193 194
	GSList const *l = NULL;
	GSList *r;
	
195 196
	g_return_if_fail (parseoptions != NULL);

197 198 199
	if (parseoptions->sep.chr)
		g_free (parseoptions->sep.chr);
	parseoptions->sep.chr = g_strdup (character);
200

201 202 203 204 205
	if (parseoptions->sep.str) {
		for (l = parseoptions->sep.str; l != NULL; l = l->next)
			g_free ((char *) l->data);
		g_slist_free (parseoptions->sep.str);
	}
206

207 208 209
	for (r = NULL, l = string; l != NULL; l = l->next)
		r = g_slist_prepend (r, g_strdup (l->data));
	parseoptions->sep.str = g_slist_reverse (r);
210 211 212
}

void
213
stf_parse_options_csv_set_stringindicator (StfParseOptions_t *parseoptions, char const stringindicator)
214 215 216 217 218 219 220
{
	g_return_if_fail (parseoptions != NULL);
	g_return_if_fail (stringindicator != '\0');

	parseoptions->stringindicator = stringindicator;
}

221
/**
222
 * stf_parse_options_csv_set_indicator_2x_is_single:
223 224 225 226 227
 * @indic_2x : a boolean value indicating whether we want to see two
 * 		adjacent string indicators as a single string indicator
 * 		that is part of the cell, rather than a terminator.
 **/
void
228
stf_parse_options_csv_set_indicator_2x_is_single (StfParseOptions_t *parseoptions,
229
						  gboolean const indic_2x)
230 231 232 233 234 235
{
	g_return_if_fail (parseoptions != NULL);

	parseoptions->indicator_2x_is_single = indic_2x;
}

236
/**
237
 * stf_parse_options_csv_set_duplicates:
238
 * @duplicates : a boolean value indicating whether we want to see two
239
 *               separators right behind eachother as one
240 241
 **/
void
242
stf_parse_options_csv_set_duplicates (StfParseOptions_t *parseoptions, gboolean const duplicates)
243 244 245 246 247 248 249
{
	g_return_if_fail (parseoptions != NULL);

	parseoptions->duplicates = duplicates;
}

/**
250
 * stf_parse_options_fixed_splitpositions_clear:
251 252 253 254 255 256 257
 *
 * This will clear the splitpositions (== points on which a line is split)
 **/
void
stf_parse_options_fixed_splitpositions_clear (StfParseOptions_t *parseoptions)
{
	g_return_if_fail (parseoptions != NULL);
258

259 260 261 262 263
	g_array_free (parseoptions->splitpositions, TRUE);
	parseoptions->splitpositions = g_array_new (FALSE, FALSE, sizeof (int));
}

/**
264
 * stf_parse_options_fixed_splitpositions_add:
265 266 267 268 269
 *
 * @position will be added to the splitpositions, @position must be equal to
 * or greater than zero or -1 which means as much as "parse to end of line"
 **/
void
270
stf_parse_options_fixed_splitpositions_add (StfParseOptions_t *parseoptions, int const position)
271 272 273 274 275 276 277 278 279
{
	g_return_if_fail (parseoptions != NULL);
	g_return_if_fail (position >= 0 || position == -1);

	g_array_append_val (parseoptions->splitpositions, position);
}


/**
280
 * stf_parse_options_valid:
281 282 283 284 285 286 287 288 289 290
 * @parseoptions : an import options struct
 *
 * Checks if @parseoptions is correctly filled
 *
 * returns : TRUE if it is correctly filled, FALSE otherwise.
 **/
static gboolean
stf_parse_options_valid (StfParseOptions_t *parseoptions)
{
	g_return_val_if_fail (parseoptions != NULL, FALSE);
291

292 293 294
	if (parseoptions->parsetype == PARSE_TYPE_CSV) {

		if (parseoptions->stringindicator == '\0') {
295

296 297 298
			g_warning ("STF: Cannot have \\0 as string indicator");
			return FALSE;
		}
299

300 301 302
	} else if (parseoptions->parsetype == PARSE_TYPE_FIXED) {

		if (!parseoptions->splitpositions) {
303

304 305 306 307 308 309 310 311 312 313 314 315
			g_warning ("STF: No splitpositions in struct");
			return FALSE;
		}
	}

	return TRUE;
}

/*******************************************************************************************************
 * STF PARSE : The actual routines that do the 'trick'
 *******************************************************************************************************/

316
static inline void
317
trim_spaces_inplace (char *field, StfParseOptions_t const *parseoptions)
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
{
	unsigned char *s = (unsigned char *)field;

	if (!s) return;

	if (isspace (*s) && parseoptions->trim_spaces & TRIM_TYPE_LEFT) {
		unsigned char *tmp = s;
		while (isspace (*tmp)) tmp++;
		strcpy (s, tmp);
	}

	if (parseoptions->trim_spaces & TRIM_TYPE_RIGHT) {
		int len = strlen (s);
		while (len && isspace (s[len - 1]))
			s[--len] = 0;
	}
}

336
/**
337
 * stf_parse_csv_is_separator:
338
 *
339 340
 * returns NULL if @character is not a separator, a pointer to the character
 * after the separator otherwise.
341
 **/
342 343
static inline char const *
stf_parse_csv_is_separator (char const *character, char const *chr, GSList const *str)
344
{
345 346
	g_return_val_if_fail (character != NULL, NULL);

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
	if (str) {
		GSList const *l;
		
		for (l = str; l != NULL; l = l->next) {
			char const *s = l->data;
			char const *r;
			int cnt;
			int const len = strlen (s);

			/* Don't compare past the end of the buffer! */
			for (r = character, cnt = 0; cnt < len; cnt++, r++)
				if (*r == '\0')
					break;
			
			if ((cnt == len) && (strncmp (character, s, len) == 0))
				return character + len;
		}
	}
365

366 367 368 369
	if (chr) {
		char const *s;
		
		for (s = chr; *s != '\0'; s++) {
370
			if (*character == *s)
371 372 373
				return character + 1;
		}
	}
374

375
	return NULL;
376 377 378
}

/**
379
 * stf_parse_csv_cell:
380
 *
381
 * returns a pointer to the parsed cell contents. (has to be freed by the calling routine)
382
 **/
383
static inline char *
384 385 386
stf_parse_csv_cell (Source_t *src, StfParseOptions_t *parseoptions)
{
	GString *res;
387
	char const *cur;
388
	gboolean sawstringterm;
389 390 391 392 393 394
	int len = 0;

	g_return_val_if_fail (src != NULL, NULL);
	g_return_val_if_fail (parseoptions != NULL, NULL);

	cur = src->position;
395 396

	/* A leading quote is always a quote */
397 398 399
	if (*cur == parseoptions->stringindicator) {
		cur++;
		sawstringterm = FALSE;
400
	} else
401 402 403
		sawstringterm = TRUE;

	res = g_string_new ("");
404

405
	while (*cur != '\0') {
406
		if (!sawstringterm) {
407 408 409 410 411
			if (*cur == parseoptions->stringindicator) {
				/* two stringindicators in a row represent a
				 * single stringindicator character that does
				 * not terminate the cell
				 */
412
				cur++;
413 414 415 416 417
				if (*cur != parseoptions->stringindicator ||
				    !parseoptions->indicator_2x_is_single) {
					sawstringterm = TRUE;
					continue;
				}
418 419
			}
		} else {
420
			char const *s;
421 422 423
			
			if (*cur == parseoptions->terminator)
				break;
424

425
			if ((s = stf_parse_csv_is_separator (cur, parseoptions->sep.chr, parseoptions->sep.str))) {
426
				cur = s;
427
				if (parseoptions->duplicates) {
428
					if (stf_parse_csv_is_separator (s, parseoptions->sep.chr, parseoptions->sep.str))
429 430 431
						continue;
				}
				break;
432
			}
433 434 435 436 437 438 439 440 441
		}

		g_string_append_c (res, *cur);

		len++;
		cur++;
	}

	src->position = cur;
442

443 444 445 446 447 448 449 450 451 452 453
	if (len != 0) {
		char *tmp = res->str;
		g_string_free (res, FALSE);
		return tmp;
	}

	g_string_free (res, TRUE);
	return NULL;
}

/**
454
 * stf_parse_csv_line:
455 456
 *
 * This will parse one line from the current @src->position.
457
 * It will return a GList with the cell contents as strings.
458
 * NOTE :
459
 * 1) The calling routine is responsible for freeing the strings in the GList
460 461
 * 2) The calling routine is responsible for freeing the list itself.
 *
462
 * returns : a list with char*'s
463
 **/
464
static GList *
465 466
stf_parse_csv_line (Source_t *src, StfParseOptions_t *parseoptions)
{
467
	GList *list = NULL;
468 469 470 471
	int col = 0;

	g_return_val_if_fail (src != NULL, NULL);
	g_return_val_if_fail (parseoptions != NULL, NULL);
472

473 474
	while (*src->position != '\0' && *src->position != parseoptions->terminator) {
		char *field = stf_parse_csv_cell (src, parseoptions);
475

476
		trim_spaces_inplace (field, parseoptions);
477
		list = g_list_prepend (list, field);
478

479 480
		if (++col >= SHEET_MAX_COLS) {
			g_warning (WARN_TOO_MANY_COLS, col);
481
			break;
482 483 484
		}
	}

485
	return g_list_reverse (list);
486 487 488
}

/**
489
 * stf_parse_fixed_cell:
490
 *
491
 * returns a pointer to the parsed cell contents. (has to be freed by the calling routine)
492
 **/
493
static inline char *
494 495 496
stf_parse_fixed_cell (Source_t *src, StfParseOptions_t *parseoptions)
{
	GString *res;
497
	char const *cur;
498 499
	int splitval;
	int len = 0;
500 501 502

	g_return_val_if_fail (src != NULL, NULL);
	g_return_val_if_fail (parseoptions != NULL, NULL);
503

504
	cur = src->position;
505

506
	res = g_string_new ("");
507
	if (src->splitpos < my_garray_len (parseoptions->splitpositions))
508 509 510 511
		splitval = (int) g_array_index (parseoptions->splitpositions, int, src->splitpos);
	else
		splitval = -1;

512
	while (*cur != '\0' && *cur != parseoptions->terminator && splitval != src->linepos) {
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
		g_string_append_c (res, *cur);

		src->linepos++;
	        cur++;
		len++;
	}

	src->position = cur;

	if (len != 0) {
		char *tmp = res->str;
		g_string_free (res, FALSE);
		return tmp;
	}

	g_string_free (res, TRUE);
	return NULL;
}

/**
533
 * stf_parse_fixed_line:
534 535
 *
 * This will parse one line from the current @src->position.
536
 * It will return a GList with the cell contents as strings.
537
 * NOTE :
538
 * 1) The calling routine is responsible for freeing the string in the GList
539 540 541 542
 * 2) The calling routine is responsible for freeing the list itself.
 *
 * returns : a list with char*'s
 **/
543
static GList *
544 545
stf_parse_fixed_line (Source_t *src, StfParseOptions_t *parseoptions)
{
546
	GList *list = NULL;
547 548 549 550 551 552 553
	int col = 0;

	g_return_val_if_fail (src != NULL, NULL);
	g_return_val_if_fail (parseoptions != NULL, NULL);

	src->linepos = 0;
	src->splitpos = 0;
554

555 556
	while (*src->position != '\0' && *src->position != parseoptions->terminator) {
		char *field = stf_parse_fixed_cell (src, parseoptions);
557

558
		trim_spaces_inplace (field, parseoptions);
559
		list = g_list_prepend (list, field);
560

561 562
		if (++col >= SHEET_MAX_COLS) {
			g_warning (WARN_TOO_MANY_COLS, col);
563
			break;
564
		}
565

566 567 568
		src->splitpos++;
	}

569
	return g_list_reverse (list);
570 571 572
}

/**
573
 * stf_parse_general:
574
 *
575
 * The GList that is returned contains smaller GLists.
576 577
 * The format is more or less :
 *
578 579 580 581
 * GList (Top-level)
 *  |------>GList (Sub)
 *  |------>GList (Sub)
 *  |------>GList (Sub)
582
 *
583 584
 * Every Sub-GList represents a parsed line and contains
 * strings as data. if a Sub-GList is NULL this means the line
585 586 587
 * was empty.
 * NOTE : The calling routine has to free *a lot* of stuff by
 *        itself :
588 589 590
 *        1) The data of each Sub-GList item (with g_free) these are all strings.
 *        2) The sub-GList's themselves (with g_slist_free).
 *        3) The top level GList.
591
 *
592
 * returns : a GList with Sub-GList's containing celldata.
593
 **/
594 595
GList *
stf_parse_general (StfParseOptions_t *parseoptions, char const *data)
596
{
597
	GList *l = NULL;
598 599 600 601 602 603 604 605 606
	Source_t src;
	int row;

	g_return_val_if_fail (parseoptions != NULL, NULL);
	g_return_val_if_fail (data != NULL, NULL);
	g_return_val_if_fail (stf_parse_options_valid (parseoptions), NULL);

	src.position = data;
	row = 0;
607

608
	while (*src.position != '\0') {
Almer S. Tigelaar's avatar
Almer S. Tigelaar committed
609
		GList *r;
610
			
611 612
		if (++row >= SHEET_MAX_ROWS) {
				g_warning (WARN_TOO_MANY_ROWS, row);
613
				break;
614
		}
Almer S. Tigelaar's avatar
Almer S. Tigelaar committed
615
				
616 617 618 619
		if (parseoptions->parselines != -1)
			if (row > parseoptions->parselines)
				break;

Almer S. Tigelaar's avatar
Almer S. Tigelaar committed
620 621 622
		r = parseoptions->parsetype == PARSE_TYPE_CSV
			? stf_parse_csv_line (&src, parseoptions)
			: stf_parse_fixed_line (&src, parseoptions);
623
		l = g_list_prepend (l, r);
Almer S. Tigelaar's avatar
Almer S. Tigelaar committed
624
		
625 626 627
		src.position++;
	}

628
	return g_list_reverse (l);
629 630 631
}

/**
632
 * stf_parse_get_rowcount:
633 634 635 636
 *
 * returns : number of rows in @data
 **/
int
637
stf_parse_get_rowcount (StfParseOptions_t *parseoptions, char const *data)
638
{
639
	char const *s;
640
	int rowcount = 0;
641
	gboolean last_row_empty = TRUE;
642 643 644

	g_return_val_if_fail (parseoptions != NULL, 0);
	g_return_val_if_fail (data != NULL, 0);
645

646 647 648 649 650
	for (s = data; *s != '\0'; s++) {
		if (*s == parseoptions->terminator) {
			rowcount++;
			last_row_empty = TRUE;
		} else
651
			last_row_empty = FALSE;
652 653 654 655 656 657

		if (parseoptions->parselines != -1)
			if (rowcount > parseoptions->parselines)
				break;
	}

658
	return last_row_empty ? rowcount : rowcount + 1;
659 660 661
}

/**
662
 * stf_parse_get_colcount:
663 664 665 666
 *
 * returns : number of columns in @data
 **/
int
667
stf_parse_get_colcount (StfParseOptions_t *parseoptions, char const *data)
668 669 670 671 672 673 674
{
	int colcount = 0;

	g_return_val_if_fail (parseoptions != NULL, 0);
	g_return_val_if_fail (data != NULL, 0);

	if (parseoptions->parsetype == PARSE_TYPE_CSV) {
675
		char const *iterator = data;
676
		int tempcount = 0;
677

678 679
		while (*iterator != '\0') {
			char const *s;
680 681
			
			if (*iterator == parseoptions->terminator) {
682 683 684 685
				if (tempcount > colcount)
					colcount = tempcount;
				tempcount = 0;
			}
686

687
			if ((s = stf_parse_csv_is_separator (iterator, parseoptions->sep.chr, parseoptions->sep.str))) {
688
				iterator = s;
689
				if (parseoptions->duplicates) {
690
					if (stf_parse_csv_is_separator (s, parseoptions->sep.chr, parseoptions->sep.str))
691 692
						continue;
				}
693

694
				tempcount++;
695 696
			} else
				iterator++;
697
		}
698 699
		if (tempcount > colcount)
			colcount = tempcount;
700
	} else
701
		colcount = my_garray_len (parseoptions->splitpositions) - 1;
702 703 704 705 706

	return colcount;
}

/**
707
 * stf_parse_get_longest_row_width:
708 709 710 711
 *
 * Returns the largest number of characters found in a line/row
 **/
int
712
stf_parse_get_longest_row_width (StfParseOptions_t *parseoptions, char const *data)
713
{
714
	char const *s;
715 716 717 718 719 720 721
	int len = 0;
	int longest = 0;
	int row = 0;

	g_return_val_if_fail (parseoptions != NULL, 0);
	g_return_val_if_fail (data != NULL, 0);

722 723
	for (s = data; *s != '\0'; s++) {
		if (*s == parseoptions->terminator || s[1] == '\0') {
724 725 726
			if (len > longest)
				longest = len;
			len = 0;
727
			row++;
728 729
		} else
			len++;
730 731 732 733 734

		if (parseoptions->parselines != -1)
			if (row > parseoptions->parselines)
				break;
	}
735 736
	
	return longest;
737
}
738

739
/**
740
 * stf_parse_get_colwidth:
741 742 743 744 745
 *
 * Will determine the width of column @index in @data given the
 * parsing rules as specified in @parseoptions
 **/
int
746
stf_parse_get_colwidth (StfParseOptions_t *parseoptions, char const *data, int const index)
747 748 749 750 751 752 753
{
	int width = 0;

	g_return_val_if_fail (parseoptions != NULL, 0);
	g_return_val_if_fail (data != NULL, 0);

	if (parseoptions->parsetype == PARSE_TYPE_CSV) {
754
		char const *iterator = data;
755 756
		int col = 0, colwidth = 0;

757 758
		while (*iterator != '\0') {
			char const *s;
759
			
760
			if ((s = stf_parse_csv_is_separator (iterator, parseoptions->sep.chr, parseoptions->sep.str))) {
761

762
				iterator = s;
763
				if (parseoptions->duplicates) {
764
					if (stf_parse_csv_is_separator (s, parseoptions->sep.chr, parseoptions->sep.str))
765 766
						continue;
				}
767

768 769
				if (col == index && colwidth > width)
					width = colwidth;
770

771 772 773 774 775 776
				colwidth = 0;
				col++;
			} else {
				colwidth++;
				if (*iterator == parseoptions->terminator) {
					if (col == index && colwidth > width)
777 778
						width = colwidth;
					col = 0;
779 780 781
					colwidth = 0;
				}
				iterator++;
782 783
			}
		}
784 785
		if (col == index && colwidth > width)
			width = colwidth;
786
	} else {
787 788 789 790
		int colstart = index - 1 < 0
			? 0
			: (int) g_array_index (parseoptions->splitpositions, int, index - 1);
		int colend = (int) g_array_index (parseoptions->splitpositions, int, index);
791 792

		if (colend == -1) {
793
			const char *s;
794
			int len = 0, templen = 0;
795

796 797
			for (s = data; *s != '\0'; s++) {
				if (*s == parseoptions->terminator) {
798 799 800
					if (templen > len)
						len = templen;
					templen = 0;
801 802
				} else
					templen++;
803 804 805 806
			}

			colend = len;
		}
807

808 809 810 811 812 813 814 815
		width = colend - colstart;
	}

	return width;

}

/**
816
 * stf_parse_convert_to_unix:
817
 *
818
 * This function will convert the @data into
819
 * unix line-terminated format. this means that CRLF (windows) will be converted to LF
820 821
 * and CR (Macintosh) to LF.
 * In addition to that form feed (\F) characters will be removed.
Morten Welinder's avatar
Morten Welinder committed
822
 * NOTE: This will not resize the buffer
823
 *
Morten Welinder's avatar
Morten Welinder committed
824
 * returns: TRUE on success, FALSE otherwise.
825 826
 **/
gboolean
Morten Welinder's avatar
Morten Welinder committed
827
stf_parse_convert_to_unix (char *data)
828
{
829 830
	char *s, *d;
	
831
	if (!data)
832
		return FALSE;
833

834
	for (s = d = data; *s != '\0';) {
835 836 837 838 839
		if (*s == '\r') {
			*d++ = '\n';
			s++;
			if (*s == '\n')
				s++;
840
			continue;
841 842
		} else if (*s == '\f') {
			s++;
843 844 845 846
			continue;
		}
		
		*d++ = *s++;
847
	}
848
	*d = '\0';
849

850 851 852 853 854 855
	return TRUE;
}

/**
 * stf_is_valid_data
 *
856 857
 * returns wether the input data is valid to import.
 * (meaning it checks wether it is text only)
858
 *
859
 * returns : NULL if valid, a pointer to the invalid character otherwise
860
 **/
861 862
char const *
stf_parse_is_valid_data (char const *data)
863
{
864
	unsigned char const *s;
865 866
	wchar_t wstr;
	int len;
867

868 869 870
	for (s = data; *s != '\0';) {
		len = mblen(s, MB_CUR_MAX);
		if (len == -1)
871
			return (char *)s;
872 873 874 875 876 877 878 879 880 881 882
		if (len > 1) {
			if (mbstowcs (&wstr, s, 1) == 1 &&
			    !iswprint (wstr) && !iswspace (wstr))
				return (char *)s;
			s += len;
		} else {
			if (!isprint (*s) && !isspace (*s))
				return (char *)s;
			s++;
		}
	}
883

884
	return NULL;
885 886
}

887 888 889 890 891
/**
 * stf_parse_options_fixed_autodiscover:
 * @parseoptions: a Parse options struct.
 * @data_lines : The number of lines to look at in @data.
 * @data : The actual data.
892
 *
893 894
 * Automatically try to discover columns in the text to be parsed.
 * We ignore empty lines (only containing parseoptions->terminator)
895
 *
896 897
 * FIXME: This is so extremely ugly that I am too tired to rewrite it right now.
 *        Think hard of a better more flexible solution...
898 899
 **/
void
900
stf_parse_options_fixed_autodiscover (StfParseOptions_t *parseoptions, int const data_lines, char const *data)
901
{
902
	char const *iterator = data;
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	GSList *list = NULL;
	GSList *list_start = NULL;
	int lines = 0;
	int effective_lines = 0;
	int max_line_length = 0;
	int *line_begin_hits = NULL;
	int *line_end_hits = NULL;
	int i;

	stf_parse_options_fixed_splitpositions_clear (parseoptions);

	/*
	 * First take a look at all possible white space combinations
	 */
	while (*iterator) {
		gboolean begin_recorded = FALSE;
		AutoDiscovery_t *disc = NULL;
		int position = 0;

		while (*iterator && *iterator != parseoptions->terminator) {
923

924 925 926 927 928 929 930 931
			if (!begin_recorded && *iterator == ' ') {

				disc = g_new0 (AutoDiscovery_t, 1);

				disc->start = position;

				begin_recorded = TRUE;
			} else if (begin_recorded && *iterator != ' ') {
932

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
				disc->stop = position;
				list = g_slist_prepend (list, disc);

				begin_recorded = FALSE;
				disc = NULL;
			}

			position++;
			iterator++;
		}

		if (position > max_line_length)
			max_line_length = position;

		/*
		 * If there are excess spaces at the end of
		 * the line : ignore them
		 */
		if (disc)
			g_free (disc);

		/*
		 * Hop over the terminator
		 */
		if (*iterator)
			iterator++;

		if (position != 0)
			effective_lines++;
962

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
		lines++;

		if (lines >= data_lines)
			break;
	}

	list       = g_slist_reverse (list);
	list_start = list;

	/*
	 * Kewl stuff :
	 * Look at the number of hits at each line position
	 * if the number of hits equals the number of lines
	 * we can be pretty sure this is the start or end
	 * of a column, we filter out empty columns
	 * later
	 */
	line_begin_hits = g_new0 (int, max_line_length + 1);
	line_end_hits   = g_new0 (int, max_line_length + 1);
982

983 984 985 986 987 988 989
	while (list) {
		AutoDiscovery_t *disc = list->data;

		line_begin_hits[disc->start]++;
		line_end_hits[disc->stop]++;

		g_free (disc);
990

991 992 993 994
		list = g_slist_next (list);
	}
	g_slist_free (list_start);

995 996
	for (i = 0; i < max_line_length + 1; i++)
		if (line_begin_hits[i] == effective_lines || line_end_hits[i] == effective_lines)
997 998 999
			stf_parse_options_fixed_splitpositions_add (parseoptions, i);

	/*
1000 1001 1002
	 * Do some corrections to the initial columns
	 * detected here, we obviously don't need to
	 * do this if there are no columns at all.
1003
	 */
1004
	if (my_garray_len (parseoptions->splitpositions) > 0) {
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016

		/*
		 * Try to find columns that look like :
		 *
		 * Example     100
		 * Example2      9
		 *
		 * (In other words : Columns with left & right justification with
		 *  a minimum of 2 spaces in the middle)
		 * Split these columns in 2
		 */

1017
		for (i = 0; i < my_garray_len (parseoptions->splitpositions) - 1; i++) {
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
			int begin = g_array_index (parseoptions->splitpositions, int, i);
			int end   = g_array_index (parseoptions->splitpositions, int, i + 1);
			int num_spaces   = -1;
			int spaces_start = 0;
			gboolean right_aligned = TRUE;
			gboolean left_aligned  = TRUE;
			gboolean has_2_spaces  = TRUE;

			iterator = data;
			lines = 0;
			while (*iterator) {
				gboolean trigger = FALSE;
				gboolean space_trigger = FALSE;
				int pos = 0;

				num_spaces   = -1;
				spaces_start = 0;
				while (*iterator && *iterator != parseoptions->terminator) {

					if (pos == begin) {
1038

1039 1040 1041 1042 1043
						if (*iterator == ' ')
							left_aligned = FALSE;

						trigger = TRUE;
					} else if (pos == end - 1) {
1044

1045 1046 1047 1048 1049 1050
						if (*iterator == ' ')
							right_aligned = FALSE;

						trigger = FALSE;
					}

1051
					if (trigger || pos == end - 1) {
1052
						if (!space_trigger && *iterator == ' ') {
1053

1054 1055 1056
							space_trigger = TRUE;
							spaces_start = pos;
						} else if (space_trigger && *iterator != ' ') {
1057

1058 1059 1060 1061
							space_trigger = FALSE;
							num_spaces = pos - spaces_start;
						}
					}
1062

1063 1064 1065 1066 1067 1068
					iterator++;
					pos++;
				}

				if (num_spaces < 2)
					has_2_spaces = FALSE;
1069

1070 1071 1072 1073
				if (*iterator)
					iterator++;

				lines++;
1074

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
				if (lines >= data_lines)
					break;
			}

			/*
			 * If this column meets all the criteria
			 * split it into two at the last measured
			 * spaces_start + num_spaces
			 */
			if (has_2_spaces && right_aligned && left_aligned) {
				int val = (((spaces_start + num_spaces) - spaces_start) / 2) + spaces_start;

				g_array_insert_val (parseoptions->splitpositions, i + 1, val);

				/*
				 * Skip over the inserted column
				 */
				i++;
			}
		}
1095

1096 1097
		/*
		 * Remove empty columns here if needed
1098
		 */
1099
		for (i = 0; i < my_garray_len (parseoptions->splitpositions) - 1; i++) {
1100 1101 1102 1103 1104 1105 1106 1107 1108
			int begin = g_array_index (parseoptions->splitpositions, int, i);
			int end = g_array_index (parseoptions->splitpositions, int, i + 1);
			gboolean only_spaces = TRUE;

			iterator = data;
			lines = 0;
			while (*iterator) {
				gboolean trigger = FALSE;
				int pos = 0;
1109

1110 1111
				while (*iterator && *iterator != parseoptions->terminator) {

1112

1113 1114 1115 1116 1117 1118
					if (pos == begin)
						trigger = TRUE;
					else if (pos == end)
						trigger = FALSE;

					if (trigger) {
1119

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
						if (*iterator != ' ')
							only_spaces = FALSE;
					}

					iterator++;
					pos++;
				}

				if (*iterator)
					iterator++;

				lines++;
1132

1133 1134 1135 1136 1137 1138 1139 1140
				if (lines >= data_lines)
					break;
			}

			/*
			 * The column only contains spaces
			 * remove it
			 */
1141
			if (only_spaces) {
1142
				g_array_remove_index (parseoptions->splitpositions, i);
1143 1144 1145 1146 1147 1148 1149 1150 1151

				/*
				 * We HAVE to make sure that the next column (end) also
				 * gets checked out. If we don't decrease "i" here, we
				 * will skip over it as the indexes shift down after
				 * the removal
				 */
				i--;
			}
1152 1153
		}
	}
1154

1155 1156 1157 1158
	g_free (line_begin_hits);
	g_free (line_end_hits);
}

1159 1160 1161 1162 1163
/*******************************************************************************************************
 * STF PARSE HL: high-level functions that dump the raw data returned by the low-level parsing
 *               functions into something meaningful (== application specific)
 *******************************************************************************************************/

1164 1165
Sheet *
stf_parse_sheet (StfParseOptions_t *parseoptions, char const *data, Sheet *sheet)
1166
{
1167 1168
	GList *res, *l;
	int row;
1169 1170 1171

	g_return_val_if_fail (parseoptions != NULL, NULL);
	g_return_val_if_fail (data != NULL, NULL);
1172
	g_return_val_if_fail (IS_SHEET (sheet), NULL);
1173

1174 1175 1176 1177 1178
	res = stf_parse_general (parseoptions, data);
	for (row = 0, l = res; l != NULL; l = l->next, row++) {
		GList *mres = l->data;
		GList *m;
		int col;
1179

1180 1181 1182 1183
		for (col = 0, m = mres; m