1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
|
/***************************************************************************
* Copyright (C) 2012 by Hans-Peter Deifel *
* hpdeifel@gmx.de *
* *
* 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., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301 USA. *
***************************************************************************/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <regex.h>
#include <getopt.h>
#include <unistd.h>
#include <math.h>
#include <sys/ioctl.h>
#include <fnmatch.h>
#include <errno.h>
#include <dirent.h>
#include <sys/stat.h>
#include <cpp/poppler-document.h>
#include <cpp/poppler-page.h>
#ifdef HAVE_UNAC
#include <unac.h>
#endif
#include <memory>
#include "output.h"
#include "exclude.h"
/* set this to 1 if any match was found. Used for the exit status */
int found_something = 0;
/* default options */
int ignore_case = 0;
int f_recursive_search = 0;
/* characters of context to put around each match.
* -1 means: print whole line
* -2 means: try to fit context into terminal */
int context = -2;
int line_width = 80;
int count = 0;
int quiet = 0;
#ifdef HAVE_UNAC
int use_unac = 0;
#endif
struct outconf outconf = {
-1, /* filename */
0, /* pagenum */
1, /* color */
};
enum {
HELP_OPTION,
COLOR_OPTION,
EXCLUDE_OPTION,
INCLUDE_OPTION,
#ifdef HAVE_UNAC
UNAC_OPTION,
#endif
};
struct option long_options[] =
{
{"ignore-case", 0, 0, 'i'},
{"page-number", 0, 0, 'n'},
{"with-filename", 0, 0, 'H'},
{"no-filename", 0, 0, 'h'},
{"count", 0, 0, 'c'},
{"color", 1, 0, COLOR_OPTION},
{"context", 1, 0, 'C'},
{"recursive", 0, 0, 'r'},
{"recursive", 0, 0, 'R'},
{"exclude", 1, 0, EXCLUDE_OPTION},
{"include", 1, 0, INCLUDE_OPTION},
{"help", 0, 0, HELP_OPTION},
{"version", 0, 0, 'V'},
{"quiet", 0, 0, 'q'},
#ifdef HAVE_UNAC
{"unac", 0, 0, UNAC_OPTION},
#endif
{0, 0, 0, 0}
};
ExcludeList excludes;
ExcludeList includes;
void regmatch_to_match(const regmatch_t match, int index, struct match *mt)
{
mt->start = match.rm_so + index;
mt->end = match.rm_eo + index;
}
#ifdef HAVE_UNAC
/* convenience layer over libunac. The result has to be freed with
* simple_unac_free */
char *simple_unac(char *string)
{
if (!use_unac)
return string;
char *res = NULL;
size_t reslen = 0;
if (unac_string("UTF-8", string, strlen(string), &res, &reslen)) {
perror("pdfgrep: Failed to remove accents: ");
return strdup(string);
}
return res;
}
void simple_unac_free(char *string)
{
if (use_unac)
free(string);
}
#endif
int search_in_document(poppler::document *doc, const std::string &filename, regex_t *needle)
{
regmatch_t match[] = {{0, 0}};
int count_matches = 0;
int length = 0;
struct context cntxt = {context, 0, (char*)filename.c_str(), 0, &outconf};
for (int i = 1; i <= doc->pages(); i++) {
std::auto_ptr<poppler::page> doc_page(doc->create_page(i - 1));
if (!doc_page.get()) {
if (!quiet) {
fprintf(stderr, "pdfgrep: Could not search in page %d of %s\n", i, filename.c_str());
}
continue;
}
cntxt.pagenum = i;
poppler::byte_array str = doc_page->text().to_utf8();
str.resize(str.size() + 1, '\0');
#ifdef HAVE_UNAC
char *unac_str = simple_unac(&str[0]);
char *str_start = unac_str;
#else
char *str_start = &str[0];
#endif
int index = 0;
struct match mt = {str_start, str.size()};
while (!regexec(needle, str_start+index, 1, match, 0)) {
regmatch_to_match(match[0], index, &mt);
count_matches++;
if (quiet) {
#ifdef HAVE_UNAC
simple_unac_free(unac_str);
#endif
goto clean;
} else if (!count) {
switch (context) {
/* print whole line */
case -1:
print_context_line(&cntxt, &mt);
break;
/* try to guess the terminal width */
case -2:
/* Calculate the length of the line prefix:
* filename:linenumber: */
length = 0;
if (outconf.filename)
length += 1 + filename.size();
if (outconf.pagenum)
length += 1 + (int)log10(i);
length += match[0].rm_eo - match[0].rm_so;
cntxt.before = line_width - length;
print_context_chars(&cntxt, &mt);
break;
/* print a fixed context */
default:
print_context_chars(&cntxt, &mt);
break;
}
printf("\n");
}
found_something = 1;
index += match[0].rm_so + 1;
}
#ifdef HAVE_UNAC
simple_unac_free(unac_str);
#endif
}
if (count && !quiet) {
print_line_prefix(&outconf, filename.c_str(), -1);
printf("%d\n", count_matches);
}
clean:
return count_matches;
}
/* parses a color pair like "foo=bar" to "foo" and "bar" */
void parse_env_color_pair(char* pair, char** name, char** value)
{
*name = pair;
int i = 0;
while (pair[i] != '\0' && pair[i] != '=') {
i++;
}
if (pair[i] == '=') {
/* value starts one char after '=' */
*value = pair+i+1;
/* and replace '=' by '\0' */
pair[i] = '\0';
} else { /* if pair[i] == '\0' */
/* let value point to the '\0' */
*value = pair+i;
}
}
/* set colors of output according to content of environment-varaible env_var.
the content of env_var has to be like the GREP_COLORS variable for grep
see man 1 grep for further details of GREP_COLORS */
void read_colors_from_env(const char* env_var)
{
/* create a copy of var to edit it with strtok */
if (!getenv(env_var)) {
return;
}
char* colors_list = strdup(getenv(env_var));
if (!colors_list) {
/* if var is not set */
return;
}
/* save original length _before_ editing it with strtok */
int colors_list_len = strlen(colors_list);
int i = 0;
char* cur_color_pair;
char *cur_name, *cur_value;
/* read all color=value pairs */
while (i < colors_list_len && (cur_color_pair = strtok(colors_list+i, ":"))) {
/* set index i to next color pair */
i += strlen(cur_color_pair); /* skip token content */
i += 1; /* skip delemiter */
/* get name and value of color pair */
parse_env_color_pair(cur_color_pair, &cur_name, &cur_value);
#define PARSE_COLOR(GREP_NAME, GLOBAL_VAR) \
if (!strcmp(cur_name, GREP_NAME)) { \
free(GLOBAL_VAR); /* free old value */ \
GLOBAL_VAR = strdup(cur_value); /* set to new color */ \
}
/* now check for known settings and set global colors */
PARSE_COLOR("mt", outconf.colors.highlight)
else PARSE_COLOR("ms", outconf.colors.highlight)
else PARSE_COLOR("mc", outconf.colors.highlight)
else PARSE_COLOR("fn", outconf.colors.filename)
else PARSE_COLOR("ln", outconf.colors.pagenum)
else PARSE_COLOR("se", outconf.colors.separator)
#undef PARSE_COLOR
}
/* free our copy of the environment var */
free(colors_list);
}
void set_default_colors()
{
outconf.colors.filename = strdup("35");
outconf.colors.pagenum = strdup("32");
outconf.colors.highlight = strdup("01;31");
outconf.colors.separator = strdup("36");
}
void free_colors()
{
free(outconf.colors.filename);
free(outconf.colors.pagenum);
free(outconf.colors.highlight);
free(outconf.colors.separator);
}
void init_colors()
{
set_default_colors();
/* free colors, when programm exits */
atexit(free_colors);
}
/* return the terminal line width or line_width
* if the former is not available */
int get_line_width()
{
const char *v = getenv("COLUMNS");
int width = line_width;
if (v && *v)
width = atoi(v);
struct winsize ws;
if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && 0 < ws.ws_col)
width = ws.ws_col;
if (width > 0)
return width;
return line_width;
}
void print_usage(char *self)
{
printf("Usage: %s [OPTION]... PATTERN FILE...\n", self);
}
void print_help(char *self)
{
print_usage(self);
printf("\nSearch for PATTERN in each FILE.\n"
"PATTERN is an extended regular expression.\n\n"
"Options:\n"
" -i, --ignore-case\t\tIgnore case distinctions\n"
" -H, --with-filename\t\tPrint the file name for each match\n"
" -h, --no-filename\t\tSuppress the prefixing of file name on output\n"
" -n, --page-number\t\tPrint page number with output lines\n"
" -c, --count\t\t\tPrint only a count of matches per file\n"
" -C, --context NUM\t\tPrint at most NUM chars of context\n"
" --color WHEN\t\tUse colors for highlighting;\n"
"\t\t\t\tWHEN can be `always', `never' or `auto'\n"
" -q, --quiet\t\t\tSuppress normal output\n"
" -R, --recursive\t\tSearch directories recursively\n"
" --help\t\t\tPrint this help\n"
" -V, --version\t\t\tShow version information\n");
}
void print_version()
{
printf("This is %s version %s\n", PACKAGE, VERSION);
}
int is_dir(const std::string filename)
{
struct stat st;
if (stat(filename.c_str(), &st) == 0 && S_ISDIR(st.st_mode))
return 1;
else
return 0;
}
int do_search_in_document(const std::string path, const std::string filename,
regex_t *ptrRegex, bool check_excludes = true)
{
if (check_excludes &&
(!is_excluded(includes, filename) || is_excluded(excludes, filename)))
return 0;
std::auto_ptr<poppler::document> doc(poppler::document::load_from_file(path));
if (!doc.get() || doc->is_locked()) {
fprintf(stderr, "pdfgrep: Could not open %s\n",
path.c_str());
return 1;
}
if (search_in_document(doc.get(), path, ptrRegex) && quiet) {
exit(0);
}
return 0;
}
int do_search_in_directory(const std::string filename, regex_t *ptrRegex)
{
DIR *ptrDir = NULL;
struct dirent *ptrDirent = NULL;
ptrDir = opendir(filename.c_str());
if (!ptrDir) {
fprintf(stderr, "pdfgrep: %s: %s\n", filename.c_str(),
strerror(errno));
return 1;
}
while(1) {
std::string path(filename);
errno = 0;
ptrDirent = readdir(ptrDir); //not sorted, in order as `ls -f`
if (!ptrDirent)
break;
if (!strcmp(ptrDirent->d_name, ".") || !strcmp(ptrDirent->d_name, ".."))
continue;
path += "/";
path += ptrDirent->d_name;
if (is_dir(path)) {
do_search_in_directory(path, ptrRegex);
} else {
do_search_in_document(path, ptrDirent->d_name, ptrRegex);
}
}
closedir(ptrDir);
return 0;
}
int main(int argc, char** argv)
{
regex_t regex;
init_colors();
while (1) {
int c = getopt_long(argc, argv, "icC:nrRhHVq",
long_options, NULL);
if (c == -1)
break;
switch (c) {
case HELP_OPTION:
print_help(argv[0]);
exit(0);
case 'V':
print_version();
exit(0);
case 'n':
outconf.pagenum = 1;
break;
case 'r':
case 'R':
f_recursive_search = 1;
break;
case 'h':
outconf.filename = 0;
break;
case 'H':
outconf.filename = 1;
break;
case 'i':
ignore_case = REG_ICASE;
break;
case 'c':
count = 1;
break;
case COLOR_OPTION:
if (!optarg)
break;
if (!strcmp("always", optarg)) {
outconf.color = 2;
} else if (!strcmp("never", optarg)) {
outconf.color = 0;
} else {
outconf.color = 1;
}
break;
case 'C':
if (optarg) {
if (!strcmp(optarg, "line")) {
context = -1;
} else {
context = atoi(optarg);
}
}
break;
case EXCLUDE_OPTION:
exclude_add(excludes, optarg);
break;
case INCLUDE_OPTION:
exclude_add(includes, optarg);
break;
case 'q':
quiet = 1;
break;
#ifdef HAVE_UNAC
case UNAC_OPTION:
use_unac = 1;
break;
#endif
case '?':
/* TODO: do something here */
break;
default:
break;
}
}
if (argc - optind < 2) {
print_usage(argv[0]);
exit(2);
}
char *pattern = argv[optind++];
#ifdef HAVE_UNAC
pattern = simple_unac(pattern);
#endif
int error = regcomp(®ex, pattern, REG_EXTENDED | ignore_case);
if (error) {
char err_msg[256];
regerror(error, ®ex, err_msg, 256);
fprintf(stderr, "pdfgrep: %s\n", err_msg);
exit(2);
}
bool color_tty = isatty(STDOUT_FILENO) && getenv("TERM") &&
strcmp(getenv("TERM"), "dumb");
if (outconf.color == 1 && !color_tty) {
outconf.color = 0;
}
if (outconf.color) read_colors_from_env("GREP_COLORS");
if (outconf.filename < 0) {
if ((argc - optind) == 1 && !is_dir(argv[optind])) {
outconf.filename = 0;
} else
outconf.filename = 1;
}
if (isatty(STDOUT_FILENO))
line_width = get_line_width();
if (excludes_empty(includes))
exclude_add(includes, "*.pdf");
error = 0;
for (int i = optind; i < argc; i++) {
const std::string filename(argv[i]);
if (!is_dir(filename)) {
do_search_in_document(filename, filename, ®ex,false);
} else if (f_recursive_search) {
do_search_in_directory(filename, ®ex);
} else { // TODO: report errors
error = 1;
}
}
if (error) {
exit(2);
} else if (found_something) {
exit(0);
} else {
exit(1);
}
}
/* vim: set noet: */
|