search.c 15.2 KB
Newer Older
1 2 3 4 5 6 7
/*
 * search.c:  Search-and-replace for Gnumeric.
 *
 * Author:
 *   Morten Welinder (terra@diku.dk)
 */

8
#include <gnumeric-config.h>
Morten Welinder's avatar
Morten Welinder committed
9
#include "gnumeric.h"
10
#include "search.h"
11 12

#include "ranges.h"
Morten Welinder's avatar
Morten Welinder committed
13 14 15
#include "sheet.h"
#include "workbook.h"
#include "position.h"
Morten Welinder's avatar
Morten Welinder committed
16 17 18
#include "cell.h"
#include "value.h"
#include "sheet-object-cell-comment.h"
19

20 21 22 23 24
#include <string.h>
#include <libgnome/gnome-i18n.h>
#include <ctype.h>
#include <stdlib.h>

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/* ------------------------------------------------------------------------- */

SearchReplace *
search_replace_new (void)
{
	return g_new0 (SearchReplace, 1);
}

/* ------------------------------------------------------------------------- */

void
search_replace_free (SearchReplace *sr)
{
	g_free (sr->search_text);
	g_free (sr->replace_text);
40 41 42 43 44
	g_free (sr->range_text);
	if (sr->comp_search) {
		regfree (sr->comp_search);
		g_free (sr->comp_search);
	}
45 46 47 48 49
	g_free (sr);
}

/* ------------------------------------------------------------------------- */

50
static int
Morten Welinder's avatar
Morten Welinder committed
51
search_replace_compile (SearchReplace *sr, gboolean repl)
52 53 54 55 56 57 58 59 60 61 62 63 64 65
{
	const char *pattern;
	char *tmp;
	int flags = 0;
	int res;

	if (sr->comp_search) {
		regfree (sr->comp_search);
		g_free (sr->comp_search);
	}

	if (sr->is_regexp) {
		pattern = sr->search_text;
		tmp = NULL;
66
		sr->plain_replace =
Morten Welinder's avatar
Morten Welinder committed
67 68
			repl && (strchr (sr->replace_text, '$') == 0 &&
				 strchr (sr->replace_text, '\\') == 0);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	} else {
		/*
		 * Create a regular expression equivalent to the search
		 * string.  (Thus hoping the regular expression search
		 * routines are pretty good.)
		 */

		const char *src = sr->search_text;
		char *dst = tmp = g_new (char, strlen (src) * 2 + 1);
		pattern = tmp;

		for (; *src; src++) {
			switch (*src) {
			case '.': case '[': case '\\':
			case '*': case '^': case '$':
				*dst++ = '\\';
				/* Fall through. */
			default:
				*dst++ = *src;
				break;
			}
		}
		*dst = 0;
92 93

		sr->plain_replace = TRUE;
94 95 96 97 98 99 100 101 102 103 104 105 106 107
	}

	if (sr->ignore_case) flags |= REG_ICASE;

	sr->comp_search = g_new0 (regex_t, 1);
	res = regcomp (sr->comp_search, pattern, flags);

	g_free (tmp);

	return res;
}

/* ------------------------------------------------------------------------- */

108 109 110 111
SearchReplace *
search_replace_copy (const SearchReplace *sr)
{
	SearchReplace *dst = search_replace_new ();
Morten Welinder's avatar
Morten Welinder committed
112 113
	gboolean repl = (sr->replace_text != NULL);

114 115 116
	*dst = *sr;
	if (sr->search_text) dst->search_text = g_strdup (sr->search_text);
	if (sr->replace_text) dst->replace_text = g_strdup (sr->replace_text);
117 118 119
	if (sr->range_text) dst->range_text = g_strdup (sr->range_text);
	if (sr->comp_search) {
		dst->comp_search = NULL;
Morten Welinder's avatar
Morten Welinder committed
120
		search_replace_compile (dst, repl);
121
	}
122 123 124 125 126
	return dst;
}

/* ------------------------------------------------------------------------- */

