less.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini less implementation for busybox
  4. *
  5. * Copyright (C) 2005 by Rob Sullivan <cogito.ergo.cogito@gmail.com>
  6. *
  7. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  8. */
  9. /*
  10. * TODO:
  11. * - Add more regular expression support - search modifiers, certain matches, etc.
  12. * - Add more complex bracket searching - currently, nested brackets are
  13. * not considered.
  14. * - Add support for "F" as an input. This causes less to act in
  15. * a similar way to tail -f.
  16. * - Allow horizontal scrolling.
  17. *
  18. * Notes:
  19. * - the inp file pointer is used so that keyboard input works after
  20. * redirected input has been read from stdin
  21. */
  22. #include "busybox.h"
  23. #if ENABLE_FEATURE_LESS_REGEXP
  24. #include "xregex.h"
  25. #endif
  26. /* FIXME: currently doesn't work right */
  27. #undef ENABLE_FEATURE_LESS_FLAGCS
  28. #define ENABLE_FEATURE_LESS_FLAGCS 0
  29. /* The escape codes for highlighted and normal text */
  30. #define HIGHLIGHT "\033[7m"
  31. #define NORMAL "\033[0m"
  32. /* The escape code to clear the screen */
  33. #define CLEAR "\033[H\033[J"
  34. /* The escape code to clear to end of line */
  35. #define CLEAR_2_EOL "\033[K"
  36. /* These are the escape sequences corresponding to special keys */
  37. enum {
  38. REAL_KEY_UP = 'A',
  39. REAL_KEY_DOWN = 'B',
  40. REAL_KEY_RIGHT = 'C',
  41. REAL_KEY_LEFT = 'D',
  42. REAL_PAGE_UP = '5',
  43. REAL_PAGE_DOWN = '6',
  44. REAL_KEY_HOME = '7',
  45. REAL_KEY_END = '8',
  46. /* These are the special codes assigned by this program to the special keys */
  47. KEY_UP = 20,
  48. KEY_DOWN = 21,
  49. KEY_RIGHT = 22,
  50. KEY_LEFT = 23,
  51. PAGE_UP = 24,
  52. PAGE_DOWN = 25,
  53. KEY_HOME = 26,
  54. KEY_END = 27,
  55. /* Absolute max of lines eaten */
  56. MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
  57. /* This many "after the end" lines we will show (at max) */
  58. TILDES = 1,
  59. };
  60. static unsigned max_displayed_line;
  61. static unsigned width;
  62. static const char *empty_line_marker = "~";
  63. static char *filename;
  64. static char **files;
  65. static unsigned num_files = 1;
  66. static unsigned current_file = 1;
  67. static const char **buffer;
  68. static const char **flines;
  69. static int cur_fline; /* signed */
  70. static unsigned max_fline;
  71. static unsigned max_lineno; /* this one tracks linewrap */
  72. static ssize_t eof_error = 1; /* eof if 0, error if < 0 */
  73. static char terminated = 1;
  74. static size_t readpos;
  75. static size_t readeof;
  76. /* last position in last line, taking into account tabs */
  77. static size_t linepos;
  78. /* Command line options */
  79. enum {
  80. FLAG_E = 1,
  81. FLAG_M = 1 << 1,
  82. FLAG_m = 1 << 2,
  83. FLAG_N = 1 << 3,
  84. FLAG_TILDE = 1 << 4,
  85. /* hijack command line options variable for internal state vars */
  86. LESS_STATE_MATCH_BACKWARDS = 1 << 15,
  87. };
  88. #if ENABLE_FEATURE_LESS_MARKS
  89. static unsigned mark_lines[15][2];
  90. static unsigned num_marks;
  91. #endif
  92. #if ENABLE_FEATURE_LESS_REGEXP
  93. static unsigned *match_lines;
  94. static int match_pos; /* signed! */
  95. static unsigned num_matches;
  96. static regex_t pattern;
  97. static unsigned pattern_valid;
  98. #else
  99. enum { pattern_valid = 0 };
  100. #endif
  101. static struct termios term_orig, term_vi;
  102. /* File pointer to get input from */
  103. static int kbd_fd;
  104. /* Reset terminal input to normal */
  105. static void set_tty_cooked(void)
  106. {
  107. fflush(stdout);
  108. tcsetattr(kbd_fd, TCSANOW, &term_orig);
  109. }
  110. /* Exit the program gracefully */
  111. static void less_exit(int code)
  112. {
  113. /* TODO: We really should save the terminal state when we start,
  114. * and restore it when we exit. Less does this with the
  115. * "ti" and "te" termcap commands; can this be done with
  116. * only termios.h? */
  117. putchar('\n');
  118. fflush_stdout_and_exit(code);
  119. }
  120. /* Move the cursor to a position (x,y), where (0,0) is the
  121. top-left corner of the console */
  122. static void move_cursor(int line, int row)
  123. {
  124. printf("\033[%u;%uH", line, row);
  125. }
  126. static void clear_line(void)
  127. {
  128. printf("\033[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
  129. }
  130. static void print_hilite(const char *str)
  131. {
  132. printf(HIGHLIGHT"%s"NORMAL, str);
  133. }
  134. static void print_statusline(const char *str)
  135. {
  136. clear_line();
  137. printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
  138. }
  139. #if ENABLE_FEATURE_LESS_REGEXP
  140. static void fill_match_lines(unsigned pos);
  141. #else
  142. #define fill_match_lines(pos) ((void)0)
  143. #endif
  144. static void read_lines(void)
  145. {
  146. #define readbuf bb_common_bufsiz1
  147. char *current_line, *p;
  148. USE_FEATURE_LESS_REGEXP(unsigned old_max_fline = max_fline;)
  149. int w = width;
  150. char last_terminated = terminated;
  151. if (option_mask32 & FLAG_N)
  152. w -= 8;
  153. current_line = xmalloc(w);
  154. p = current_line;
  155. max_fline += last_terminated;
  156. if (!last_terminated) {
  157. const char *cp = flines[max_fline];
  158. if (option_mask32 & FLAG_N)
  159. cp += 8;
  160. strcpy(current_line, cp);
  161. p += strlen(current_line);
  162. } else {
  163. linepos = 0;
  164. }
  165. while (1) {
  166. again:
  167. *p = '\0';
  168. terminated = 0;
  169. while (1) {
  170. char c;
  171. if (readpos >= readeof) {
  172. ndelay_on(0);
  173. eof_error = safe_read(0, readbuf, sizeof(readbuf));
  174. ndelay_off(0);
  175. readpos = 0;
  176. readeof = eof_error;
  177. if (eof_error < 0) {
  178. readeof = 0;
  179. if (errno != EAGAIN)
  180. print_statusline("read error");
  181. }
  182. if (eof_error <= 0) {
  183. goto reached_eof;
  184. }
  185. }
  186. c = readbuf[readpos];
  187. /* backspace? [needed for manpages] */
  188. /* <tab><bs> is (a) insane and */
  189. /* (b) harder to do correctly, so we refuse to do it */
  190. if (c == '\x8' && linepos && p[-1] != '\t') {
  191. readpos++; /* eat it */
  192. linepos--;
  193. *--p = '\0';
  194. continue;
  195. }
  196. if (c == '\t')
  197. linepos += (linepos^7) & 7;
  198. linepos++;
  199. if (linepos >= w)
  200. break;
  201. /* ok, we will eat this char */
  202. readpos++;
  203. if (c == '\n') { terminated = 1; break; }
  204. /* NUL is substituted by '\n'! */
  205. if (c == '\0') c = '\n';
  206. *p++ = c;
  207. *p = '\0';
  208. }
  209. /* Corner case: linewrap with only "" wrapping to next line */
  210. /* Looks ugly on screen, so we do not store this empty line */
  211. if (!last_terminated && !current_line[0]) {
  212. last_terminated = 1;
  213. max_lineno++;
  214. goto again;
  215. }
  216. reached_eof:
  217. last_terminated = terminated;
  218. flines = xrealloc(flines, (max_fline+1) * sizeof(char *));
  219. if (option_mask32 & FLAG_N) {
  220. /* Width of 7 preserves tab spacing in the text */
  221. flines[max_fline] = xasprintf(
  222. (max_lineno <= 9999999) ? "%7u %s" : "%07u %s",
  223. max_lineno % 10000000, current_line);
  224. free(current_line);
  225. if (terminated)
  226. max_lineno++;
  227. } else {
  228. flines[max_fline] = xrealloc(current_line, strlen(current_line)+1);
  229. }
  230. if (max_fline >= MAXLINES)
  231. break;
  232. if (max_fline > cur_fline + max_displayed_line)
  233. break;
  234. if (eof_error <= 0) {
  235. if (eof_error < 0 && errno == EAGAIN) {
  236. /* not yet eof or error, reset flag (or else
  237. * we will hog CPU - select() will return
  238. * immediately */
  239. eof_error = 1;
  240. }
  241. break;
  242. }
  243. max_fline++;
  244. current_line = xmalloc(w);
  245. p = current_line;
  246. linepos = 0;
  247. }
  248. fill_match_lines(old_max_fline);
  249. #undef readbuf
  250. }
  251. #if ENABLE_FEATURE_LESS_FLAGS
  252. /* Interestingly, writing calc_percent as a function saves around 32 bytes
  253. * on my build. */
  254. static int calc_percent(void)
  255. {
  256. unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
  257. return p <= 100 ? p : 100;
  258. }
  259. /* Print a status line if -M was specified */
  260. static void m_status_print(void)
  261. {
  262. int percentage;
  263. clear_line();
  264. printf(HIGHLIGHT"%s", filename);
  265. if (num_files > 1)
  266. printf(" (file %i of %i)", current_file, num_files);
  267. printf(" lines %i-%i/%i ",
  268. cur_fline + 1, cur_fline + max_displayed_line + 1,
  269. max_fline + 1);
  270. if (cur_fline >= max_fline - max_displayed_line) {
  271. printf("(END)"NORMAL);
  272. if (num_files > 1 && current_file != num_files)
  273. printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
  274. return;
  275. }
  276. percentage = calc_percent();
  277. printf("%i%%"NORMAL, percentage);
  278. }
  279. #endif
  280. /* Print the status line */
  281. static void status_print(void)
  282. {
  283. const char *p;
  284. /* Change the status if flags have been set */
  285. #if ENABLE_FEATURE_LESS_FLAGS
  286. if (option_mask32 & (FLAG_M|FLAG_m)) {
  287. m_status_print();
  288. return;
  289. }
  290. /* No flags set */
  291. #endif
  292. clear_line();
  293. if (cur_fline && cur_fline < max_fline - max_displayed_line) {
  294. putchar(':');
  295. return;
  296. }
  297. p = "(END)";
  298. if (!cur_fline)
  299. p = filename;
  300. if (num_files > 1) {
  301. printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
  302. p, current_file, num_files);
  303. return;
  304. }
  305. print_hilite(p);
  306. }
  307. static char controls[] =
  308. /* NUL: never encountered; TAB: not converted */
  309. /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
  310. "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
  311. "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
  312. static char ctrlconv[] =
  313. /* '\n': it's a former NUL - subst with '@', not 'J' */
  314. "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
  315. "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
  316. #if ENABLE_FEATURE_LESS_REGEXP
  317. static void print_found(const char *line)
  318. {
  319. int match_status;
  320. int eflags;
  321. char *growline;
  322. regmatch_t match_structs;
  323. char buf[width];
  324. const char *str = line;
  325. char *p = buf;
  326. size_t n;
  327. while (*str) {
  328. n = strcspn(str, controls);
  329. if (n) {
  330. if (!str[n]) break;
  331. memcpy(p, str, n);
  332. p += n;
  333. str += n;
  334. }
  335. n = strspn(str, controls);
  336. memset(p, '.', n);
  337. p += n;
  338. str += n;
  339. }
  340. strcpy(p, str);
  341. /* buf[] holds quarantined version of str */
  342. /* Each part of the line that matches has the HIGHLIGHT
  343. and NORMAL escape sequences placed around it.
  344. NB: we regex against line, but insert text
  345. from quarantined copy (buf[]) */
  346. str = buf;
  347. growline = NULL;
  348. eflags = 0;
  349. goto start;
  350. while (match_status == 0) {
  351. char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
  352. growline ? : "",
  353. match_structs.rm_so, str,
  354. match_structs.rm_eo - match_structs.rm_so,
  355. str + match_structs.rm_so);
  356. free(growline); growline = new;
  357. str += match_structs.rm_eo;
  358. line += match_structs.rm_eo;
  359. eflags = REG_NOTBOL;
  360. start:
  361. /* Most of the time doesn't find the regex, optimize for that */
  362. match_status = regexec(&pattern, line, 1, &match_structs, eflags);
  363. }
  364. if (!growline) {
  365. printf(CLEAR_2_EOL"%s\n", str);
  366. return;
  367. }
  368. printf(CLEAR_2_EOL"%s%s\n", growline, str);
  369. free(growline);
  370. }
  371. #else
  372. void print_found(const char *line);
  373. #endif
  374. static void print_ascii(const char *str)
  375. {
  376. char buf[width];
  377. char *p;
  378. size_t n;
  379. printf(CLEAR_2_EOL);
  380. while (*str) {
  381. n = strcspn(str, controls);
  382. if (n) {
  383. if (!str[n]) break;
  384. printf("%.*s", (int) n, str);
  385. str += n;
  386. }
  387. n = strspn(str, controls);
  388. p = buf;
  389. do {
  390. if (*str == 0x7f)
  391. *p++ = '?';
  392. else if (*str == (char)0x9b)
  393. /* VT100's CSI, aka Meta-ESC. Who's inventor? */
  394. /* I want to know who committed this sin */
  395. *p++ = '{';
  396. else
  397. *p++ = ctrlconv[(unsigned char)*str];
  398. str++;
  399. } while (--n);
  400. *p = '\0';
  401. print_hilite(buf);
  402. }
  403. puts(str);
  404. }
  405. /* Print the buffer */
  406. static void buffer_print(void)
  407. {
  408. int i;
  409. move_cursor(0, 0);
  410. for (i = 0; i <= max_displayed_line; i++)
  411. if (pattern_valid)
  412. print_found(buffer[i]);
  413. else
  414. print_ascii(buffer[i]);
  415. status_print();
  416. }
  417. static void buffer_fill_and_print(void)
  418. {
  419. int i;
  420. for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
  421. buffer[i] = flines[cur_fline + i];
  422. }
  423. for (; i <= max_displayed_line; i++) {
  424. buffer[i] = empty_line_marker;
  425. }
  426. buffer_print();
  427. }
  428. /* Move the buffer up and down in the file in order to scroll */
  429. static void buffer_down(int nlines)
  430. {
  431. int diff;
  432. cur_fline += nlines;
  433. read_lines();
  434. if (cur_fline + max_displayed_line > max_fline + TILDES) {
  435. cur_fline -= nlines;
  436. diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
  437. /* As the number of lines requested was too large, we just move
  438. to the end of the file */
  439. if (diff > 0)
  440. cur_fline += diff;
  441. }
  442. buffer_fill_and_print();
  443. }
  444. static void buffer_up(int nlines)
  445. {
  446. cur_fline -= nlines;
  447. if (cur_fline < 0) cur_fline = 0;
  448. read_lines();
  449. buffer_fill_and_print();
  450. }
  451. static void buffer_line(int linenum)
  452. {
  453. if (linenum < 0)
  454. linenum = 0;
  455. cur_fline = linenum;
  456. read_lines();
  457. if (linenum + max_displayed_line > max_fline)
  458. linenum = max_fline - max_displayed_line + TILDES;
  459. cur_fline = linenum;
  460. buffer_fill_and_print();
  461. }
  462. static void open_file_and_read_lines(void)
  463. {
  464. if (filename) {
  465. int fd = xopen(filename, O_RDONLY);
  466. dup2(fd, 0);
  467. if (fd) close(fd);
  468. } else {
  469. /* "less" with no arguments in argv[] */
  470. /* For status line only */
  471. filename = xstrdup(bb_msg_standard_input);
  472. }
  473. readpos = 0;
  474. readeof = 0;
  475. linepos = 0;
  476. terminated = 1;
  477. read_lines();
  478. }
  479. /* Reinitialize everything for a new file - free the memory and start over */
  480. static void reinitialize(void)
  481. {
  482. int i;
  483. if (flines) {
  484. for (i = 0; i <= max_fline; i++)
  485. free((void*)(flines[i]));
  486. free(flines);
  487. flines = NULL;
  488. }
  489. max_fline = -1;
  490. cur_fline = 0;
  491. max_lineno = 0;
  492. open_file_and_read_lines();
  493. buffer_fill_and_print();
  494. }
  495. static void getch_nowait(char* input, int sz)
  496. {
  497. ssize_t rd;
  498. fd_set readfds;
  499. again:
  500. fflush(stdout);
  501. /* NB: select returns whenever read will not block. Therefore:
  502. * (a) with O_NONBLOCK'ed fds select will return immediately
  503. * (b) if eof is reached, select will also return
  504. * because read will immediately return 0 bytes.
  505. * Even if select says that input is available, read CAN block
  506. * (switch fd into O_NONBLOCK'ed mode to avoid it)
  507. */
  508. FD_ZERO(&readfds);
  509. if (max_fline <= cur_fline + max_displayed_line
  510. && eof_error > 0 /* did NOT reach eof yet */
  511. ) {
  512. /* We are interested in stdin */
  513. FD_SET(0, &readfds);
  514. }
  515. FD_SET(kbd_fd, &readfds);
  516. tcsetattr(kbd_fd, TCSANOW, &term_vi);
  517. select(kbd_fd + 1, &readfds, NULL, NULL, NULL);
  518. input[0] = '\0';
  519. ndelay_on(kbd_fd);
  520. rd = read(kbd_fd, input, sz);
  521. ndelay_off(kbd_fd);
  522. if (rd < 0) {
  523. /* No keyboard input, but we have input on stdin! */
  524. if (errno != EAGAIN) /* Huh?? */
  525. return;
  526. read_lines();
  527. buffer_fill_and_print();
  528. goto again;
  529. }
  530. }
  531. /* Grab a character from input without requiring the return key. If the
  532. * character is ASCII \033, get more characters and assign certain sequences
  533. * special return codes. Note that this function works best with raw input. */
  534. static int less_getch(void)
  535. {
  536. char input[16];
  537. unsigned i;
  538. again:
  539. getch_nowait(input, sizeof(input));
  540. /* Detect escape sequences (i.e. arrow keys) and handle
  541. * them accordingly */
  542. if (input[0] == '\033' && input[1] == '[') {
  543. set_tty_cooked();
  544. i = input[2] - REAL_KEY_UP;
  545. if (i < 4)
  546. return 20 + i;
  547. i = input[2] - REAL_PAGE_UP;
  548. if (i < 4)
  549. return 24 + i;
  550. return 0;
  551. }
  552. /* Reject almost all control chars */
  553. i = input[0];
  554. if (i < ' ' && i != 0x0d && i != 8) goto again;
  555. set_tty_cooked();
  556. return i;
  557. }
  558. static char* less_gets(int sz)
  559. {
  560. char c;
  561. int i = 0;
  562. char *result = xzalloc(1);
  563. while (1) {
  564. fflush(stdout);
  565. /* I be damned if I know why is it needed *repeatedly*,
  566. * but it is needed. Is it because of stdio? */
  567. tcsetattr(kbd_fd, TCSANOW, &term_vi);
  568. read(kbd_fd, &c, 1);
  569. if (c == 0x0d)
  570. return result;
  571. if (c == 0x7f)
  572. c = 8;
  573. if (c == 8 && i) {
  574. printf("\x8 \x8");
  575. i--;
  576. }
  577. if (c < ' ')
  578. continue;
  579. if (i >= width - sz - 1)
  580. continue; /* len limit */
  581. putchar(c);
  582. result[i++] = c;
  583. result = xrealloc(result, i+1);
  584. result[i] = '\0';
  585. }
  586. }
  587. static void examine_file(void)
  588. {
  589. print_statusline("Examine: ");
  590. free(filename);
  591. filename = less_gets(sizeof("Examine: ")-1);
  592. /* files start by = argv. why we assume that argv is infinitely long??
  593. files[num_files] = filename;
  594. current_file = num_files + 1;
  595. num_files++; */
  596. files[0] = filename;
  597. num_files = current_file = 1;
  598. reinitialize();
  599. }
  600. /* This function changes the file currently being paged. direction can be one of the following:
  601. * -1: go back one file
  602. * 0: go to the first file
  603. * 1: go forward one file */
  604. static void change_file(int direction)
  605. {
  606. if (current_file != ((direction > 0) ? num_files : 1)) {
  607. current_file = direction ? current_file + direction : 1;
  608. free(filename);
  609. filename = xstrdup(files[current_file - 1]);
  610. reinitialize();
  611. } else {
  612. print_statusline(direction > 0 ? "No next file" : "No previous file");
  613. }
  614. }
  615. static void remove_current_file(void)
  616. {
  617. int i;
  618. if (num_files < 2)
  619. return;
  620. if (current_file != 1) {
  621. change_file(-1);
  622. for (i = 3; i <= num_files; i++)
  623. files[i - 2] = files[i - 1];
  624. num_files--;
  625. } else {
  626. change_file(1);
  627. for (i = 2; i <= num_files; i++)
  628. files[i - 2] = files[i - 1];
  629. num_files--;
  630. current_file--;
  631. }
  632. }
  633. static void colon_process(void)
  634. {
  635. int keypress;
  636. /* Clear the current line and print a prompt */
  637. print_statusline(" :");
  638. keypress = less_getch();
  639. switch (keypress) {
  640. case 'd':
  641. remove_current_file();
  642. break;
  643. case 'e':
  644. examine_file();
  645. break;
  646. #if ENABLE_FEATURE_LESS_FLAGS
  647. case 'f':
  648. m_status_print();
  649. break;
  650. #endif
  651. case 'n':
  652. change_file(1);
  653. break;
  654. case 'p':
  655. change_file(-1);
  656. break;
  657. case 'q':
  658. less_exit(0);
  659. break;
  660. case 'x':
  661. change_file(0);
  662. break;
  663. }
  664. }
  665. #if ENABLE_FEATURE_LESS_REGEXP
  666. static int normalize_match_pos(int match)
  667. {
  668. match_pos = match;
  669. if (match >= num_matches)
  670. match_pos = num_matches - 1;
  671. if (match < 0)
  672. match_pos = 0;
  673. return match_pos;
  674. }
  675. static void goto_match(int match)
  676. {
  677. if (num_matches)
  678. buffer_line(match_lines[normalize_match_pos(match)]);
  679. }
  680. static void fill_match_lines(unsigned pos)
  681. {
  682. if (!pattern_valid)
  683. return;
  684. /* Run the regex on each line of the current file */
  685. while (pos <= max_fline) {
  686. /* If this line matches */
  687. if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
  688. /* and we didn't match it last time */
  689. && !(num_matches && match_lines[num_matches-1] == pos)
  690. ) {
  691. match_lines = xrealloc(match_lines, (num_matches+1) * sizeof(int));
  692. match_lines[num_matches++] = pos;
  693. }
  694. pos++;
  695. }
  696. }
  697. static void regex_process(void)
  698. {
  699. char *uncomp_regex, *err;
  700. /* Reset variables */
  701. free(match_lines);
  702. match_lines = NULL;
  703. match_pos = 0;
  704. num_matches = 0;
  705. if (pattern_valid) {
  706. regfree(&pattern);
  707. pattern_valid = 0;
  708. }
  709. /* Get the uncompiled regular expression from the user */
  710. clear_line();
  711. putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
  712. uncomp_regex = less_gets(1);
  713. if (!uncomp_regex[0]) {
  714. free(uncomp_regex);
  715. buffer_print();
  716. return;
  717. }
  718. /* Compile the regex and check for errors */
  719. err = regcomp_or_errmsg(&pattern, uncomp_regex, 0);
  720. free(uncomp_regex);
  721. if (err) {
  722. print_statusline(err);
  723. free(err);
  724. return;
  725. }
  726. pattern_valid = 1;
  727. match_pos = 0;
  728. fill_match_lines(0);
  729. if (num_matches == 0 || max_fline <= max_displayed_line) {
  730. buffer_print();
  731. return;
  732. }
  733. while (match_pos < num_matches) {
  734. if (match_lines[match_pos] > cur_fline)
  735. break;
  736. match_pos++;
  737. }
  738. if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
  739. match_pos--;
  740. buffer_line(match_lines[normalize_match_pos(match_pos)]);
  741. }
  742. #endif
  743. static void number_process(int first_digit)
  744. {
  745. int i = 1;
  746. int num;
  747. char num_input[sizeof(int)*4]; /* more than enough */
  748. char keypress;
  749. num_input[0] = first_digit;
  750. /* Clear the current line, print a prompt, and then print the digit */
  751. clear_line();
  752. printf(":%c", first_digit);
  753. /* Receive input until a letter is given */
  754. while (i < sizeof(num_input)-1) {
  755. num_input[i] = less_getch();
  756. if (!num_input[i] || !isdigit(num_input[i]))
  757. break;
  758. putchar(num_input[i]);
  759. i++;
  760. }
  761. /* Take the final letter out of the digits string */
  762. keypress = num_input[i];
  763. num_input[i] = '\0';
  764. num = bb_strtou(num_input, NULL, 10);
  765. /* on format error, num == -1 */
  766. if (num < 1 || num > MAXLINES) {
  767. buffer_print();
  768. return;
  769. }
  770. /* We now know the number and the letter entered, so we process them */
  771. switch (keypress) {
  772. case KEY_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
  773. buffer_down(num);
  774. break;
  775. case KEY_UP: case 'b': case 'w': case 'y': case 'u':
  776. buffer_up(num);
  777. break;
  778. case 'g': case '<': case 'G': case '>':
  779. cur_fline = num + max_displayed_line;
  780. read_lines();
  781. buffer_line(num - 1);
  782. break;
  783. case 'p': case '%':
  784. num = num * (max_fline / 100); /* + max_fline / 2; */
  785. cur_fline = num + max_displayed_line;
  786. read_lines();
  787. buffer_line(num);
  788. break;
  789. #if ENABLE_FEATURE_LESS_REGEXP
  790. case 'n':
  791. goto_match(match_pos + num);
  792. break;
  793. case '/':
  794. option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
  795. regex_process();
  796. break;
  797. case '?':
  798. option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
  799. regex_process();
  800. break;
  801. #endif
  802. }
  803. }
  804. #if ENABLE_FEATURE_LESS_FLAGCS
  805. static void flag_change(void)
  806. {
  807. int keypress;
  808. clear_line();
  809. putchar('-');
  810. keypress = less_getch();
  811. switch (keypress) {
  812. case 'M':
  813. option_mask32 ^= FLAG_M;
  814. break;
  815. case 'm':
  816. option_mask32 ^= FLAG_m;
  817. break;
  818. case 'E':
  819. option_mask32 ^= FLAG_E;
  820. break;
  821. case '~':
  822. option_mask32 ^= FLAG_TILDE;
  823. break;
  824. }
  825. }
  826. static void show_flag_status(void)
  827. {
  828. int keypress;
  829. int flag_val;
  830. clear_line();
  831. putchar('_');
  832. keypress = less_getch();
  833. switch (keypress) {
  834. case 'M':
  835. flag_val = option_mask32 & FLAG_M;
  836. break;
  837. case 'm':
  838. flag_val = option_mask32 & FLAG_m;
  839. break;
  840. case '~':
  841. flag_val = option_mask32 & FLAG_TILDE;
  842. break;
  843. case 'N':
  844. flag_val = option_mask32 & FLAG_N;
  845. break;
  846. case 'E':
  847. flag_val = option_mask32 & FLAG_E;
  848. break;
  849. default:
  850. flag_val = 0;
  851. break;
  852. }
  853. clear_line();
  854. printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
  855. }
  856. #endif
  857. static void save_input_to_file(void)
  858. {
  859. const char *msg = "";
  860. char *current_line;
  861. int i;
  862. FILE *fp;
  863. print_statusline("Log file: ");
  864. current_line = less_gets(sizeof("Log file: ")-1);
  865. if (strlen(current_line) > 0) {
  866. fp = fopen(current_line, "w");
  867. if (!fp) {
  868. msg = "Error opening log file";
  869. goto ret;
  870. }
  871. for (i = 0; i <= max_fline; i++)
  872. fprintf(fp, "%s\n", flines[i]);
  873. fclose(fp);
  874. msg = "Done";
  875. }
  876. ret:
  877. print_statusline(msg);
  878. free(current_line);
  879. }
  880. #if ENABLE_FEATURE_LESS_MARKS
  881. static void add_mark(void)
  882. {
  883. int letter;
  884. print_statusline("Mark: ");
  885. letter = less_getch();
  886. if (isalpha(letter)) {
  887. /* If we exceed 15 marks, start overwriting previous ones */
  888. if (num_marks == 14)
  889. num_marks = 0;
  890. mark_lines[num_marks][0] = letter;
  891. mark_lines[num_marks][1] = cur_fline;
  892. num_marks++;
  893. } else {
  894. print_statusline("Invalid mark letter");
  895. }
  896. }
  897. static void goto_mark(void)
  898. {
  899. int letter;
  900. int i;
  901. print_statusline("Go to mark: ");
  902. letter = less_getch();
  903. clear_line();
  904. if (isalpha(letter)) {
  905. for (i = 0; i <= num_marks; i++)
  906. if (letter == mark_lines[i][0]) {
  907. buffer_line(mark_lines[i][1]);
  908. break;
  909. }
  910. if (num_marks == 14 && letter != mark_lines[14][0])
  911. print_statusline("Mark not set");
  912. } else
  913. print_statusline("Invalid mark letter");
  914. }
  915. #endif
  916. #if ENABLE_FEATURE_LESS_BRACKETS
  917. static char opp_bracket(char bracket)
  918. {
  919. switch (bracket) {
  920. case '{': case '[':
  921. return bracket + 2;
  922. case '(':
  923. return ')';
  924. case '}': case ']':
  925. return bracket - 2;
  926. case ')':
  927. return '(';
  928. }
  929. return 0;
  930. }
  931. static void match_right_bracket(char bracket)
  932. {
  933. int bracket_line = -1;
  934. int i;
  935. if (strchr(flines[cur_fline], bracket) == NULL) {
  936. print_statusline("No bracket in top line");
  937. return;
  938. }
  939. for (i = cur_fline + 1; i < max_fline; i++) {
  940. if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
  941. bracket_line = i;
  942. break;
  943. }
  944. }
  945. if (bracket_line == -1)
  946. print_statusline("No matching bracket found");
  947. buffer_line(bracket_line - max_displayed_line);
  948. }
  949. static void match_left_bracket(char bracket)
  950. {
  951. int bracket_line = -1;
  952. int i;
  953. if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
  954. print_statusline("No bracket in bottom line");
  955. return;
  956. }
  957. for (i = cur_fline + max_displayed_line; i >= 0; i--) {
  958. if (strchr(flines[i], opp_bracket(bracket)) != NULL) {
  959. bracket_line = i;
  960. break;
  961. }
  962. }
  963. if (bracket_line == -1)
  964. print_statusline("No matching bracket found");
  965. buffer_line(bracket_line);
  966. }
  967. #endif /* FEATURE_LESS_BRACKETS */
  968. static void keypress_process(int keypress)
  969. {
  970. switch (keypress) {
  971. case KEY_DOWN: case 'e': case 'j': case 0x0d:
  972. buffer_down(1);
  973. break;
  974. case KEY_UP: case 'y': case 'k':
  975. buffer_up(1);
  976. break;
  977. case PAGE_DOWN: case ' ': case 'z':
  978. buffer_down(max_displayed_line + 1);
  979. break;
  980. case PAGE_UP: case 'w': case 'b':
  981. buffer_up(max_displayed_line + 1);
  982. break;
  983. case 'd':
  984. buffer_down((max_displayed_line + 1) / 2);
  985. break;
  986. case 'u':
  987. buffer_up((max_displayed_line + 1) / 2);
  988. break;
  989. case KEY_HOME: case 'g': case 'p': case '<': case '%':
  990. buffer_line(0);
  991. break;
  992. case KEY_END: case 'G': case '>':
  993. cur_fline = MAXLINES;
  994. read_lines();
  995. buffer_line(cur_fline);
  996. break;
  997. case 'q': case 'Q':
  998. less_exit(0);
  999. break;
  1000. #if ENABLE_FEATURE_LESS_MARKS
  1001. case 'm':
  1002. add_mark();
  1003. buffer_print();
  1004. break;
  1005. case '\'':
  1006. goto_mark();
  1007. buffer_print();
  1008. break;
  1009. #endif
  1010. case 'r': case 'R':
  1011. buffer_print();
  1012. break;
  1013. /*case 'R':
  1014. full_repaint();
  1015. break;*/
  1016. case 's':
  1017. save_input_to_file();
  1018. break;
  1019. case 'E':
  1020. examine_file();
  1021. break;
  1022. #if ENABLE_FEATURE_LESS_FLAGS
  1023. case '=':
  1024. m_status_print();
  1025. break;
  1026. #endif
  1027. #if ENABLE_FEATURE_LESS_REGEXP
  1028. case '/':
  1029. option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
  1030. regex_process();
  1031. break;
  1032. case 'n':
  1033. goto_match(match_pos + 1);
  1034. break;
  1035. case 'N':
  1036. goto_match(match_pos - 1);
  1037. break;
  1038. case '?':
  1039. option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
  1040. regex_process();
  1041. break;
  1042. #endif
  1043. #if ENABLE_FEATURE_LESS_FLAGCS
  1044. case '-':
  1045. flag_change();
  1046. buffer_print();
  1047. break;
  1048. case '_':
  1049. show_flag_status();
  1050. break;
  1051. #endif
  1052. #if ENABLE_FEATURE_LESS_BRACKETS
  1053. case '{': case '(': case '[':
  1054. match_right_bracket(keypress);
  1055. break;
  1056. case '}': case ')': case ']':
  1057. match_left_bracket(keypress);
  1058. break;
  1059. #endif
  1060. case ':':
  1061. colon_process();
  1062. break;
  1063. }
  1064. if (isdigit(keypress))
  1065. number_process(keypress);
  1066. }
  1067. static void sig_catcher(int sig ATTRIBUTE_UNUSED)
  1068. {
  1069. set_tty_cooked();
  1070. exit(1);
  1071. }
  1072. int less_main(int argc, char **argv)
  1073. {
  1074. int keypress;
  1075. /* TODO: -x: do not interpret backspace, -xx: tab also */
  1076. /* -xxx: newline also */
  1077. /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
  1078. getopt32(argc, argv, "EMmN~");
  1079. argc -= optind;
  1080. argv += optind;
  1081. num_files = argc;
  1082. files = argv;
  1083. /* Another popular pager, most, detects when stdout
  1084. * is not a tty and turns into cat. This makes sense. */
  1085. if (!isatty(STDOUT_FILENO))
  1086. return bb_cat(argv);
  1087. if (!num_files) {
  1088. if (isatty(STDIN_FILENO)) {
  1089. /* Just "less"? No args and no redirection? */
  1090. bb_error_msg("missing filename");
  1091. bb_show_usage();
  1092. }
  1093. } else
  1094. filename = xstrdup(files[0]);
  1095. kbd_fd = xopen(CURRENT_TTY, O_RDONLY);
  1096. get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
  1097. /* 20: two tabstops + 4 */
  1098. if (width < 20 || max_displayed_line < 3)
  1099. bb_error_msg_and_die("too narrow here");
  1100. max_displayed_line -= 2;
  1101. buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
  1102. if (option_mask32 & FLAG_TILDE)
  1103. empty_line_marker = "";
  1104. tcgetattr(kbd_fd, &term_orig);
  1105. signal(SIGTERM, sig_catcher);
  1106. signal(SIGINT, sig_catcher);
  1107. term_vi = term_orig;
  1108. term_vi.c_lflag &= ~(ICANON | ECHO);
  1109. term_vi.c_iflag &= ~(IXON | ICRNL);
  1110. /*term_vi.c_oflag &= ~ONLCR;*/
  1111. term_vi.c_cc[VMIN] = 1;
  1112. term_vi.c_cc[VTIME] = 0;
  1113. /* Want to do it just once, but it doesn't work, */
  1114. /* so we are redoing it (see code above). Mystery... */
  1115. /*tcsetattr(kbd_fd, TCSANOW, &term_vi);*/
  1116. reinitialize();
  1117. while (1) {
  1118. keypress = less_getch();
  1119. keypress_process(keypress);
  1120. }
  1121. }