Debian Codegraph @

texk/xdvik/search-internal.c

raw
1 /*
2 * Copyright (c) 2003-2004 the xdvik development team
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to
6 * deal in the Software without restriction, including without limitation the
7 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 * sell copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * PAUL VOJTA OR ANY OTHER AUTHOR OF THIS SOFTWARE BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23 /*
24 How dvi search works:
25
26 (1) Map the search string passed by the user from resource.text_encoding
27 to UTF-8 (currently only maps ISO_8859-1), and create a regexp from
28 the string if needed.
29
30 If case-insensitive matching is activated and regexp search is not
31 active, the search string is converted to lowercase. For regexp
32 searches, the flag available with regcomp to ignore case is used.
33
34 (2) Scan 2 adjacent pages (so that we can also find matches across page
35 boundaries), collecting the text into a char *buffer.
36 This involves the following steps:
37
38 - Map characters from wide_ubyte to uint32_t encoding (ucs-4),
39 using and Adobe names lookup table (for Postscript Type1
40 fonts) or font-specific character info (for Metafont fonts).
41
42 This step also maps accented glyphs to composite glyphs,
43 expands ligatures to separate characters (e.g. `ffi' to
44 `f'`f'`i'), and tries to detect word boundaries and line
45 breaks.
46
47 If case-insensitive matching is activated, the characters are
48 also lowercased in this step.
49
50 Optionally, hyphenation can be removed in this step.
51
52 Routine: do_char() in dvi-draw.c (must be in dvi_draw.c since
53 we need access to drawing-related stuff like `currinf' to get
54 information about the current font, position in the DVI file
55 etc.).
56
57 - Save the uint32_t characters into a char *buffer, mapping to
58 utf-8.
59
60 (3) Search the buffer from (2) for the string from (1). If a match
61 has been found, the page is scanned again to store the bounding
62 box information of the matched text for highlighting it.
63 */
64
65
66
67 #include "xdvi-config.h"
68 #include "xdvi.h"
69
70 #define SWITCH_TO_UTF8 1
71
72 #if HAVE_REGEX_H
73 #include <regex.h>
74 #endif
75
76 #if HAVE_ICONV_H
77 #include <iconv.h>
78 #endif
79
80 #include <locale.h>
81
82 #if USE_LANGINFO
83 #include <langinfo.h>
84 #endif
85
86 #include <ctype.h>
87
88 #include <X11/keysym.h>
89
90 #include "dvi-init.h" /* for total_pages */
91 #include "dvi-draw.h"
92 #include "search-internal.h"
93
94 #include "search-dialog.h"
95 #include "message-window.h"
96 #include "statusline.h"
97 #include "events.h"
98 #include "encodings.h"
99 #include "pagesel.h"
100 #include "events.h"
101 #include "util.h"
102 #include "x_util.h"
103 #include "string-utils.h"
104 #include "mag.h"
105 #include "pagehist.h"
106 #include "translations.h"
107
108 #define DEBUG_SEARCH 0
109 /* #define MATCH_HIGHLIGHT_INVERTED 1 */
110
111
112 /* margins for highlighting the match */
113 const int BBOX_LOWER_MARGIN = 2;
114 const int BBOX_UPPER_MARGIN = 1;
115
116 #if 0
117 #define GET_BBOX(bbox, shrink, x, y, w, h) \
118 x = (bbox.ulx / (double)shrink + 0.5) - BBOX_UPPER_MARGIN; \
119 y = (bbox.uly / (double)shrink + 0.5) - BBOX_UPPER_MARGIN; \
120 w = ((bbox.lrx - bbox.ulx) / (double)shrink) + 0.5 \
121 + BBOX_UPPER_MARGIN + BBOX_LOWER_MARGIN + 1; \
122 h = ((bbox.lry - bbox.uly) / (double)shrink) + 0.5 \
123 + BBOX_UPPER_MARGIN + BBOX_LOWER_MARGIN + 2;
124 #endif /* 0 */
125 /* use integer arithmetic */
126 #define GET_BBOX(bbox, shrink, x, y, w, h) \
127 x = (bbox.ulx + shrink / 2) / shrink - BBOX_UPPER_MARGIN; \
128 y = (bbox.uly + shrink / 2) / shrink - BBOX_UPPER_MARGIN; \
129 w = (bbox.lrx - bbox.ulx + shrink - 1) / shrink \
130 + BBOX_UPPER_MARGIN + BBOX_LOWER_MARGIN + 1; \
131 h = (bbox.lry - bbox.uly + shrink - 1) / shrink \
132 + BBOX_UPPER_MARGIN + BBOX_LOWER_MARGIN + 2;
133
134 /* access from drawing routines */
135 static struct word_info *m_info = NULL;
136 static int m_match_page = -1;
137
138 /* Force restarting search if user switches pages. E.g. if
139 the current match is the last of 3 matches on the page,
140 and user re-selects the page, the search should start again
141 with match 1. Similarly, if current page is second of two
142 pages scanned, and user clicks on first, search shouldn't continue
143 on second page but restart on current one.
144 */
145 static Boolean m_changed_page = False;
146
147 static Boolean m_highlight_region_changed = True;
148
149 void
150 search_signal_page_changed(void)
151 {
152 m_changed_page = True;
153 }
154
155
156 static void
157 reset_info(struct word_info *w_info)
158 {
159 if (w_info == NULL)
160 return;
161
162 free(w_info->txt_buf);
163 w_info->txt_buf = NULL;
164 w_info->txt_buf_size = 0;
165 w_info->curr_buf_idx = 0;
166
167 free(w_info->bboxes);
168 w_info->bboxes = NULL;
169 w_info->bboxes_size = 0;
170 w_info->bboxes_idx = 0;
171
172 m_highlight_region_changed = True;
173 }
174
175
176 static void
177 generate_highlight_expose(const struct word_info *info)
178 {
179 int x1 = INT_MAX, y1 = INT_MAX, x2 = 0, y2 = 0;
180 size_t i;
181 for (i = 0; info->bboxes != NULL && i <= info->bboxes_idx && info->bboxes[i].ulx < INT_MAX; i++) {
182 if (info->bboxes[i].ulx < x1)
183 x1 = info->bboxes[i].ulx;
184 if (info->bboxes[i].uly < y1)
185 y1 = info->bboxes[i].uly;
186 if (info->bboxes[i].lrx > x2)
187 x2 = info->bboxes[i].lrx;
188 if (info->bboxes[i].lry > y2)
189 y2 = info->bboxes[i].lry;
190 }
191 #if 0
192 fprintf(stderr, "region for exposure: %d,%d to %d,%d\n",
193 x1, y1, x2, y2);
194 #endif /* 0 */
195 x1 -= MAX(BBOX_UPPER_MARGIN, BBOX_LOWER_MARGIN) - 2;
196 y1 -= MAX(BBOX_UPPER_MARGIN, BBOX_LOWER_MARGIN) - 2;
197 x2 += MAX(BBOX_UPPER_MARGIN, BBOX_LOWER_MARGIN) + 2;
198 y2 += MAX(BBOX_UPPER_MARGIN, BBOX_LOWER_MARGIN) + 2;
199 clearexpose(&mane, x1, y1, x2 - x1, y2 - y1);
200 }
201
202 static void
203 draw_bboxes(const struct word_info *info)
204 {
205 size_t i;
206 static GC bboxGC = 0;
207 static Boolean highlight_inverted_bak;
208
209 if (bboxGC != 0 && highlight_inverted_bak != resource.match_highlight_inverted) {
210 XFreeGC(DISP, bboxGC);
211 bboxGC = 0;
212 }
213 highlight_inverted_bak = resource.match_highlight_inverted;
214
215 if (resource.match_highlight_inverted) {
216 if (MAGNIFIER_ACTIVE && !INSIDE_MANE_WIN)
217 return;
218
219 TRACE_FIND((stderr, "-- EXPOSED region: x %d, y %d, w %d, h %d",
220 globals.win_expose.min_x, globals.win_expose.min_y, globals.win_expose.max_x - globals.win_expose.min_x, globals.win_expose.max_y - globals.win_expose.min_y));
221
222 if (bboxGC == 0) {
223 XGCValues values;
224 unsigned long valuemask;
225
226 values.function = GXinvert; /* was: GXxor; see bug #850788 */
227 if (values.function == GXinvert) {
228 valuemask = GCFunction;
229 }
230 else {
231 values.foreground = WhitePixelOfScreen(SCRN) ^ BlackPixelOfScreen(SCRN);
232 /* fprintf(stderr, "foreground: 0x%lx, white pixel: 0x%lx, black pixel: 0x%lx\n", */
233 /* values.foreground, WhitePixelOfScreen(SCRN), BlackPixelOfScreen(SCRN)); */
234 valuemask = GCFunction | GCForeground;
235 }
236 bboxGC = XCreateGC(DISP, XtWindow(globals.widgets.top_level), valuemask, &values);
237 }
238 }
239 else if (bboxGC == 0) {
240 XGCValues values;
241 values.function = GXcopy;
242 values.line_width = 2;
243 values.cap_style = CapRound;
244 values.foreground = resource.hl_Pixel;
245 values.background = resource.back_Pixel;
246 bboxGC = XCreateGC(DISP, XtWindow(globals.widgets.top_level),
247 GCFunction | GCLineWidth | GCCapStyle | GCForeground | GCBackground, &values);
248 }
249
250 TRACE_FIND((stderr, "bboxes_idx: %lu", (unsigned long)info->bboxes_idx));
251 for (i = 0; info->bboxes != NULL && i <= info->bboxes_idx && info->bboxes[i].ulx < INT_MAX; i++) {
252 int x, y, w, h;
253
254 if (info->bboxes[i].ulx > 10000 || info->bboxes[i].uly > 10000) {
255 TRACE_FIND((stderr, "skipping box: x %d, y %d",
256 info->bboxes[i].ulx, info->bboxes[i].uly));
257 continue;
258 }
259
260 GET_BBOX(info->bboxes[i], currwin.shrinkfactor, x, y, w, h);
261 TRACE_FIND((stderr, "DRAWING box: x %d, y %d, w %d, h %d; shrink: %d",
262 x, y, w, h, currwin.shrinkfactor));
263 if (resource.match_highlight_inverted) {
264 if (clip_region(&x, &y, &w, &h)) {
265 TRACE_FIND((stderr, "CLIPPED box: x %d, y %d, w %d, h %d",
266 x, y, w, h));
267 TEST_DELAY("Redrawing BBOX ............... ");
268 XFillRectangle(DISP, mane.win, bboxGC, x, y, w, h);
269 TEST_DELAY("Inverting BBOX ............... ");
270 }
271 }
272 /* XDrawRectangle(DISP, mane.win, globals.gc.high, x, y, w + 0, h + 0); */
273 /* clearexpose(&mane, x, y, w + 3, h + 3); */
274 /* XDrawRectangle(DISP, mane.win, globals.gc.high, x, y, w + 2, h + 2); */
275 /* XDrawRectangle(DISP, mane.win, globals.gc.high, x + 1, y + 1, w, h); */
276 else {
277 static XPoint points[5] = { {0,0}, {0,0}, {0,0}, {0,0}, {0,0} };
278
279 h++;
280
281 points[0].x = x;
282 points[0].y = y;
283
284 points[1].x = w;
285
286 points[2].y = h;
287
288 points[3].x = -w;
289
290 points[4].y = -h;
291
292 XDrawLines(DISP, mane.win, bboxGC, points, 5, CoordModePrevious);
293 }
294
295 if (!MAGNIFIER_ACTIVE) {
296 /* note: inverted y_max y_min, since we want to display the full box here */
297 scroll_page_if_needed(x + w, x, y + h, y);
298 }
299 }
300 }
301
302 /* return true if we have a match on page pageno */
303 Boolean
304 search_have_match(int pageno)
305 {
306 /* fprintf(stderr, "pageno: %d --- m_info: %p\n", pageno, m_info); */
307 /* fprintf(stderr, "m_match_page: %d\n", m_match_page); */
308 return m_info != NULL && m_match_page == pageno;
309 }
310
311 /* TODO: Speed this up, by doing something like bsearch? */
312 /*
313 Returns 2 if we're at the 1st or last character of the bbox, 1 if
314 inside the bbox, and 0 else (currently the return value 2 is unused).
315 */
316 int
317 search_inside_bbox_match(int x, int y)
318 {
319 size_t i;
320
321 ASSERT(m_info != NULL, "inside_match musn't be called with m_info == NULL!");
322 TRACE_FIND((stderr, "m_info->bboxes: %p; idx: %lu", (void *)m_info->bboxes, (unsigned long)m_info->bboxes_idx));
323 for (i = 0; m_info->bboxes != NULL && i <= m_info->bboxes_idx && m_info->bboxes[i].ulx < INT_MAX; i++) {
324 TRACE_FIND((stderr, "inside_bbox_match: %d, %d", x, y));
325 TRACE_FIND((stderr, "x: %d, y: %d, x2: %d, y2: %d",
326 (int)(m_info->bboxes[i].ulx / (double)currwin.shrinkfactor + 0.5),
327 (int)(m_info->bboxes[i].uly / (double)currwin.shrinkfactor + 0.5),
328 (int)(m_info->bboxes[i].lrx / (double)currwin.shrinkfactor + 0.5),
329 (int)(m_info->bboxes[i].lry / (double)currwin.shrinkfactor + 0.5)));
330
331 if (x >= (int)(m_info->bboxes[i].ulx / (double)currwin.shrinkfactor + 0.5)
332 && x <= (int)(m_info->bboxes[i].lrx / (double)currwin.shrinkfactor + 0.5)
333 && y >= (int)(m_info->bboxes[i].uly / (double)currwin.shrinkfactor + 0.5)
334 && y <= (int)(m_info->bboxes[i].lry / (double)currwin.shrinkfactor + 0.5)) {
335 TRACE_FIND((stderr, "%d == %d",
336 x - 1, (int)(m_info->bboxes[i].ulx / (double)currwin.shrinkfactor + 0.5)));
337 TRACE_FIND((stderr, "%d == %d",
338 y - 1, (int)(m_info->bboxes[i].uly / (double)currwin.shrinkfactor + 0.5)));
339 if (x - 1 == (int)(m_info->bboxes[i].ulx / (double)currwin.shrinkfactor + 0.5)
340 && y - 1 == (int)(m_info->bboxes[i].uly / (double)currwin.shrinkfactor + 0.5))
341 return 2;
342 else
343 return 1;
344 }
345 }
346 return 0;
347 }
348
349 void
350 search_draw_inverted_regions(void)
351 {
352 if (m_info != NULL) {
353 draw_bboxes(m_info);
354 }
355 }
356
357
358 /*
359 * shift everything in info down by 1 pages, so that info for page 1 becomes
360 * info for page 0.
361 */
362 static void
363 shift_info_down(struct search_info *searchinfo, struct word_info *info, struct page_mapping *page_mapping)
364 {
365 size_t initial_offset = 0;
366 if (page_mapping[0].offset != -1) { /* remember value */
367 initial_offset = page_mapping[0].offset;
368 }
369
370 if (globals.debug & DBG_FIND) {
371 int i;
372 fprintf(stderr, "current page_mapping:\n");
373 for (i = 0; i < 2; i++) {
374 fprintf(stderr, "%d: %d\n", page_mapping[i].pageno, page_mapping[i].offset);
375 }
376 }
377
378 TRACE_FIND((stderr, "initial offset: %lu", (unsigned long)initial_offset));
379
380 page_mapping[0].offset = page_mapping[1].offset - initial_offset;
381 page_mapping[0].pageno = page_mapping[1].pageno;
382 ASSERT(page_mapping[0].offset >= 0, "new index mustn't be negative!\n");
383 page_mapping[1].offset = page_mapping[1].pageno = -1;
384
385 TRACE_FIND((stderr, "new val at 0: %d; curr_idx: %lu, len: %lu",
386 page_mapping[0].offset,
387 (unsigned long)(info->curr_buf_idx - initial_offset),
388 (unsigned long)(strlen(info->txt_buf + initial_offset))));
389
390 /* move the text buffer down, and update its current index accordingly */
391 ASSERT(info->curr_buf_idx >= initial_offset, "info->curr_buf_idx mustn't become negative!");
392 memmove(info->txt_buf, info->txt_buf + initial_offset, info->curr_buf_idx - initial_offset + 1);
393 info->curr_buf_idx -= initial_offset;
394 TRACE_FIND((stderr, "new index: %lu", (unsigned long)info->curr_buf_idx));
395
396 searchinfo->from_pos -= initial_offset;
397 searchinfo->to_pos -= initial_offset;
398 if (searchinfo->from_pos < 0)
399 searchinfo->from_pos = 0;
400 if (searchinfo->to_pos < 0)
401 searchinfo->to_pos = 0;
402 TRACE_FIND((stderr, "new offsets: from=%d, to=%d", searchinfo->from_pos, searchinfo->to_pos));
403 }
404
405 /*
406 * shift everything in info up by 1 page, so that info for page 0 becomes info
407 * for page 1.
408 */
409 static void
410 shift_info_up(struct word_info *info, struct page_mapping *page_mapping)
411 {
412 if (globals.debug & DBG_FIND) {
413 int i;
414 fprintf(stderr, "current page_mapping:\n");
415 for (i = 0; i < 2; i++) {
416 fprintf(stderr, "%d: %d\n", page_mapping[i].pageno, page_mapping[i].offset);
417 }
418 }
419
420 ASSERT(page_mapping[0].offset > 0, "info->curr_buf_idx mustn't become negative!");
421 info->curr_buf_idx = page_mapping[0].offset;
422 TRACE_FIND((stderr, "new index: %lu", (unsigned long)info->curr_buf_idx));
423
424 page_mapping[1].offset = page_mapping[0].offset;
425 page_mapping[1].pageno = page_mapping[0].pageno;
426 page_mapping[0].offset = page_mapping[0].pageno = -1;
427
428 }
429
430 static void
431 append_to_info(struct word_info *info, const char *str)
432 {
433 size_t len = strlen(str);
434 size_t new_size = info->txt_buf_size;
435 while (len >= new_size) { /* space for trailing 0 */
436 new_size++;
437 }
438 if (new_size > info->txt_buf_size) {
439 info->txt_buf_size = new_size;
440 info->txt_buf = xrealloc(info->txt_buf, sizeof *(info->txt_buf) * info->txt_buf_size);
441 }
442 memcpy(info->txt_buf + info->curr_buf_idx, str, len + 1); /* also copy trailing 0 */
443 info->curr_buf_idx += len;
444 }
445
446 /* append info2 to info1, enlarging info1 as needed. */
447 static void
448 append_info(struct word_info *info1, const struct word_info *info2)
449 {
450 if (info2->txt_buf_size > 0) {
451 info1->txt_buf = xrealloc(info1->txt_buf, sizeof *(info1->txt_buf)
452 * (info1->txt_buf_size + info2->txt_buf_size));
453 memcpy(info1->txt_buf + info1->curr_buf_idx, info2->txt_buf, info2->txt_buf_size);
454 info1->txt_buf_size += info2->txt_buf_size;
455 info1->curr_buf_idx += info2->curr_buf_idx;
456 }
457 }
458
459 /* prepend info1 to info2, enlarging info2 as needed. */
460 static void
461 prepend_info(const struct word_info *info1, struct word_info *info2)
462 {
463 if (info1->txt_buf_size > 0) {
464 info2->txt_buf = xrealloc(info2->txt_buf, sizeof *(info2->txt_buf)
465 * (info2->txt_buf_size + info1->txt_buf_size + 1));
466 memmove(info2->txt_buf + info1->curr_buf_idx, info2->txt_buf, info2->curr_buf_idx);
467 info2->txt_buf[info1->curr_buf_idx + info2->curr_buf_idx] = '\0';
468 memcpy(info2->txt_buf, info1->txt_buf, info1->curr_buf_idx);
469 /* TRACE_FIND((stderr, "prepend_info: info2->txt_buf is: |%s|", info2->txt_buf)); */
470 info2->txt_buf_size += info1->txt_buf_size;
471 info2->curr_buf_idx += info1->curr_buf_idx;
472 }
473 }
474
475 #if HAVE_REGEX_H
476 /* convert the encoding part (between the `.' and the `@') of the
477 locale string passed as argument to UTF-8, and return the result
478 in a newly allocated string which the caller is responsible for
479 free()ing.
480 */
481 static char *
482 locale_to_utf8(const char *locale)
483 {
484 char *utf8_locale = xstrdup(locale);
485 char *ptr;
486 if ((ptr = strchr(utf8_locale, '.')) != NULL) {
487 char *ptr2, *rest = "";
488 if ((ptr2 = strchr(utf8_locale, '@')) != NULL)
489 rest = xstrdup(ptr2);
490
491 utf8_locale = xrealloc(utf8_locale,
492 ptr - utf8_locale + strlen(".utf8") + strlen(rest) + 1);
493 *ptr = '\0';
494 utf8_locale = strcat(utf8_locale, ".utf8");
495 if (ptr2 != NULL) {
496 utf8_locale = strcat(utf8_locale, rest);
497 free(rest);
498 }
499 }
500 else {
501 utf8_locale = xstrcat(utf8_locale, ".utf8");
502 }
503 return utf8_locale;
504 }
505 #endif /* HAVE_REGEX_H */
506
507 static Boolean
508 is_utf8_ideograph(const unsigned char *p)
509 {
510 int len;
511 uint32_t ucs4;
512
513 if ((len = utf8_to_ucs4((const char *)p, &ucs4, strlen((const char*)p))) <= 0)
514 return False;
515
516 return is_ideograph(ucs4);
517 }
518
519
520 static void
521 dump_buffer(const struct word_info *info, size_t offset, FILE *fp, outputFormatT fmt)
522 {
523 size_t i = offset, len, tot_len;
524
525 if (info->txt_buf == NULL)
526 return;
527
528 tot_len = strlen(info->txt_buf);
529 while (i < tot_len) {
530 if (fmt == FMT_UTF8) { /* just dump as-is */
531 fputc(info->txt_buf[i++], fp);
532 }
533 else { /* convert to iso-latin1, rendering unknown characters as `?' */
534 uint32_t ucs4;
535 const char *ret;
536
537 /* first apply normalization heurisitcs also used by search */
538 len = utf8_to_ucs4(info->txt_buf + i, &ucs4, strlen(info->txt_buf + i));
539 if ((ret = search_normalize_chars(ucs4)) != NULL)
540 fputs(ret, fp);
541 else if (ucs4 <= 0xff) /* in iso-latin1 range */
542 fputc((unsigned char)ucs4, fp);
543 else
544 fprintf(fp, "\\%.4lX", (unsigned long)ucs4);
545 i += len;
546 }
547 }
548 }
549
550 static void
551 scan_page(FILE *fp, int pageno, struct word_info *w_info)
552 {
553 off_t pos_save;
554 static ubyte my_scan_buffer[DVI_BUFFER_LEN];
555 struct drawinf currinf_save;
556 struct scan_info info;
557 ubyte maxchar_save;
558
559 reinit_text_scan(); /* to reset scanning heuristics (linebreaks etc.) */
560 info.data = (void *)w_info;
561 info.geom_special = NULL; /* no procedure here */
562
563 /* Save file position */
564 pos_save = save_file_status(globals.dvi_file.bak_fp, &currinf_save, &maxchar_save);
565
566 lseek(fileno(fp), pageinfo_get_offset(pageno), SEEK_SET);
567 memset((char *)&currinf.data, 0, sizeof currinf.data);
568 currinf.tn_table_len = TNTABLELEN;
569 currinf.tn_table = tn_table;
570 currinf.tn_head = tn_head;
571
572 /* point currinf to our own buffer: */
573 G_dvi_buf_ptr = my_scan_buffer;
574
575 currinf.pos = currinf.end = G_dvi_buf_ptr;
576 currinf.virtual = NULL;
577
578 geom_scan(text_do_char, fp, &info, pageno);
579
580 /* Restore file status. */
581 restore_file_status(globals.dvi_file.bak_fp, currinf_save, maxchar_save, pos_save);
582 }
583
584
585 static Boolean
586 do_scan_page(struct word_info *w_info, struct search_settings *settings,
587 struct page_mapping *page_mapping, int buffer_offset, int pageno,
588 searchDirectionT direction)
589 {
590 struct word_info page_info = { NULL, 0, 0, NULL, 0, 0, NULL, NULL, 0, False, True, False };
591 page_info.settings = settings;
592 ASSERT(buffer_offset >= 0, "buffer_offset must have been initialized");
593 page_info.buffer_offset = buffer_offset;
594 TRACE_FIND((stderr, "scanning page: %d; from_pos: %d", pageno, settings->searchinfo->from_pos));
595
596 if (read_events(EV_NOWAIT) & EV_GE_FIND_CANCEL) {
597 TRACE_FIND((stderr, "interrupted!!"));
598 return False;
599 }
600
601 scan_page(globals.dvi_file.bak_fp, pageno, &page_info);
602
603 /* TRACE_FIND((stderr, "scanned buffer of length %d on page %d; contents: |%s|", */
604 /* page_info.curr_buf_idx, pageno, page_info.txt_buf)); */
605
606 /* terminate page */
607 append_to_info(&page_info, "\n");
608 if (direction == SEARCH_DOWN) {
609 /* append to existing info */
610 append_info(w_info, &page_info);
611 page_mapping->offset = w_info->curr_buf_idx;
612 }
613 else {
614 prepend_info(&page_info, w_info);
615 /* TRACE_FIND((stderr, "buffer after prepending: |%s|", w_info->txt_buf)); */
616 page_mapping->offset = page_info.curr_buf_idx;
617 }
618 page_mapping->pageno = pageno;
619
620 return True;
621 }
622
623 #if HAVE_REGEX_H
624 static void
625 report_regexp_error(int errcode, regex_t *regex, const char *term, int flag)
626 {
627 size_t n = regerror(errcode, regex, NULL, 0);
628 char *err_buf = xmalloc(n);
629 regerror(errcode, regex, err_buf, n);
630 xdvi_bell();
631 popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
632 MSG_ERR,
633 NULL,
634 "Could not %s regular expression \"%s\": %s\n",
635 flag == 0 ? "compile" : "execute",
636 term, err_buf);
637 free(err_buf);
638 }
639 #endif /* HAVE_REGEX_H */
640
641 static void
642 try_match(const struct word_info *info,
643 const struct search_settings *settings)
644 {
645 char *res = NULL;
646 size_t from_pos = 0;
647 struct search_info *searchinfo = settings->searchinfo;
648
649 ASSERT(info->curr_buf_idx == strlen(info->txt_buf), "");
650 TRACE_FIND((stderr, "buffer index: %lu, len: %lu; from: %lu",
651 (unsigned long)info->curr_buf_idx,
652 (unsigned long)strlen(info->txt_buf),
653 (unsigned long)searchinfo->from_pos));
654 if (searchinfo->from_pos != -1)
655 from_pos = searchinfo->from_pos;
656
657 if (settings->direction == SEARCH_DOWN) {
658 TRACE_FIND((stderr, "trying to match |%s| from %lu; total: %lu",
659 settings->utf8_term,
660 (unsigned long)from_pos,
661 (unsigned long)strlen(info->txt_buf)));
662
663 res = strstr(info->txt_buf + from_pos, settings->utf8_term);
664 }
665 else {
666 size_t curr_pos = 0;
667 char *res_bak = NULL;
668
669 TRACE_FIND((stderr, "UP; trying to match |%s| from %lu, %lu",
670 settings->utf8_term,
671 (unsigned long)curr_pos, (unsigned long)from_pos));
672 TRACE_FIND((stderr, "buf: |%s|", info->txt_buf + curr_pos));
673 while (curr_pos <= from_pos) {
674 res_bak = res;
675 res = strstr(info->txt_buf + curr_pos, settings->utf8_term);
676 if (res != NULL) {
677 curr_pos = res - info->txt_buf + strlen(settings->utf8_term);
678 }
679 else {
680 break;
681 }
682 }
683 res = res_bak;
684 }
685 if (res != NULL) {
686 searchinfo->have_match = True;
687 searchinfo->from_pos = res - info->txt_buf;
688 searchinfo->to_pos = searchinfo->from_pos + strlen(settings->utf8_term);
689 }
690 else {
691 searchinfo->have_match = False;
692 }
693 }
694
695 #if HAVE_REGEX_H
696 static Boolean
697 try_regexp_match(regex_t *regex,
698 const struct word_info *info,
699 const struct search_settings *settings)
700 {
701 int have_match;
702 regmatch_t re_match;
703 size_t from_pos = 0;
704 Boolean retval = True;
705
706 struct search_info *searchinfo = settings->searchinfo;
707
708 #if SWITCH_TO_UTF8
709 /* switch to UTF-8 encoding, as for regcomp() */
710 char *utf8_locale = locale_to_utf8(globals.orig_locale);
711 TRACE_FIND((stderr, "current locale: |%s|, utf8 version: |%s|", globals.orig_locale, utf8_locale));
712 setlocale(LC_ALL, utf8_locale);
713 #endif
714
715 re_match.rm_so = re_match.rm_eo = -1;
716
717 if (searchinfo->from_pos != -1)
718 from_pos = searchinfo->from_pos;
719
720 if (settings->direction == SEARCH_DOWN) {
721 Boolean search_again = True;
722
723 while (search_again && from_pos < info->curr_buf_idx) {
724 searchinfo->have_match = False;
725 search_again = False;
726
727 /* TRACE_FIND((stderr, "search string: |%s|, from_pos: %d", info->txt_buf + from_pos, from_pos)); */
728 have_match = regexec(regex, info->txt_buf + from_pos, 1, &re_match, 0);
729
730 if (have_match == 0) { /* match */
731 TRACE_FIND((stderr, "match from %d to %d", (int)re_match.rm_so, (int)re_match.rm_eo));
732 if (re_match.rm_so == re_match.rm_eo) { /* skip zero-length matches */
733 from_pos += re_match.rm_so + 1;
734 search_again = True;
735 }
736 else {
737 searchinfo->from_pos = re_match.rm_so + from_pos;
738 searchinfo->to_pos = re_match.rm_eo + from_pos;
739 searchinfo->have_match = True;
740 }
741 }
742 else if (have_match != REG_NOMATCH) { /* error */
743 report_regexp_error(have_match, regex, settings->term, 1);
744 retval = False;
745 break;
746 }
747 }
748 }
749 else { /* searching backwards */
750 size_t curr_pos = 0, prev_pos = 0;
751 regmatch_t re_match_bak;
752 Boolean search_again = True;
753 searchinfo->have_match = False;
754 TRACE_FIND((stderr, "UP; trying to match |%s| from %lu, %lu",
755 settings->utf8_term,
756 (unsigned long)curr_pos, (unsigned long)from_pos));
757
758 re_match_bak.rm_so = re_match_bak.rm_eo = -1;
759
760 while (search_again && curr_pos <= from_pos) {
761 search_again = False;
762
763 /* remember previous match data */
764 re_match_bak.rm_so = prev_pos + re_match.rm_so;
765 re_match_bak.rm_eo = prev_pos + re_match.rm_eo;
766
767 TRACE_FIND((stderr, "backup values: %d, %d; curr_pos: %lu",
768 (int)re_match_bak.rm_so, (int)re_match_bak.rm_eo, (unsigned long)curr_pos));
769
770 /* TRACE_FIND((stderr, "text buf: |%s|", info->txt_buf + curr_pos)); */
771 have_match = regexec(regex, info->txt_buf + curr_pos, 1, &re_match, 0);
772 while (have_match == 0 && re_match.rm_so == re_match.rm_eo) { /* skip zero-length matches */
773 have_match = regexec(regex, info->txt_buf + ++curr_pos, 1, &re_match, 0);
774 }
775
776
777 if (have_match == 0) { /* match */
778 TRACE_FIND((stderr, "match from %d to %d", (int)re_match.rm_so, (int)re_match.rm_eo));
779 TRACE_FIND((stderr, "updating pos: %lu -> %lu; from_pos: %lu",
780 (unsigned long)curr_pos,
781 (unsigned long)(curr_pos + re_match.rm_eo),
782 (unsigned long)from_pos));
783 prev_pos = curr_pos;
784 curr_pos += re_match.rm_eo;
785 search_again = True;
786 }
787 else if (have_match != REG_NOMATCH) { /* error */
788 report_regexp_error(have_match, regex, settings->term, 1);
789 retval = False;
790 break;
791 }
792 }
793 if (retval) {
794 re_match.rm_so = re_match_bak.rm_so;
795 re_match.rm_eo = re_match_bak.rm_eo;
796
797 if (re_match.rm_so != -1) {
798 TRACE_FIND((stderr, "remembering from-to: %d - %d", (int)re_match.rm_so, (int)re_match.rm_eo));
799 searchinfo->from_pos = re_match.rm_so;
800 searchinfo->to_pos = re_match.rm_eo;
801 searchinfo->have_match = True;
802 }
803 }
804 }
805
806 #if SWITCH_TO_UTF8
807 /* switch back to original encoding */
808 setlocale(LC_ALL, globals.orig_locale);
809 setlocale(LC_NUMERIC, "C");
810 free(utf8_locale);
811 #endif
812
813 return retval;
814 }
815 #endif /* HAVE_REGEX_H */
816
817 /* Erase exising highlighting. TODO: Move this into dvi-draw so that
818 there's no big delay between erasing and drawing the next marker.
819 */
820 static void
821 erase_match_highlighting(struct word_info *info, Boolean flag)
822 {
823 size_t i;
824
825 if (info == NULL || (MAGNIFIER_ACTIVE && !INSIDE_MANE_WIN))
826 return;
827
828 for (i = 0; info->bboxes != NULL && i <= info->bboxes_idx && info->bboxes[i].ulx < INT_MAX; i++) {
829 int x, y, w, h;
830 GET_BBOX(info->bboxes[i], currwin.shrinkfactor, x, y, w, h);
831 if (resource.match_highlight_inverted) {
832 if (flag || m_highlight_region_changed) {
833 clearexpose(&mane, x, y, w, h);
834 }
835 else if (clip_region(&x, &y, &w, &h)) {
836 TRACE_FIND((stderr, "ERASING box: x %d, y %d, w %d, h %d",
837 x, y, w, h));
838 TEST_DELAY("Showing BBOX ............... ");
839 XClearArea(DISP, mane.win, x, y, w, h, False);
840 TEST_DELAY("Clearing BBOX ............... ");
841 }
842 }
843 else if (flag) {
844 /* erase only the existing marks, not the entire bounding box, to avoid flashing of
845 the text inside the bounding box. 1 pixel added to w, h just to make sure in case of
846 rounding errors. */
847 h++;
848 clearexpose(&mane, x - 1, y - 1, 2, h + 2);
849 clearexpose(&mane, x - 1, y - 1, w + 2, 2);
850 clearexpose(&mane, x + w - 1, y - 1, 2, h + 2);
851 clearexpose(&mane, x - 1, y + h - 1, w + 2, 2);
852 }
853 }
854 if (flag) {
855 reset_info(info);
856 info = NULL;
857 }
858 else
859 m_highlight_region_changed = False;
860 }
861
862 static void
863 highlight_match(struct search_settings *settings,
864 const struct word_info *w_info,
865 const struct page_mapping *page_mapping)
866 {
867 const int context = 10;
868 int match_page, i, j = 0;
869 static struct word_info curr_info = { NULL, 0, 0, NULL, 0, 0, NULL, NULL, 0, True, False, False };
870 struct search_info *searchinfo = settings->searchinfo;
871 Boolean match_wrapped = False;
872
873 curr_info.settings = settings;
874 curr_info.page_mapping = page_mapping;
875
876 TRACE_FIND((stderr, "MATCH from pos %d to %d:",
877 searchinfo->from_pos, searchinfo->to_pos));
878
879 if (globals.debug & DBG_FIND) {
880 fprintf(stderr, "current page_mapping:\n");
881 for (i = 0; i < 2; i++) {
882 fprintf(stderr, "%d: %d\n", page_mapping[i].pageno, page_mapping[i].offset);
883 }
884 }
885
886 TRACE_FIND((stderr, "to_pos: %d, %d", searchinfo->to_pos, page_mapping[0].offset));
887 if (searchinfo->from_pos < page_mapping[0].offset) {
888 match_page = page_mapping[0].pageno;
889 if (searchinfo->to_pos > page_mapping[0].offset) {
890 match_wrapped = True;
891 }
892 }
893 else {
894 if (searchinfo->from_pos >= page_mapping[1].offset) {
895 XDVI_ERROR((stderr, "to_pos (%d) should be smaller than page_mapping[1].offset (%d)!",
896 searchinfo->from_pos, page_mapping[1].offset));
897 }
898 ASSERT(searchinfo->from_pos < page_mapping[1].offset, "to_pos should be smaller than page_mapping[1].offset!");
899 match_page = page_mapping[1].pageno;
900 if (searchinfo->to_pos > page_mapping[1].offset) {
901 match_wrapped = True;
902 }
903 }
904 if (!settings->isearchterm) {
905 if (match_wrapped)
906 statusline_info(STATUS_MEDIUM, "Match from page %d to %d", match_page + 1, match_page + 2);
907 else
908 statusline_info(STATUS_MEDIUM, "Match on page %d", match_page + 1);
909
910 if (settings->wrapcnt > 0)
911 statusline_append(STATUS_MEDIUM, " (wrapped)", " (wrapped)");
912 }
913 if (globals.debug & DBG_FIND) {
914 fprintf(stderr, "*** match_page: %d, adding: %d\n", match_page, searchinfo->page_offset);
915
916 for (j = searchinfo->from_pos - context; j < searchinfo->from_pos; j++) {
917 if (j >= 0)
918 fputc(w_info->txt_buf[j], stderr);
919 else
920 fputc(' ', stderr);
921 }
922 fputs("\n >>", stderr);
923 for (j = searchinfo->from_pos; j < searchinfo->to_pos; j++) {
924 fputc(w_info->txt_buf[j], stderr);
925 }
926 fputs("<<\n ", stderr);
927 for (j = searchinfo->from_pos; j < searchinfo->to_pos; j++) {
928 fputc(' ', stderr);
929 }
930 for (j = searchinfo->to_pos; j < (int)w_info->curr_buf_idx; j++) {
931 fputc(w_info->txt_buf[j], stderr);
932 if (w_info->txt_buf[j] == '\n')
933 break;
934 }
935 fputc('\n', stderr);
936 }
937
938 if (match_page != current_page) {
939 goto_page(match_page, resource.keep_flag ? NULL : home, False);
940 page_history_insert(match_page);
941 /* globals.ev.flags |= EV_NEWPAGE; */
942 }
943 /* don't raise the window - this can obscure the search popup */
944 /* XMapRaised(DISP, XtWindow(globals.widgets.top_level)); */
945
946 /* this erases contents of m_info, so be careful - contents of curr_info
947 will be indirectly erased by this ... */
948 erase_match_highlighting(m_info, True);
949
950 /* now rescan the page to get bounding box info for the match */
951 scan_page(globals.dvi_file.bak_fp, match_page, &curr_info);
952 m_info = &curr_info;
953
954 m_match_page = match_page;
955
956 do_autoscroll = True; /* enable scrolling to match */
957 /* create an expose event so that the region gets highlighted */
958 if (m_info != NULL) {
959 generate_highlight_expose(m_info);
960 }
961 }
962
963 #if HAVE_REGEX_H
964
965 /*
966 * A mapping of Perl-style character classes to POSIX-style character classes.
967 */
968 static struct perl2posix_mapping {
969 const char *perl_class;
970 const char *posix_class;
971 } perl2posix_map[] = {
972 { "\\w", "[[:alnum:]]" },
973 { "\\W", "[^[:alnum:]]" },
974 { "\\d", "[[:digit:]]" },
975 { "\\D", "[^[:digit:]]" },
976 { "\\s", "[[:space:]]" },
977 { "\\S", "[^[:space:]]" },
978 { NULL, NULL } /* terminate */
979 };
980
981 /*
982 * Convert `perl_regex', a regexp using Perl-style character classes,
983 * to a regexp using POSIX-style character classes. Return the latter
984 * in freshly allocated memory, which the caller is responsible to free().
985 * Uses the perl2posix_map table.
986 */
987 static char *
988 perl2posix(const char *perl_regex)
989 {
990 char *posix_regex = xstrdup(perl_regex);
991 size_t i;
992
993 for (i = 0; perl2posix_map[i].perl_class != NULL; i++) {
994 const char *ptr;
995 size_t offset = 0;
996 TRACE_FIND((stderr, "searching for |%s| at offset %lu", perl2posix_map[i].perl_class, (unsigned long)offset));
997 while ((ptr = find_format_str(posix_regex + offset, perl2posix_map[i].perl_class)) != NULL) {
998 size_t len1 = ptr - posix_regex; /* length up to match */
999 size_t len2 = strlen(perl2posix_map[i].posix_class);
1000 TRACE_FIND((stderr, "Regexp: mapping %s to %s",
1001 perl2posix_map[i].perl_class,
1002 perl2posix_map[i].posix_class));
1003 /* -1 since -2 for perl format string, +1 for trailing '\0' */
1004 posix_regex = xrealloc(posix_regex, strlen(posix_regex) + len2 - 1);
1005 /* make space for new format string */
1006 memmove(posix_regex + len1 + len2, posix_regex + len1 + 2, strlen(posix_regex + len1 + 2) + 1);
1007 /* copy in new format string */
1008 memcpy(posix_regex + len1, perl2posix_map[i].posix_class, len2);
1009 TRACE_FIND((stderr, "Expanded regex: |%s|", posix_regex));
1010 offset = len1 + len2;
1011 TRACE_FIND((stderr, "searching again for |%s| at offset %lu",
1012 perl2posix_map[i].perl_class,
1013 (unsigned long)offset));
1014 }
1015 }
1016 return posix_regex;
1017 }
1018
1019 #endif /* HAVE_REGEX_H */
1020
1021 char *
1022 get_text_selection(int *len, int ulx, int uly, int lrx, int lry)
1023 {
1024 struct word_info txt_info = { NULL, 0, 0, NULL, 0, 0, NULL, NULL, 0, False, False, True };
1025 struct bbox text_bbox;
1026
1027 text_bbox.ulx = ulx;
1028 text_bbox.uly = uly;
1029 text_bbox.lrx = lrx;
1030 text_bbox.lry = lry;
1031
1032 txt_info.bboxes = &text_bbox;
1033
1034 /* initialize buffer with empty string */
1035 txt_info.txt_buf_size = 1;
1036 txt_info.txt_buf = xmalloc(txt_info.txt_buf_size);
1037 txt_info.txt_buf[0] = '\0';
1038
1039 /* this enlarges the buffer as needed */
1040 scan_page(globals.dvi_file.bak_fp, current_page, &txt_info);
1041
1042 *len = txt_info.txt_buf_size;
1043 return txt_info.txt_buf;
1044
1045 #if 0
1046 /* fprintf(stderr, "========== SELECTION (len %d):\n", txt_info.curr_buf_idx); */
1047 /* dump_buffer(&txt_info, 0, stderr, FMT_ISO_8859_1); */
1048 /* fprintf(stderr, "==========\n"); */
1049
1050 buf = xmalloc(4 * txt_info.curr_buf_idx + 1); /* just in case we get many non-printables */
1051 while (i < txt_info.curr_buf_idx) {
1052 uint32_t ucs4;
1053 const char *ret;
1054
1055 /* first apply normalization heurisitcs also used by search */
1056 size_t len = utf8_to_ucs4(txt_info.txt_buf + i, &ucs4, strlen(txt_info.txt_buf + i));
1057 if ((ret = search_normalize_chars(ucs4)) != NULL) {
1058 size_t len_ret = strlen(ret);
1059 memcpy(buf + offset, ret, len_ret);
1060 offset += len_ret;
1061 }
1062 else if (ucs4 <= 0xff) { /* in iso-latin1 range */
1063 buf[offset++] = (unsigned char)ucs4;
1064 }
1065 else {
1066 sprintf(buf + offset, "\\%.4lX", ucs4);
1067 offset += 4;
1068 }
1069 i += len;
1070 }
1071 buf[offset] = '\0';
1072 free(txt_info.txt_buf);
1073 return buf;
1074 #endif /* 0 */
1075 }
1076
1077 Boolean
1078 search_extract_text(struct save_or_print_info *info)
1079 {
1080 int i;
1081 FILE *fp;
1082
1083 if ((fp = XFOPEN(info->finfo->out_file, "wb")) == NULL) {
1084 popup_message(globals.widgets.top_level,
1085 MSG_ERR,
1086 NULL, "Could not open %s for writing: %s.",
1087 info->finfo->out_file,
1088 strerror(errno));
1089 return False;
1090 }
1091
1092 for (i = 0; i < total_pages; i++) {
1093 if (info->pinfo->callback == NULL || info->pinfo->callback(info, i)) {
1094 struct word_info txt_info = { NULL, 0, 0, NULL, 0, 0, NULL, NULL, 0, False, False, False };
1095 scan_page(globals.dvi_file.bak_fp, i, &txt_info);
1096
1097 dump_buffer(&txt_info, 0, fp, info->fmt);
1098
1099 free(txt_info.txt_buf);
1100
1101 fputs("\n\n", fp); /* two newlines for page breaks */
1102 }
1103 }
1104
1105 fclose(fp);
1106 return True;
1107 }
1108
1109 void
1110 search_erase_highlighting(Boolean reset)
1111 {
1112 erase_match_highlighting(m_info, reset);
1113 }
1114
1115 static void
1116 message_search_ended(XtPointer arg)
1117 {
1118 struct search_settings *settings = (struct search_settings *)arg;
1119
1120 settings->searchinfo->from_pos = settings->searchinfo->to_pos = -1;
1121 TRACE_FIND((stderr, "search ended; current_page: %d", current_page));
1122 settings->from_page = current_page;
1123 search_signal_page_changed();
1124 settings->message_window = 0;
1125 /* statusline_append(STATUS_SHORT, " stopped."); */
1126 if (!settings->isearchterm)
1127 statusline_info(STATUS_SHORT, "Search stopped.");
1128 }
1129
1130
1131 void
1132 search_restart(XtPointer arg)
1133 {
1134 struct search_settings *settings = (struct search_settings *)arg;
1135 Widget popup, textfield;
1136 char *searchterm = NULL;
1137 char *textfield_name = NULL;
1138
1139 TRACE_FIND((stderr, "restart search!"));
1140
1141 /* Update the search term (user might have changed it before
1142 hitting `Return' to restart the search). We need to start
1143 from the toplevel widget since this method may be called
1144 from a different window (e.g. confirmation popup).
1145 */
1146 #if defined(MOTIF) && USE_COMBOBOX
1147 textfield_name = "Text";
1148 #else
1149 textfield_name = Xdvi_SEARCHBOX_INPUT_NAME;
1150 #endif /* defined(MOTIF) && USE_COMBOBOX */
1151 if (!settings->isearchterm
1152 && get_widget_by_name(&popup, globals.widgets.top_level, Xdvi_SEARCH_POPUP_NAME, True)
1153 && get_widget_by_name(&textfield, popup, textfield_name, True)) {
1154 XtVaGetValues(textfield,
1155 #ifdef MOTIF
1156 XmNvalue,
1157 #else
1158 XtNstring,
1159 #endif
1160 &searchterm, NULL);
1161 if (searchterm == NULL) {
1162 XDVI_WARNING((stderr, "Got NULL searchterm in search_restart()!"));
1163 return;
1164 }
1165 settings->term = searchterm;
1166 }
1167
1168 if (settings->direction == SEARCH_DOWN) {
1169 settings->from_page = 0;
1170 }
1171 else {
1172 settings->from_page = total_pages - 1;
1173 }
1174 if (settings->direction == SEARCH_DOWN)
1175 settings->searchinfo->from_pos = settings->searchinfo->to_pos = -1;
1176 else
1177 settings->searchinfo->from_pos = settings->searchinfo->to_pos = INT_MAX;
1178
1179 settings->message_window = 0;
1180 search_signal_page_changed();
1181 search_dvi((XtPointer)settings);
1182 }
1183
1184 static void
1185 normalize_newline(char *str)
1186 {
1187 size_t i, j;
1188 for (i = 0, j = 0; str[i] != '\0'; i++, j++) {
1189 if (str[i] == '\\' && str[i + 1] == 'n') {
1190 if (i > 0 && str[i - 1] == '\\') {
1191 str[j] = 'n';
1192 i++;
1193 }
1194 else {
1195 str[j] = '\n';
1196 i++;
1197 }
1198 }
1199 else {
1200 str[j] = str[i];
1201 }
1202 }
1203 str[j] = str[i]; /* copy terminating '\0' */
1204 }
1205
1206
1207 static Boolean
1208 reinit_searchterm(struct search_settings *settings, const char *encoding)
1209 {
1210 struct search_info *searchinfo = settings->searchinfo;
1211
1212 free(settings->utf8_term);
1213 settings->utf8_term = NULL;
1214
1215 if (memicmp(encoding, "iso-8859-1", strlen("iso-8859-1")) == 0
1216 || memicmp(encoding, "iso8859-1", strlen("iso8859-1")) == 0) {
1217 int conv_len = (strlen(settings->term) + 1) * 2;
1218 int ret_len;
1219 char *ptr = xmalloc(conv_len);
1220 if ((ret_len = str_iso_8859_1_to_utf8(settings->term, ptr, conv_len)) < 0) {
1221 xdvi_bell();
1222 popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1223 MSG_ERR,
1224 NULL,
1225 "Shouldn't happen: search term `%s' is too long (> %d)", settings->term, conv_len);
1226 searchinfo->locked = False;
1227 free(ptr);
1228 settings->utf8_term = xstrdup("");
1229 return False;
1230 }
1231 settings->utf8_term = ptr;
1232 }
1233 else if (memicmp(encoding, "utf-8", strlen("utf-8")) == 0
1234 || memicmp(encoding, "utf8", strlen("utf8")) == 0) {
1235 settings->utf8_term = xstrdup(settings->term);
1236 }
1237 else {
1238 if ((settings->utf8_term = iconv_convert_string(encoding, "utf-8", settings->term)) == NULL) {
1239 return False;
1240 }
1241 }
1242
1243 TRACE_FIND((stderr, "UTF-8 search term: |%s|", settings->utf8_term));
1244 normalize_newline(settings->utf8_term);
1245 TRACE_FIND((stderr, "UTF-8 search term after normalizing newline: |%s|", settings->utf8_term));
1246
1247 #if 0
1248 /* lowercasing for regexps is dealt with by REG_ICASE */
1249 if (!settings->case_sensitive && !settings->use_regexp) {
1250 if (!utf8_lowercase(settings->utf8_term))
1251 return False;
1252 TRACE_FIND((stderr, "Lowercased UTF-8 search term: |%s|", settings->utf8_term));
1253 }
1254 #else /* always lowercase, since REG_ICASE is broken with UTF-8(?) */
1255 if (!settings->case_sensitive && !utf8_lowercase(settings->utf8_term))
1256 return False;
1257 TRACE_FIND((stderr, "Lowercased UTF-8 search term: |%s|", settings->utf8_term));
1258 #endif /* 1 */
1259
1260 /* remove spaces/newlines before/after an ideographic char */
1261 {
1262 unsigned char *p = (unsigned char *)settings->utf8_term;
1263 unsigned char *q;
1264 int l, len = strlen((char *)p);
1265 uint32_t ucs4;
1266 Boolean had_ideograph;
1267
1268 had_ideograph = False;
1269 while (len > 0) {
1270 if (*p == ' ' || *p == '\n') {
1271 q = p + 1;
1272 while (*q == ' ' || *q == '\n')
1273 q++;
1274 len -= q - p;
1275 if (had_ideograph || is_utf8_ideograph(q))
1276 memmove(p, q, len + 1); /* remove spaces/newlines */
1277 else
1278 p = q; /* preserve spaces/newlines */
1279 }
1280 else {
1281 if ((l = utf8_to_ucs4((char *)p, &ucs4, len)) <= 0)
1282 break;
1283 len -= l;
1284 had_ideograph = is_ideograph(ucs4);
1285 p += l;
1286 }
1287 }
1288
1289 settings->utf8_term = xrealloc(settings->utf8_term, strlen(settings->utf8_term) + 1);
1290 }
1291
1292 return True;
1293 }
1294
1295 void
1296 search_reset_info(void)
1297 {
1298 TRACE_FIND((stderr, "resetting info!"));
1299 reset_info(m_info);
1300 m_info = NULL;
1301 }
1302
1303
1304 #if HAVE_REGEX_H
1305 static Boolean
1306 do_recompile_regexp(struct search_settings *settings,
1307 regex_t *regex)
1308 {
1309 int re_retval;
1310 /* use extended POSIX, and make `.' not match newlines (otherwise it's
1311 often too unintuitive because of the greediness of '+'/'*' */
1312 int re_flags = REG_EXTENDED | REG_NEWLINE;
1313 TRACE_FIND((stderr, "compiling regexp ..."));
1314
1315 if (settings->posix_term != NULL) {
1316 TRACE_FIND((stderr, "freeing old regexp ..."));
1317 free(settings->posix_term);
1318 regfree(regex);
1319 }
1320 settings->posix_term = perl2posix(settings->utf8_term);
1321
1322 #if 0 /* this is broken with e.g. german umlauts; maybe it can't deal with UTF-8 encoding? */
1323 /* compile regexp from search term */
1324 if (!settings->case_sensitive)
1325 re_flags |= REG_ICASE;
1326 #endif
1327
1328 { /* change the encoding part of the locale to UTF-8 to match encoding
1329 of the search string and the search buffer */
1330 #if SWITCH_TO_UTF8
1331 char *utf8_locale = locale_to_utf8(globals.orig_locale);
1332 TRACE_FIND((stderr, "current locale: |%s|, utf8 version: |%s|", globals.orig_locale, utf8_locale));
1333 setlocale(LC_ALL, utf8_locale);
1334 #endif
1335 re_retval = regcomp(regex, settings->posix_term, re_flags);
1336 #if SWITCH_TO_UTF8
1337 setlocale(LC_ALL, globals.orig_locale);
1338 setlocale(LC_NUMERIC, "C");
1339 free(utf8_locale);
1340 #endif
1341 }
1342
1343 if (re_retval != 0) {
1344 report_regexp_error(re_retval, regex, settings->term, 0);
1345 settings->searchinfo->locked = False;
1346 return False;
1347 }
1348
1349 return True;
1350 }
1351
1352 #else /* HAVE_REGEX_H */
1353
1354 static void
1355 warn_no_regex(void)
1356 {
1357 xdvi_bell();
1358 popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1359 MSG_WARN,
1360 NULL,
1361 "POSIX regular expression support (regex.h) is not available on this platform; "
1362 "using ordinary string matching instead.");
1363 }
1364 #endif /* HAVE_REGEX_H */
1365
1366 /*
1367 Scan at most two adjacent pages, writing results in to page_mapping.
1368 Return False if user cancelled the search, True else.
1369 */
1370 static Boolean
1371 scan_two_pages(struct search_settings *settings,
1372 struct word_info *info,
1373 struct page_mapping *page_mapping,
1374 int curr_page)
1375 {
1376 Boolean cancelled = False;
1377 struct search_info *searchinfo = settings->searchinfo;
1378
1379 if (curr_page != page_mapping[0].pageno
1380 && curr_page != page_mapping[1].pageno) { /* none of 2 pages scanned yet */
1381 reset_info(info);
1382 if (settings->direction == SEARCH_DOWN) {
1383 if (!do_scan_page(info, settings, &(page_mapping[0]),
1384 0, curr_page, settings->direction)
1385 || (curr_page + 1 < total_pages &&
1386 !do_scan_page(info, settings, &(page_mapping[1]),
1387 page_mapping[0].offset, curr_page + 1, settings->direction)))
1388 cancelled = True;
1389 }
1390 else {
1391 if (!do_scan_page(info, settings, &(page_mapping[1]),
1392 0, curr_page, settings->direction)
1393 || (curr_page > 0 &&
1394 !do_scan_page(info, settings, &(page_mapping[0]),
1395 page_mapping[1].offset, curr_page - 1, settings->direction)))
1396 cancelled = True;
1397 else if (page_mapping[0].offset != -1) {
1398 page_mapping[1].offset += page_mapping[0].offset;
1399 if (searchinfo->from_pos != INT_MAX)
1400 searchinfo->from_pos += page_mapping[0].offset;
1401 }
1402 }
1403 }
1404 else if (curr_page != page_mapping[0].pageno) { /* current page scanned as page_mapping[1] */
1405 if (settings->direction == SEARCH_DOWN && curr_page + 1 < total_pages) {
1406 shift_info_down(searchinfo, info, page_mapping);
1407 if (!do_scan_page(info, settings, &(page_mapping[1]),
1408 page_mapping[0].offset, curr_page + 1, settings->direction))
1409 cancelled = True;
1410 }
1411 else if (curr_page - 1 != page_mapping[0].pageno && curr_page > 0) {
1412 if (!do_scan_page(info, settings, &(page_mapping[0]),
1413 0, curr_page - 1, settings->direction))
1414 cancelled = True;
1415 else {
1416 page_mapping[1].offset += page_mapping[0].offset;
1417 if (searchinfo->from_pos != INT_MAX)
1418 searchinfo->from_pos += page_mapping[0].offset;
1419 }
1420 }
1421 }
1422 else if (curr_page != page_mapping[1].pageno) { /* current page scanned as page_mapping[0] */
1423 if (settings->direction == SEARCH_UP && curr_page > 0) {
1424 shift_info_up(info, page_mapping);
1425 if (!do_scan_page(info, settings, &(page_mapping[0]),
1426 0, curr_page - 1, settings->direction))
1427 cancelled = True;
1428 else {
1429 page_mapping[1].offset += page_mapping[0].offset;
1430 if (searchinfo->from_pos != INT_MAX) {
1431 searchinfo->from_pos += page_mapping[0].offset;
1432 searchinfo->to_pos += page_mapping[0].offset;
1433 }
1434 TRACE_FIND((stderr, "new offsets: from=%d, to=%d", searchinfo->from_pos, searchinfo->to_pos));
1435 }
1436 }
1437 else if (curr_page + 1 != page_mapping[1].pageno && curr_page + 1 < total_pages) {
1438 if (!do_scan_page(info, settings, &(page_mapping[1]),
1439 page_mapping[0].offset, curr_page + 1, settings->direction))
1440 cancelled = True;
1441 }
1442 }
1443
1444 return !cancelled;
1445 }
1446
1447 static void
1448 search_over_pages(struct search_settings *settings,
1449 struct page_mapping *page_mapping,
1450 struct word_info *w_info,
1451 int *from_pos_bak,
1452 Boolean adjust_hyphen_offset
1453 #if HAVE_REGEX_H
1454 , regex_t *regex
1455 #endif
1456 )
1457 {
1458 int curr_page = settings->from_page; /* page on which we're currently on */
1459
1460 for (;;) { /* scan pages, try to match */
1461 if (settings->isearchterm) {
1462 const char *prefix = "";
1463 if (settings->wrapcnt > 0)
1464 prefix = "Wrapped ";
1465 statusline_info(STATUS_FOREVER, "%sI-search (ESC to exit): %s", prefix, settings->isearchterm);
1466 }
1467 else {
1468 if (resource.expert_mode & XPRT_SHOW_STATUSLINE) /* too distracting for stdout */
1469 statusline_info(STATUS_MEDIUM, "Searching on page %d", curr_page);
1470 }
1471 TRACE_FIND((stderr, "curr_page: %d, pageno 0: %d, pageno1: %d",
1472 curr_page, page_mapping[0].pageno, page_mapping[1].pageno));
1473
1474 settings->hyphen_delta = 0;
1475 /* scan_two_pages will return False if user cancelled */
1476 if (!scan_two_pages(settings, w_info, page_mapping, curr_page)
1477 || (read_events(EV_NOWAIT) & EV_GE_FIND_CANCEL)) {
1478 if (!settings->isearchterm) {
1479 if (resource.expert_mode & XPRT_SHOW_STATUSLINE) /* too distracting for stdout */
1480 statusline_append(STATUS_SHORT,
1481 "- cancelled.",
1482 "- cancelled.");
1483 }
1484 settings->searchinfo->locked = False;
1485 return;
1486
1487 }
1488
1489 TRACE_FIND((stderr, "page mapping:\n%d: %d\n%d: %d",
1490 page_mapping[0].pageno, page_mapping[0].offset,
1491 page_mapping[1].pageno, page_mapping[1].offset));
1492
1493 /* dump_buffer(w_info, 0, stderr, FMT_ISO_8859_1); */
1494
1495 /* If ignore_hyphens has changed (in which case adjust_hyphen_offset
1496 is true), the buffer will contain settings->hyphen_delta fewer
1497 or more characters than in the previous pass due to the removal
1498 or addition of hyphens; adjust from_pos and to_pos accordingly:
1499 */
1500 if (adjust_hyphen_offset) {
1501 TRACE_FIND((stderr, "adjusting offset by %d", settings->hyphen_delta));
1502 if (settings->ignore_hyphens) { /* fewer characters */
1503 settings->searchinfo->from_pos -= settings->hyphen_delta;
1504 settings->searchinfo->to_pos -= settings->hyphen_delta;
1505 }
1506 else { /* more characters */
1507 settings->searchinfo->from_pos += settings->hyphen_delta;
1508 settings->searchinfo->to_pos += settings->hyphen_delta;
1509 }
1510 TRACE_FIND((stderr, "NEW from_pos: %d; to_pos: %d",
1511 settings->searchinfo->from_pos, settings->searchinfo->to_pos));
1512 }
1513
1514
1515 /* match the searchstring */
1516 #if HAVE_REGEX_H
1517 if (settings->use_regexp) {
1518 if (!try_regexp_match(regex, w_info, settings)) /* regexp error */
1519 return;
1520
1521 }
1522 else {
1523 #endif
1524 try_match(w_info, settings);
1525 #if HAVE_REGEX_H
1526 }
1527 #endif
1528
1529 /* again, check if user cancelled */
1530 if (read_events(EV_NOWAIT) & EV_GE_FIND_CANCEL) { /* user cancelled */
1531 if (!settings->isearchterm)
1532 statusline_append(STATUS_SHORT,
1533 "- cancelled.",
1534 "- cancelled.");
1535 settings->searchinfo->locked = False;
1536 return;
1537
1538 }
1539
1540 if (settings->searchinfo->have_match) { /* match, highlight it */
1541 highlight_match(settings, w_info, page_mapping);
1542 settings->searchinfo->locked = False;
1543 if (settings->direction == SEARCH_DOWN && !settings->isearchterm) {
1544 *from_pos_bak = settings->searchinfo->from_pos;
1545 settings->searchinfo->from_pos = settings->searchinfo->to_pos;
1546 }
1547 break;
1548 }
1549 else if ((settings->direction == SEARCH_DOWN && curr_page + 1 < total_pages)
1550 || (settings->direction == SEARCH_UP && curr_page > 0)) {
1551 if (settings->direction == SEARCH_DOWN)
1552 curr_page++;
1553 else
1554 curr_page--;
1555 TRACE_FIND((stderr, "continuing on page %d", curr_page));
1556 erase_match_highlighting(m_info, True);
1557 /* no match, and we have more pages; continue scanning */
1558 continue;
1559 }
1560 else { /* reached end of file */
1561 Widget find_popup;
1562
1563 if (settings->isearchterm) {
1564 const char *prefix = "Failed";
1565 fprintf(stderr, "reached end with wrapcnt: %d\n", settings->wrapcnt);
1566 if (settings->wrapcnt > 0)
1567 prefix = "Failed wrapped";
1568 xdvi_bell();
1569 statusline_info(STATUS_FOREVER, "%s I-search (ESC to exit, RET to restart): %s", prefix, settings->term);
1570 settings->searchinfo->locked = False;
1571 erase_match_highlighting(m_info, True);
1572 settings->wrapcnt++;
1573 return;
1574 }
1575
1576 if (settings->wrap) {
1577 if (settings->wrapcnt > 0) {
1578 positioned_popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1579 MSG_INFO,
1580 settings->x_pos, settings->y_pos,
1581 NULL, "Pattern `%s' not found.", settings->term);
1582 /* positioned_choice_dialog(XtNameToWidget(globals.widgets.top_level, "*find_popup"), */
1583 /* MSG_INFO, */
1584 /* settings->x_pos, settings->y_pos, */
1585 /* NULL, */
1586 /* #ifndef MOTIF */
1587 /* NULL, */
1588 /* #endif */
1589 /* NULL, NULL, /\* pre callback *\/ */
1590 /* "OK", message_search_ended, (XtPointer)settings, */
1591 /* NULL, NULL, NULL, */
1592 /* "Pattern `%s' not found.", settings->term); */
1593 settings->searchinfo->locked = False;
1594 message_search_ended((XtPointer)settings);
1595 return;
1596 }
1597 settings->wrapcnt++;
1598 erase_match_highlighting(m_info, True);
1599 settings->searchinfo->locked = False;
1600 search_restart((XtPointer)settings);
1601 return;
1602 }
1603
1604 if ((find_popup = XtNameToWidget(globals.widgets.top_level, "*find_popup")) == 0) {
1605 XDVI_WARNING((stderr, "Couldn't find \"find_popup\" widget!"));
1606 find_popup = globals.widgets.top_level;
1607 }
1608
1609 if (!settings->isearchterm)
1610 statusline_append(STATUS_MEDIUM,
1611 "... searched to end of file.",
1612 "... searched to end of file.");
1613 erase_match_highlighting(m_info, True);
1614 settings->searchinfo->locked = False;
1615
1616 settings->message_window =
1617 positioned_choice_dialog(find_popup,
1618 MSG_QUESTION,
1619 settings->x_pos, settings->y_pos,
1620 NULL,
1621 #ifndef MOTIF
1622 "do-search-restart",
1623 #endif
1624 NULL, NULL, /* no pre_callbacks */
1625 "Yes", search_restart, (XtPointer)settings,
1626 "Cancel", message_search_ended, (XtPointer)settings,
1627 "Searched %s of file without finding the pattern.\n"
1628 "Start again from the %s of the file?",
1629 settings->direction == SEARCH_DOWN
1630 ? "to end" : "to beginning",
1631 settings->direction == SEARCH_DOWN
1632 ? "beginning" : "end");
1633 TRACE_GUI((stderr, "message_window: %p\n", (void *)settings->message_window));
1634 /* notreached */
1635 break;
1636 }
1637 } /* for(;;) */
1638 }
1639
1640 void
1641 search_dvi(XtPointer arg)
1642 {
1643 struct search_settings *settings = (struct search_settings *)arg;
1644 struct search_info *searchinfo = settings->searchinfo;
1645
1646 #if HAVE_REGEX_H
1647 static regex_t regex;
1648 #endif /* HAVE_REGEX_H */
1649
1650 /* a mapping of page numbers to index positions in w_info->txt_buf,
1651 for the 2 pages that we scanned */
1652 static struct page_mapping page_mapping[2] = { { -1, -1 }, { -1, -1 } };
1653
1654 static struct word_info w_info = { NULL, 0, 0, NULL, 0, 0, NULL, NULL, 0, False, False, False };
1655
1656 static time_t dvi_time_bak = 0;
1657 static char *searchterm_bak = NULL;
1658
1659 static const char *text_encoding = NULL;
1660
1661 static Boolean case_sensitive_bak = False;
1662 static Boolean ignore_hyphens_bak = False;
1663 static Boolean ignore_linebreaks_bak = False;
1664 static searchDirectionT direction_bak = SEARCH_UNINITIALIZED;
1665 /* from_pos_bak is needed to mark the start of the match when switching from
1666 search down to search backwards, where we want to jump to the previous match,
1667 so we need the start of the current match again (and down search sets
1668 searchinfo->from_pos = searchinfo->to_pos) */
1669 static int from_pos_bak = -1;
1670 /* int curr_page; */
1671
1672 Boolean reinit = False;
1673 Boolean recompile_regexp = False;
1674 Boolean adjust_hyphen_offset = False;
1675
1676 /* prevent multiple invocations while still busy searching */
1677 if (searchinfo->locked) {
1678 TRACE_FIND((stderr, "LOCKED"));
1679 return;
1680 }
1681 searchinfo->locked = True;
1682
1683 if (dvi_time_bak == 0) { /* first invocation */
1684 case_sensitive_bak = settings->case_sensitive;
1685 ignore_hyphens_bak = settings->ignore_hyphens;
1686 ignore_linebreaks_bak = settings->ignore_linebreaks;
1687 dvi_time_bak = globals.dvi_file.time;
1688 }
1689 if (globals.dvi_file.time > dvi_time_bak) {
1690 dvi_time_bak = globals.dvi_file.time;
1691 reinit = True;
1692 }
1693
1694 m_match_page = -1;
1695
1696 if (raise_message_windows()) { /* any popups user still needs to deal with? */
1697 TRACE_GUI((stderr, "Still open message windows to deal with, returning ..."));
1698 searchinfo->locked = False;
1699 return;
1700 }
1701
1702 ASSERT(settings->term != NULL, "settings->term mustn't be NULL!");
1703 if (strlen(settings->term) == 0) {
1704 if (settings->isearchterm) {
1705 settings->searchinfo->locked = False;
1706 return;
1707 }
1708
1709 positioned_popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1710 MSG_ERR,
1711 settings->x_pos, settings->y_pos,
1712 NULL, "Empty search term");
1713 searchinfo->locked = False;
1714 return;
1715 }
1716
1717 TRACE_FIND((stderr, "dvi_search: Searching for |%s| from page %d", settings->term, settings->from_page));
1718 TRACE_FIND((stderr, " settings: down = %d, re = %d, case = %d",
1719 settings->direction, settings->use_regexp, settings->case_sensitive));
1720
1721 if (m_changed_page) {
1722 m_changed_page = False;
1723 reinit = True;
1724 }
1725
1726 /* initialize text_encoding */
1727 if (text_encoding == NULL) {
1728 text_encoding = get_text_encoding();
1729 }
1730
1731 /* first call to this routine, or search term changed:
1732 Re-initialize the utf-8 representation and the regexp */
1733 if (settings->utf8_term == NULL
1734 || searchterm_bak == NULL
1735 || strcmp(settings->term, searchterm_bak) != 0) {
1736
1737 if (!reinit_searchterm(settings, text_encoding)) {
1738 searchinfo->locked = False;
1739 return;
1740 }
1741
1742 free(searchterm_bak);
1743 searchterm_bak = xstrdup(settings->term);
1744 recompile_regexp = True;
1745 }
1746
1747 if (strlen(settings->utf8_term) == 0) {
1748 positioned_popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1749 MSG_WARN,
1750 settings->x_pos, settings->y_pos,
1751 NULL, "Search term is empty after UTF-8 conversion!");
1752 searchinfo->locked = False;
1753 return;
1754 }
1755
1756 if (direction_bak != settings->direction && direction_bak != SEARCH_UNINITIALIZED
1757 && searchinfo->from_pos != INT_MAX && searchinfo->from_pos != -1) {
1758 TRACE_FIND((stderr, "changed direction! from_pos: %d", searchinfo->from_pos));
1759 if (settings->direction == SEARCH_DOWN) {
1760 searchinfo->from_pos = searchinfo->to_pos;
1761 TRACE_FIND((stderr, "DOWN; new from_pos: %d", searchinfo->from_pos));
1762 }
1763 else if (settings->direction == SEARCH_UP) {
1764 if (from_pos_bak != -1) {
1765 searchinfo->from_pos = from_pos_bak;
1766 }
1767 else {
1768 searchinfo->from_pos = 0;
1769 }
1770 TRACE_FIND((stderr, "UP; new from_pos: %d", searchinfo->from_pos));
1771 }
1772 }
1773 direction_bak = settings->direction;
1774
1775 /* If one of the settings for case, hyphens ore linebreaks has
1776 * changed, we need to rescan the page to undo lowercasing,
1777 * hyphenation or linebreak removal in w_info, but preserve
1778 * searchinfo->from_pos since user will want to find next match.
1779 */
1780 if (case_sensitive_bak != settings->case_sensitive
1781 || ignore_hyphens_bak != settings->ignore_hyphens
1782 || ignore_linebreaks_bak != settings->ignore_linebreaks) {
1783
1784 if (ignore_hyphens_bak != settings->ignore_hyphens)
1785 adjust_hyphen_offset = True;
1786 case_sensitive_bak = settings->case_sensitive;
1787 ignore_hyphens_bak = settings->ignore_hyphens;
1788 ignore_linebreaks_bak = settings->ignore_linebreaks;
1789
1790 reset_info(&w_info);
1791
1792 /* adjust from_pos if it's on second page (we'll rescan it as first page) */
1793 if (searchinfo->from_pos >= page_mapping[0].offset)
1794 searchinfo->from_pos -= page_mapping[0].offset;
1795
1796 TRACE_FIND((stderr, "from_pos: %d", searchinfo->from_pos));
1797 page_mapping[0].offset = page_mapping[1].offset = page_mapping[0].pageno = page_mapping[1].pageno = -1;
1798 /* also need to recompile regexp, and undo lowercasing of search term */
1799 if (!reinit_searchterm(settings, text_encoding))
1800 return;
1801 recompile_regexp = True;
1802 }
1803
1804 if (reinit) { /* file changed, or on different page: re-initialize scan info */
1805 TRACE_FIND((stderr, "re-initializing scan info!"));
1806 page_mapping[0].offset = page_mapping[1].offset = page_mapping[0].pageno = page_mapping[1].pageno = -1;
1807
1808 /* re-initialize info */
1809 reset_info(&w_info);
1810 if (settings->direction == SEARCH_DOWN)
1811 searchinfo->from_pos = searchinfo->to_pos = 0;
1812 else
1813 settings->searchinfo->from_pos = settings->searchinfo->to_pos = INT_MAX;
1814 }
1815
1816 TRACE_FIND((stderr, "from_pos initialized with: %d", settings->searchinfo->from_pos));
1817
1818 if (settings->use_regexp && recompile_regexp) {
1819 #if HAVE_REGEX_H
1820 if (!do_recompile_regexp(settings, &regex))
1821 return;
1822 #else
1823 warn_no_regex();
1824 #endif /* HAVE_REGEX_H */
1825 }
1826
1827 /* do it */
1828 search_over_pages(settings, page_mapping, &w_info, &from_pos_bak, adjust_hyphen_offset
1829 #if HAVE_REGEX_H
1830 , &regex
1831 #endif
1832 );
1833 }
1834
1835 static void cb_isearch(Widget w, XtPointer closure, XEvent *event, Boolean *cont);
1836
1837 static void
1838 do_isearch_cancel(struct search_settings *settings)
1839 {
1840 static const char default_key_translations[] =
1841 "\"0\":digit(0)\n"
1842 "\"1\":digit(1)\n"
1843 "\"2\":digit(2)\n"
1844 "\"3\":digit(3)\n"
1845 "\"4\":digit(4)\n"
1846 "\"5\":digit(5)\n"
1847 "\"6\":digit(6)\n"
1848 "\"7\":digit(7)\n"
1849 "\"8\":digit(8)\n"
1850 "\"9\":digit(9)\n"
1851 /* "\"-\":minus()\n" */
1852 "<Motion>:motion()\n";
1853
1854 static const char default_mouse_translations[] =
1855 "<BtnUp>:release()";
1856
1857
1858 statusline_info(STATUS_SHORT, "I-search stopped.");
1859
1860 free(settings->isearchterm);
1861 settings->isearchterm = NULL;
1862 settings->searchinfo->from_pos = settings->searchinfo->to_pos = 0;
1863 settings->from_page = current_page;
1864 erase_match_highlighting(m_info, True);
1865
1866
1867
1868 /* restore translations */
1869 XtOverrideTranslations(globals.widgets.top_level, XtParseTranslationTable(base_key_translations));
1870 XtOverrideTranslations(globals.widgets.top_level, XtParseTranslationTable(default_key_translations));
1871 XtOverrideTranslations(globals.widgets.top_level, XtParseTranslationTable(base_mouse_translations));
1872 XtOverrideTranslations(globals.widgets.top_level, XtParseTranslationTable(default_mouse_translations));
1873
1874 XtOverrideTranslations(globals.widgets.draw_widget, XtParseTranslationTable(base_key_translations));
1875 XtOverrideTranslations(globals.widgets.draw_widget, XtParseTranslationTable(default_key_translations));
1876 XtOverrideTranslations(globals.widgets.draw_widget, XtParseTranslationTable(base_mouse_translations));
1877 XtOverrideTranslations(globals.widgets.draw_widget, XtParseTranslationTable(default_mouse_translations));
1878
1879 XtOverrideTranslations(globals.widgets.clip_widget, XtParseTranslationTable(base_key_translations));
1880 XtOverrideTranslations(globals.widgets.clip_widget, XtParseTranslationTable(default_key_translations));
1881 XtOverrideTranslations(globals.widgets.clip_widget, XtParseTranslationTable(base_mouse_translations));
1882 XtOverrideTranslations(globals.widgets.clip_widget, XtParseTranslationTable(default_mouse_translations));
1883
1884 if (resource.main_translations != NULL) {
1885 XtOverrideTranslations(globals.widgets.draw_widget, XtParseTranslationTable(resource.main_translations));
1886 XtOverrideTranslations(globals.widgets.clip_widget, XtParseTranslationTable(resource.main_translations));
1887 }
1888
1889 XtRemoveEventHandler(globals.widgets.top_level, KeyPressMask|KeyReleaseMask, False,
1890 cb_isearch, (XtPointer)settings);
1891 XtRemoveEventHandler(globals.widgets.draw_widget, KeyPressMask|KeyReleaseMask, False,
1892 cb_isearch, (XtPointer)settings);
1893 XtRemoveEventHandler(globals.widgets.clip_widget, KeyPressMask|KeyReleaseMask, False,
1894 cb_isearch, (XtPointer)settings);
1895 }
1896
1897 static void
1898 cb_isearch(Widget w, XtPointer closure, XEvent *event, Boolean *cont)
1899 {
1900 struct search_settings *settings = (struct search_settings *)closure;
1901
1902 UNUSED(w);
1903 UNUSED(cont);
1904
1905 if (settings->isearchterm == NULL)
1906 settings->isearchterm = xstrdup("");
1907
1908 if (event->type == KeyPress) {
1909 char buf[48];
1910 KeySym keysym;
1911 int count;
1912 /* temporarily disable control mask; this gives better results with XLookupString() */
1913 const unsigned int save_state = event->xkey.state;
1914 /* event->xkey.state &= ~ControlMask; */
1915 count = XLookupString(&(event->xkey), buf, 48, &keysym, NULL);
1916 event->xkey.state = save_state;
1917 if (count > 0) {
1918 /* Ctrl-g and Ctrl-f continue isearch and
1919 switch to the search window, respectively */
1920 if (event->xkey.state & ControlMask) {
1921 if (keysym == XK_g) {
1922 settings->term = settings->isearchterm;
1923 isearch_start(); /* restart search */
1924 return;
1925 }
1926 else if (keysym == XK_f) {
1927 static char *str = NULL;
1928 if (str != NULL) {
1929 free(str);
1930 }
1931 str = xstrdup(settings->isearchterm);
1932 do_isearch_cancel(settings);
1933 TRACE_FIND((stderr, "restarting search: %s", str));
1934 dvi_find_string(str, False);
1935 return;
1936 }
1937 }
1938 if (keysym == XK_Escape) {
1939 do_isearch_cancel(settings);
1940 return;
1941 }
1942 if (keysym == XK_BackSpace || keysym == XK_Delete) {
1943 size_t len = strlen(settings->isearchterm);
1944 if (len > 0) {
1945 settings->isearchterm = xrealloc(settings->isearchterm, len);
1946 settings->isearchterm[len - 1] = '\0';
1947 /* statusline_info(STATUS_FOREVER, "I-search (ESC to exit): %s", settings->posix_term); */
1948 }
1949 else {
1950 xdvi_bell();
1951 }
1952 }
1953 else if (keysym >= XK_Shift_L && keysym <= XK_Hyper_R) {
1954 fprintf(stderr, "keysym %ld: Modifier %s\n", keysym, XKeysymToString(keysym));
1955 }
1956 else if (keysym == XK_Return || keysym == XK_KP_Enter || keysym == XK_Linefeed) { /* TODO */
1957 settings->term = settings->isearchterm;
1958 isearch_start(); /* restart search */
1959 return;
1960 /* statusline_info(STATUS_FOREVER, "I-search (ESC to exit): %s (next match)", settings->isearchterm); */
1961 }
1962 else if ((keysym >= XK_KP_Space && keysym <= XK_KP_9)
1963 || (keysym >= XK_space && keysym <= XK_asciitilde)
1964 || (keysym >= XK_exclamdown && keysym <= XK_ydiaeresis)
1965 || (keysym >= XK_F1 && keysym <= XK_F35)) {
1966 settings->isearchterm = xstrcat(settings->isearchterm, buf);
1967 /* statusline_info(STATUS_FOREVER, "I-search (ESC to exit): %s", settings->posix_term); */
1968 }
1969 else { /* TODO: abort search? */
1970 xdvi_bell();
1971 TRACE_FIND((stderr, "keysym %ld: %s is not handled", keysym, XKeysymToString(keysym)));
1972 }
1973
1974 if (settings->isearchterm[0] != '\0') {
1975 /* const char *prefix = ""; */
1976 /* fprintf(stderr, "cb_isearch called!\n"); */
1977 /* if (settings->wrapcnt > 0) */
1978 /* prefix = "Wrapped "; */
1979 /* statusline_info(STATUS_FOREVER, "%sI-search (ESC to exit): %s", prefix, settings->isearchterm); */
1980 settings->from_page = current_page;
1981 settings->message_window = 0;
1982 /* settings->wrapcnt = 0; */
1983 settings->term = settings->isearchterm;
1984 search_dvi((XtPointer)settings);
1985 }
1986 }
1987 }
1988
1989 }
1990
1991 #ifdef MOTIF
1992 #define XTranslations XmNtranslations
1993 #else
1994 #define XTranslations XtNtranslations
1995 #endif
1996
1997 /* static void */
1998 /* isearch_cancel(Widget w, XEvent *event, String *params, Cardinal *num_params) */
1999 /* { */
2000 /* struct search_settings *settings = NULL; */
2001 /* void *ptr; */
2002
2003 /* UNUSED(w); */
2004 /* UNUSED(event); */
2005
2006 /* if (*num_params < 1) { */
2007 /* XDVI_WARNING((stderr, "Wrong argument number (%d) in callback!", *num_params)); */
2008 /* return; */
2009 /* } */
2010 /* sscanf(*params, "%p", &ptr); */
2011 /* settings = (struct search_settings *)ptr; */
2012 /* do_isearch_cancel(settings); */
2013 /* } */
2014
2015
2016 /* static XtActionsRec isearch_actions[] = { */
2017 /* {"CancelIsearch", isearch_cancel }, */
2018 /* }; */
2019
2020 void isearch_start(void)
2021 {
2022 /* char *ptr = NULL; */
2023 XtTranslations empty_trans;
2024 static struct search_settings settings = {
2025 NULL, NULL, NULL,
2026 False, False, False, False,
2027 False, 0,
2028 NULL, /* isearchterm */
2029 SEARCH_DOWN, NULL,
2030 0, 0,
2031 0, 0, 0,
2032 0, NULL
2033 };
2034 static struct search_info searchinfo = {
2035 False, False, False,
2036 0, 0, 0, 0
2037 };
2038 static int wrapcnt_bak = 0;
2039
2040 settings.searchinfo = &searchinfo;
2041
2042 if (settings.isearchterm) { /* already running a search, jump to next match */
2043 settings.searchinfo->from_pos = settings.searchinfo->to_pos;
2044 if (settings.wrapcnt > wrapcnt_bak) { /* search wrapped */
2045 wrapcnt_bak = settings.wrapcnt;
2046 search_restart((XtPointer)&settings);
2047 }
2048 else {
2049 wrapcnt_bak = settings.wrapcnt;
2050 search_dvi((XtPointer)&settings);
2051 }
2052 return;
2053 }
2054
2055 settings.wrapcnt = 0;
2056
2057 /* ptr = get_string_va("<Key>osfCancel:CancelIsearch(%p)", (void *)&settings); */
2058 /* empty_trans = XtParseTranslationTable(ptr); */
2059 empty_trans = XtParseTranslationTable("");
2060 /* free(ptr); */
2061 /* XtAddActions(isearch_actions, XtNumber(isearch_actions)); */
2062
2063 statusline_info(STATUS_FOREVER, "I-search (ESC to exit): ");
2064 XtVaSetValues(globals.widgets.top_level, XTranslations, empty_trans, NULL);
2065 XtAddEventHandler(globals.widgets.top_level, KeyPressMask|KeyReleaseMask, False,
2066 cb_isearch, (XtPointer)&settings);
2067
2068 XtVaSetValues(globals.widgets.draw_widget, XTranslations, empty_trans, NULL);
2069 XtAddEventHandler(globals.widgets.draw_widget, KeyPressMask|KeyReleaseMask, False,
2070 cb_isearch, (XtPointer)&settings);
2071
2072 XtVaSetValues(globals.widgets.clip_widget, XTranslations, empty_trans, NULL);
2073 XtAddEventHandler(globals.widgets.clip_widget, KeyPressMask|KeyReleaseMask, False,
2074 cb_isearch, (XtPointer)&settings);
2075 }
2076