127
char *
Morten Welinder's avatar
Morten Welinder committed
128
search_replace_verify (SearchReplace *sr, gboolean repl)
129 130 131 132 133 134 135
{
	int err;
	g_return_val_if_fail (sr != NULL, NULL);

	if (!sr->search_text || sr->search_text[0] == 0)
		return g_strdup (_("Search string must not be empty."));

Morten Welinder's avatar
Morten Welinder committed
136
	if (repl && !sr->replace_text)
137 138
		return g_strdup (_("Replacement string must be set."));

139
	if (sr->scope == SRS_range) {
140
		GSList *range_list;
141

142 143
		if (!sr->range_text || sr->range_text[0] == 0)
			return g_strdup (_("You must specify a range to search."));
144

Jody Goldberg's avatar
Jody Goldberg committed
145
		if ((range_list = global_range_list_parse (sr->curr_sheet, sr->range_text))
146
		    == NULL)
147
			return g_strdup (_("The search range is invalid."));
148
		range_list_destroy (range_list);
149 150
	}

Morten Welinder's avatar
Morten Welinder committed
151
	err = search_replace_compile (sr, repl);
152 153 154
	if (err)
		return g_strdup (_("Invalid search pattern."));

Morten Welinder's avatar
Morten Welinder committed
155
	if (repl && !sr->plain_replace) {
156 157 158 159 160 161 162 163 164 165 166
		const char *s;

		for (s = sr->replace_text; *s; s++) {
			switch (*s) {
			case '$':
				s++;
				switch (*s) {
				case '1': case '2': case '3': case '4': case '5':
				case '6': case '7': case '8': case '9':
				{
					int n = *s - '0';
167
					if (n > (int)sr->comp_search->re_nsub)
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
						return g_strdup (_("Invalid $-specification in replacement."));
					break;
				}
				default:
					return g_strdup (_("Invalid $-specification in replacement."));
				}
				break;
			case '\\':
				if (s[1] == 0)
					return g_strdup (_("Invalid trailing backslash in replacement."));
				s++;
				break;
			}
		}
	}

184 185 186 187 188
	return NULL;
}

/* ------------------------------------------------------------------------- */

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
static gboolean
match_is_word (SearchReplace *sr, const char *src,
	       const regmatch_t *pm, gboolean bolp)
{
	/* The empty string is not a word.  */
	if (pm->rm_so == pm->rm_eo)
		return FALSE;

	if (pm->rm_so > 0 || !bolp) {
		/* We get here when something actually preceded the match.  */
		char c_pre = src[pm->rm_so - 1];
		if (isalnum ((unsigned char)c_pre))
			return FALSE;
	}

	{
		char c_post = src[pm->rm_eo];
206
		if (c_post != 0 && isalnum ((unsigned char)c_post))
207 208 209 210 211 212 213 214
			return FALSE;
	}

	return TRUE;
}

/* ------------------------------------------------------------------------- */

215 216 217 218 219
static char *
calculate_replacement (SearchReplace *sr, const char *src, const regmatch_t *pm)
{
	char *res;

220 221 222 223 224 225 226 227 228 229 230 231 232
	if (sr->plain_replace) {
		res = g_strdup (sr->replace_text);
	} else {
		const char *s;
		GString *gres = g_string_sized_new (strlen (sr->replace_text));

		for (s = sr->replace_text; *s; s++) {
			switch (*s) {
			case '$':
			{
				int n = s[1] - '0';
				s++;

233
				g_assert (n > 0 && n <= (int)sr->comp_search->re_nsub);
234 235 236
				g_string_append_len (gres,
						     src + pm[n].rm_so,
						     pm[n].rm_eo - pm[n].rm_so);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
				break;
			}
			case '\\':
				s++;
				g_assert (*s != 0);
				g_string_append_c (gres, *s);
				break;
			default:
				g_string_append_c (gres, *s);
				break;
			}
		}

		res = gres->str;
		g_string_free (gres, FALSE);
	}
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

	/*
	 * Try to preserve the case during replacement, i.e., do the
	 * following substitutions:
	 *
	 * search -> replace
	 * Search -> Replace
	 * SEARCH -> REPLACE
	 * TheSearch -> TheReplace
	 */
	if (sr->preserve_case) {
		gboolean is_upper, is_capital, has_letter;
		int i;

		is_upper = TRUE;
		has_letter = FALSE;
		for (i = pm->rm_so; i < pm->rm_eo; i++) {
			unsigned char c = (unsigned char)src[i];
			if (isalpha (c)) {
				has_letter = TRUE;
				if (!isupper (c)) {
					is_upper = FALSE;
					break;
				}
			}
		}
		if (!has_letter) is_upper = FALSE;

		if (!is_upper && has_letter) {
			gboolean up = TRUE;
			is_capital = TRUE;
			for (i = pm->rm_so; i < pm->rm_eo; i++) {
				unsigned char c = (unsigned char)src[i];
				if (isalpha (c)) {
					if (up ? !isupper (c) : !islower (c)) {
						is_capital = FALSE;
						break;
					}
					up = FALSE;
				} else
					up = TRUE;
			}
		} else
			is_capital = FALSE;

		if (is_upper) {
			unsigned char *p = (unsigned char *)res;
300 301 302 303
			while (*p) {
				*p = toupper (*p);
				p++;
			}
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
		} else if (is_capital) {
			gboolean up = TRUE;
			unsigned char *p = (unsigned char *)res;
			for (; *p; p++) {
				if (isalpha (*p)) {
					*p = up ? toupper (*p) : tolower (*p);
					up = FALSE;
				} else
					up = TRUE;
			}
		}
	}

	return res;
}

/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
322 323 324
gboolean
search_match_string (SearchReplace *sr, const char *src)
{
Morten Welinder's avatar
Morten Welinder committed
325
	int flags = 0;
Morten Welinder's avatar
Morten Welinder committed
326 327 328

	g_return_val_if_fail (sr && sr->comp_search, FALSE);

329 330 331
	while (1) {
		regmatch_t match;
		int ret = regexec (sr->comp_search, src, 1, &match, flags);
Morten Welinder's avatar
Morten Welinder committed
332

333 334 335 336 337 338 339 340
		switch (ret) {
		case 0:
			if (!sr->match_words)
				return TRUE;

			if (match_is_word (sr, src, &match, (flags & REG_NOTBOL) != 0))
				return TRUE;

Morten Welinder's avatar
Morten Welinder committed
341 342 343 344
			/*
			 * We had a match, but it's not a word.  Pretend we saw
			 * a one-character match and continue after that.
			 */
345 346 347 348 349 350 351 352
			flags |= REG_NOTBOL;
			src += match.rm_so + 1;
			break;

		case REG_NOMATCH:
			return FALSE;

		default:
Morten Welinder's avatar
Morten Welinder committed
353
			g_error ("Unexpected error code from regexec: %d.", ret);
354 355
			return FALSE;
		}
Morten Welinder's avatar
Morten Welinder committed
356 357 358 359 360
	}
}

/* ------------------------------------------------------------------------- */

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
/*
 * Returns NULL if nothing changed, or a g_malloc string otherwise.
 */
char *
search_replace_string (SearchReplace *sr, const char *src)
{
	int nmatch;
	regmatch_t *pmatch;
	GString *res = NULL;
	int ret;
	int flags = 0;

	g_return_val_if_fail (sr && sr->comp_search, NULL);

	nmatch = 1 + sr->comp_search->re_nsub;
	pmatch = g_new (regmatch_t, nmatch);

	while ((ret = regexec (sr->comp_search, src, nmatch, pmatch, flags)) == 0) {
		if (!res) {
			/* The size here is a bit arbitrary.  */
			int size = strlen (src) +
				10 * strlen (sr->replace_text);
			res = g_string_sized_new (size);
		}

386 387
		if (pmatch[0].rm_so > 0) {
			g_string_append_len (res, src, pmatch[0].rm_so);
388 389
		}

390 391
		if (sr->match_words && !match_is_word (sr, src, pmatch,
						       (flags & REG_NOTBOL) != 0)) {
392 393 394 395 396 397 398
			/*  We saw a fake match.  */
			if (pmatch[0].rm_so < pmatch[0].rm_eo) {
				g_string_append_c (res, src[pmatch[0].rm_so]);
				/* Pretend we saw a one-character match.  */
				pmatch[0].rm_eo = pmatch[0].rm_so + 1;
			}
		} else {
399 400 401 402
			char *replacement =
				calculate_replacement (sr, src, pmatch);
			g_string_append (res, replacement);
			g_free (replacement);
403
		}
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

		if (pmatch[0].rm_eo > 0) {
			src += pmatch[0].rm_eo;
			flags |= REG_NOTBOL;
		}

		if (pmatch[0].rm_so == pmatch[0].rm_eo) {
			/*
			 * We have matched a null string at the current point.
			 * This might happen searching for just an anchor, for
			 * example.  Don't loop forever...
			 */
			break;
		}
	}

	g_free (pmatch);

	if (res) {
		char *tmp;

		g_string_append (res, src);
		tmp = g_strdup (res->str);
		g_string_free (res, TRUE);
		return tmp;
	} else {
		return NULL;
	}
}

/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
435 436 437 438 439 440 441 442 443

static int
cb_order_sheet_row_col (const void *_a, const void *_b)
{
	const EvalPos *a = *(const EvalPos **)_a;
	const EvalPos *b = *(const EvalPos **)_b;
	int i;

	/* By sheet name.  FIXME: Any better way than this?  */
444
	i = g_utf8_collate (a->sheet->name_unquoted, b->sheet->name_unquoted);
Morten Welinder's avatar
Morten Welinder committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

	/* By row number.  */
	if (!i) i = (a->eval.row - b->eval.row);

	/* By column number.  */
	if (!i) i = (a->eval.col - b->eval.col);

	return i;
}

static int
cb_order_sheet_col_row (const void *_a, const void *_b)
{
	const EvalPos *a = *(const EvalPos **)_a;
	const EvalPos *b = *(const EvalPos **)_b;
	int i;

	/* By sheet name.  FIXME: Any better way than this?  */
463
	i = g_utf8_collate (a->sheet->name_unquoted, b->sheet->name_unquoted);
Morten Welinder's avatar
Morten Welinder committed
464 465 466 467 468 469 470 471 472 473

	/* By column number.  */
	if (!i) i = (a->eval.col - b->eval.col);

	/* By row number.  */
	if (!i) i = (a->eval.row - b->eval.row);

	return i;
}

474 475
static Value *
search_collect_cells_cb (Sheet *sheet, int col, int row,
476
			 Cell *cell, GPtrArray *cells)
477 478 479 480 481 482 483 484 485 486 487 488 489
{
	EvalPos *ep = g_new (EvalPos, 1);

	ep->sheet = sheet;
	ep->eval.col = col;
	ep->eval.row = row;

	g_ptr_array_add (cells, ep);

	return NULL;

}

Morten Welinder's avatar
Morten Welinder committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
/* Collect a list of all cells subject to search.  */
GPtrArray *
search_collect_cells (SearchReplace *sr, Sheet *sheet)
{
	GPtrArray *cells;

	switch (sr->scope) {
	case SRS_workbook:
		cells = workbook_cells (sheet->workbook, TRUE);
		break;

	case SRS_sheet:
		cells = sheet_cells (sheet,
				     0, 0, SHEET_MAX_COLS, SHEET_MAX_ROWS,
				     TRUE);
		break;

	case SRS_range:
	{
509
		GSList *range_list;
Morten Welinder's avatar
Morten Welinder committed
510
		EvalPos ep;
511 512
		cells = g_ptr_array_new ();
		range_list = global_range_list_parse (sr->curr_sheet, sr->range_text);
513 514
		global_range_list_foreach (range_list,
			   eval_pos_init_sheet (&ep, sr->curr_sheet), TRUE,
515 516
			   (ForeachCellCB) search_collect_cells_cb, cells);
		range_list_destroy (range_list);
Morten Welinder's avatar
Morten Welinder committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
		break;
	}

	default:
		cells = NULL;
		g_assert_not_reached ();
	}

	/* Sort our cells.  */
	qsort (&g_ptr_array_index (cells, 0),
	       cells->len,
	       sizeof (gpointer),
	       sr->by_row ? cb_order_sheet_row_col : cb_order_sheet_col_row);

	return cells;
}

534 535 536 537 538 539 540 541 542 543
void
search_collect_cells_free (GPtrArray *cells)
{
	unsigned i;

	for (i = 0; i < cells->len; i++)
		g_free (g_ptr_array_index (cells, i));
	g_ptr_array_free (cells, TRUE);
}

Morten Welinder's avatar
Morten Welinder committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
/* ------------------------------------------------------------------------- */
/*
 * sr: The search spec.
 * cells: An array of EvalPos*, presumably a result of search_collect_cells.
 *
 * Returns an array of SearchFilterResult*s, which the caller must free.
 */

GPtrArray *
search_filter_matching (SearchReplace *sr, const GPtrArray *cells)
{
	unsigned i;
	GPtrArray *result = g_ptr_array_new ();

	for (i = 0; i < cells->len; i++) {
		SearchReplaceCellResult cell_res;
		SearchReplaceCommentResult comment_res;
		gboolean found;
		const EvalPos *ep = g_ptr_array_index (cells, i);

		found = search_replace_cell (sr, ep, FALSE, &cell_res);
		g_free (cell_res.old_text);
		if (found) {
			SearchFilterResult *item = g_new (SearchFilterResult, 1);
			item->ep = *ep;
			item->cell = cell_res.cell;
570
			item->comment = NULL;
Morten Welinder's avatar
Morten Welinder committed
571 572 573 574 575 576
			g_ptr_array_add (result, item);
		}

		if (search_replace_comment (sr, ep, FALSE, &comment_res)) {
			SearchFilterResult *item = g_new (SearchFilterResult, 1);
			item->ep = *ep;
577
			item->cell = NULL;
Morten Welinder's avatar
Morten Welinder committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591
			item->comment = comment_res.comment;
			g_ptr_array_add (result, item);
		}
	}

	return result;
}

void
search_filter_matching_free (GPtrArray *matches)
{
	unsigned i;
	for (i = 0; i < matches->len; i++)
		g_free (g_ptr_array_index (matches, i));
Jody Goldberg's avatar
Jody Goldberg committed
592
	g_ptr_array_free (matches, TRUE);
Morten Welinder's avatar
Morten Welinder committed
593 594
}

Morten Welinder's avatar
Morten Welinder committed
595
/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689

gboolean
search_replace_comment (SearchReplace *sr,
			const EvalPos *ep,
			gboolean repl,
			SearchReplaceCommentResult *res)
{
	g_return_val_if_fail (res, FALSE);

	res->comment = NULL;
	res->old_text = NULL;
	res->new_text = NULL;

	g_return_val_if_fail (sr && sr->comp_search, FALSE);

	if (!sr->search_comments) return FALSE;

	res->comment = cell_has_comment_pos (ep->sheet, &ep->eval);
	if (!res->comment) return FALSE;

	res->old_text = cell_comment_text_get (res->comment);

	if (repl) {
		res->new_text = search_replace_string (sr, res->old_text);
		return (res->new_text != NULL);
	} else
		return search_match_string (sr, res->old_text);
}

/* ------------------------------------------------------------------------- */

gboolean
search_replace_cell (SearchReplace *sr,
		     const EvalPos *ep,
		     gboolean repl,
		     SearchReplaceCellResult *res)
{
	Cell *cell;
	Value *v;
	gboolean is_expr, is_value, is_string, is_other;

	g_return_val_if_fail (res, FALSE);

	res->cell = NULL;
	res->old_text = NULL;
	res->new_text = NULL;

	g_return_val_if_fail (sr && sr->comp_search, FALSE);

	cell = res->cell = sheet_cell_get (ep->sheet, ep->eval.col, ep->eval.row);
	if (!cell) return FALSE;

	v = cell->value;

	is_expr = cell_has_expr (cell);
	is_value = !is_expr && !cell_is_blank (cell) && v;
	is_string = is_value && (v->type == VALUE_STRING);
	is_other = is_value && !is_string;

	if ((is_expr && sr->search_expressions) ||
	    (is_string && sr->search_strings) ||
	    (is_other && sr->search_other_values)) {
		const char *actual_src;
		gboolean initial_quote;

		res->old_text = cell_get_entered_text (cell);
		initial_quote = (is_value && res->old_text[0] == '\'');

		actual_src = res->old_text + (initial_quote ? 1 : 0);

		if (repl) {
			res->new_text = search_replace_string (sr, actual_src);
			if (res->new_text) {
				if (initial_quote) {
					/*
					 * The initial quote was not part of the s-a-r,
					 * so tack it back on.
					 */
					char *tmp = g_new (char, strlen (res->new_text) + 2);
					tmp[0] = '\'';
					strcpy (tmp + 1, res->new_text);
					g_free (res->new_text);
					res->new_text = tmp;
				}
				return TRUE;
			}
		} else
			return search_match_string (sr, actual_src);
	}

	return FALSE;
}

/* ------------------------------------------------------------------------- */