less.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  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 GPLv2 or later, see file LICENSE in this source tree.
  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. //config:config LESS
  23. //config: bool "less"
  24. //config: default y
  25. //config: help
  26. //config: 'less' is a pager, meaning that it displays text files. It possesses
  27. //config: a wide array of features, and is an improvement over 'more'.
  28. //config:
  29. //config:config FEATURE_LESS_MAXLINES
  30. //config: int "Max number of input lines less will try to eat"
  31. //config: default 9999999
  32. //config: depends on LESS
  33. //config:
  34. //config:config FEATURE_LESS_BRACKETS
  35. //config: bool "Enable bracket searching"
  36. //config: default y
  37. //config: depends on LESS
  38. //config: help
  39. //config: This option adds the capability to search for matching left and right
  40. //config: brackets, facilitating programming.
  41. //config:
  42. //config:config FEATURE_LESS_FLAGS
  43. //config: bool "Enable -m/-M"
  44. //config: default y
  45. //config: depends on LESS
  46. //config: help
  47. //config: The -M/-m flag enables a more sophisticated status line.
  48. //config:
  49. //config:config FEATURE_LESS_MARKS
  50. //config: bool "Enable marks"
  51. //config: default y
  52. //config: depends on LESS
  53. //config: help
  54. //config: Marks enable positions in a file to be stored for easy reference.
  55. //config:
  56. //config:config FEATURE_LESS_REGEXP
  57. //config: bool "Enable regular expressions"
  58. //config: default y
  59. //config: depends on LESS
  60. //config: help
  61. //config: Enable regular expressions, allowing complex file searches.
  62. //config:
  63. //config:config FEATURE_LESS_WINCH
  64. //config: bool "Enable automatic resizing on window size changes"
  65. //config: default y
  66. //config: depends on LESS
  67. //config: help
  68. //config: Makes less track window size changes.
  69. //config:
  70. //config:config FEATURE_LESS_ASK_TERMINAL
  71. //config: bool "Use 'tell me cursor position' ESC sequence to measure window"
  72. //config: default y
  73. //config: depends on FEATURE_LESS_WINCH
  74. //config: help
  75. //config: Makes less track window size changes.
  76. //config: If terminal size can't be retrieved and $LINES/$COLUMNS are not set,
  77. //config: this option makes less perform a last-ditch effort to find it:
  78. //config: position cursor to 999,999 and ask terminal to report real
  79. //config: cursor position using "ESC [ 6 n" escape sequence, then read stdin.
  80. //config:
  81. //config: This is not clean but helps a lot on serial lines and such.
  82. //config:
  83. //config:config FEATURE_LESS_DASHCMD
  84. //config: bool "Enable flag changes ('-' command)"
  85. //config: default y
  86. //config: depends on LESS
  87. //config: help
  88. //config: This enables the ability to change command-line flags within
  89. //config: less itself ('-' keyboard command).
  90. //config:
  91. //config:config FEATURE_LESS_LINENUMS
  92. //config: bool "Enable dynamic switching of line numbers"
  93. //config: default y
  94. //config: depends on FEATURE_LESS_DASHCMD
  95. //config: help
  96. //config: Enables "-N" command.
  97. //usage:#define less_trivial_usage
  98. //usage: "[-E" IF_FEATURE_LESS_FLAGS("Mm") "Nh~I?] [FILE]..."
  99. //usage:#define less_full_usage "\n\n"
  100. //usage: "View FILE (or stdin) one screenful at a time\n"
  101. //usage: "\n -E Quit once the end of a file is reached"
  102. //usage: IF_FEATURE_LESS_FLAGS(
  103. //usage: "\n -M,-m Display status line with line numbers"
  104. //usage: "\n and percentage through the file"
  105. //usage: )
  106. //usage: "\n -N Prefix line number to each line"
  107. //usage: "\n -I Ignore case in all searches"
  108. //usage: "\n -~ Suppress ~s displayed past EOF"
  109. #include <sched.h> /* sched_yield() */
  110. #include "libbb.h"
  111. #if ENABLE_FEATURE_LESS_REGEXP
  112. #include "xregex.h"
  113. #endif
  114. #define ESC "\033"
  115. /* The escape codes for highlighted and normal text */
  116. #define HIGHLIGHT ESC"[7m"
  117. #define NORMAL ESC"[0m"
  118. /* The escape code to home and clear to the end of screen */
  119. #define CLEAR ESC"[H\033[J"
  120. /* The escape code to clear to the end of line */
  121. #define CLEAR_2_EOL ESC"[K"
  122. enum {
  123. /* Absolute max of lines eaten */
  124. MAXLINES = CONFIG_FEATURE_LESS_MAXLINES,
  125. /* This many "after the end" lines we will show (at max) */
  126. TILDES = 1,
  127. };
  128. /* Command line options */
  129. enum {
  130. FLAG_E = 1 << 0,
  131. FLAG_M = 1 << 1,
  132. FLAG_m = 1 << 2,
  133. FLAG_N = 1 << 3,
  134. FLAG_TILDE = 1 << 4,
  135. FLAG_I = 1 << 5,
  136. FLAG_S = (1 << 6) * ENABLE_FEATURE_LESS_DASHCMD,
  137. /* hijack command line options variable for internal state vars */
  138. LESS_STATE_MATCH_BACKWARDS = 1 << 15,
  139. };
  140. #if !ENABLE_FEATURE_LESS_REGEXP
  141. enum { pattern_valid = 0 };
  142. #endif
  143. struct globals {
  144. int cur_fline; /* signed */
  145. int kbd_fd; /* fd to get input from */
  146. int less_gets_pos;
  147. /* last position in last line, taking into account tabs */
  148. size_t last_line_pos;
  149. unsigned max_fline;
  150. unsigned max_lineno; /* this one tracks linewrap */
  151. unsigned max_displayed_line;
  152. unsigned width;
  153. #if ENABLE_FEATURE_LESS_WINCH
  154. unsigned winch_counter;
  155. #endif
  156. ssize_t eof_error; /* eof if 0, error if < 0 */
  157. ssize_t readpos;
  158. ssize_t readeof; /* must be signed */
  159. const char **buffer;
  160. const char **flines;
  161. const char *empty_line_marker;
  162. unsigned num_files;
  163. unsigned current_file;
  164. char *filename;
  165. char **files;
  166. #if ENABLE_FEATURE_LESS_MARKS
  167. unsigned num_marks;
  168. unsigned mark_lines[15][2];
  169. #endif
  170. #if ENABLE_FEATURE_LESS_REGEXP
  171. unsigned *match_lines;
  172. int match_pos; /* signed! */
  173. int wanted_match; /* signed! */
  174. int num_matches;
  175. regex_t pattern;
  176. smallint pattern_valid;
  177. #endif
  178. #if ENABLE_FEATURE_LESS_ASK_TERMINAL
  179. smallint winsize_err;
  180. #endif
  181. smallint terminated;
  182. struct termios term_orig, term_less;
  183. char kbd_input[KEYCODE_BUFFER_SIZE];
  184. };
  185. #define G (*ptr_to_globals)
  186. #define cur_fline (G.cur_fline )
  187. #define kbd_fd (G.kbd_fd )
  188. #define less_gets_pos (G.less_gets_pos )
  189. #define last_line_pos (G.last_line_pos )
  190. #define max_fline (G.max_fline )
  191. #define max_lineno (G.max_lineno )
  192. #define max_displayed_line (G.max_displayed_line)
  193. #define width (G.width )
  194. #define winch_counter (G.winch_counter )
  195. /* This one is 100% not cached by compiler on read access */
  196. #define WINCH_COUNTER (*(volatile unsigned *)&winch_counter)
  197. #define eof_error (G.eof_error )
  198. #define readpos (G.readpos )
  199. #define readeof (G.readeof )
  200. #define buffer (G.buffer )
  201. #define flines (G.flines )
  202. #define empty_line_marker (G.empty_line_marker )
  203. #define num_files (G.num_files )
  204. #define current_file (G.current_file )
  205. #define filename (G.filename )
  206. #define files (G.files )
  207. #define num_marks (G.num_marks )
  208. #define mark_lines (G.mark_lines )
  209. #if ENABLE_FEATURE_LESS_REGEXP
  210. #define match_lines (G.match_lines )
  211. #define match_pos (G.match_pos )
  212. #define num_matches (G.num_matches )
  213. #define wanted_match (G.wanted_match )
  214. #define pattern (G.pattern )
  215. #define pattern_valid (G.pattern_valid )
  216. #endif
  217. #define terminated (G.terminated )
  218. #define term_orig (G.term_orig )
  219. #define term_less (G.term_less )
  220. #define kbd_input (G.kbd_input )
  221. #define INIT_G() do { \
  222. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  223. less_gets_pos = -1; \
  224. empty_line_marker = "~"; \
  225. num_files = 1; \
  226. current_file = 1; \
  227. eof_error = 1; \
  228. terminated = 1; \
  229. IF_FEATURE_LESS_REGEXP(wanted_match = -1;) \
  230. } while (0)
  231. /* flines[] are lines read from stdin, each in malloc'ed buffer.
  232. * Line numbers are stored as uint32_t prepended to each line.
  233. * Pointer is adjusted so that flines[i] points directly past
  234. * line number. Accesor: */
  235. #define MEMPTR(p) ((char*)(p) - 4)
  236. #define LINENO(p) (*(uint32_t*)((p) - 4))
  237. /* Reset terminal input to normal */
  238. static void set_tty_cooked(void)
  239. {
  240. fflush_all();
  241. tcsetattr(kbd_fd, TCSANOW, &term_orig);
  242. }
  243. /* Move the cursor to a position (x,y), where (0,0) is the
  244. top-left corner of the console */
  245. static void move_cursor(int line, int row)
  246. {
  247. printf(ESC"[%u;%uH", line, row);
  248. }
  249. static void clear_line(void)
  250. {
  251. printf(ESC"[%u;0H" CLEAR_2_EOL, max_displayed_line + 2);
  252. }
  253. static void print_hilite(const char *str)
  254. {
  255. printf(HIGHLIGHT"%s"NORMAL, str);
  256. }
  257. static void print_statusline(const char *str)
  258. {
  259. clear_line();
  260. printf(HIGHLIGHT"%.*s"NORMAL, width - 1, str);
  261. }
  262. /* Exit the program gracefully */
  263. static void less_exit(int code)
  264. {
  265. set_tty_cooked();
  266. clear_line();
  267. if (code < 0)
  268. kill_myself_with_sig(- code); /* does not return */
  269. exit(code);
  270. }
  271. #if (ENABLE_FEATURE_LESS_DASHCMD && ENABLE_FEATURE_LESS_LINENUMS) \
  272. || ENABLE_FEATURE_LESS_WINCH
  273. static void re_wrap(void)
  274. {
  275. int w = width;
  276. int new_line_pos;
  277. int src_idx;
  278. int dst_idx;
  279. int new_cur_fline = 0;
  280. uint32_t lineno;
  281. char linebuf[w + 1];
  282. const char **old_flines = flines;
  283. const char *s;
  284. char **new_flines = NULL;
  285. char *d;
  286. if (option_mask32 & FLAG_N)
  287. w -= 8;
  288. src_idx = 0;
  289. dst_idx = 0;
  290. s = old_flines[0];
  291. lineno = LINENO(s);
  292. d = linebuf;
  293. new_line_pos = 0;
  294. while (1) {
  295. *d = *s;
  296. if (*d != '\0') {
  297. new_line_pos++;
  298. if (*d == '\t') /* tab */
  299. new_line_pos += 7;
  300. s++;
  301. d++;
  302. if (new_line_pos >= w) {
  303. int sz;
  304. /* new line is full, create next one */
  305. *d = '\0';
  306. next_new:
  307. sz = (d - linebuf) + 1; /* + 1: NUL */
  308. d = ((char*)xmalloc(sz + 4)) + 4;
  309. LINENO(d) = lineno;
  310. memcpy(d, linebuf, sz);
  311. new_flines = xrealloc_vector(new_flines, 8, dst_idx);
  312. new_flines[dst_idx] = d;
  313. dst_idx++;
  314. if (new_line_pos < w) {
  315. /* if we came here thru "goto next_new" */
  316. if (src_idx > max_fline)
  317. break;
  318. lineno = LINENO(s);
  319. }
  320. d = linebuf;
  321. new_line_pos = 0;
  322. }
  323. continue;
  324. }
  325. /* *d == NUL: old line ended, go to next old one */
  326. free(MEMPTR(old_flines[src_idx]));
  327. /* btw, convert cur_fline... */
  328. if (cur_fline == src_idx)
  329. new_cur_fline = dst_idx;
  330. src_idx++;
  331. /* no more lines? finish last new line (and exit the loop) */
  332. if (src_idx > max_fline)
  333. goto next_new;
  334. s = old_flines[src_idx];
  335. if (lineno != LINENO(s)) {
  336. /* this is not a continuation line!
  337. * create next _new_ line too */
  338. goto next_new;
  339. }
  340. }
  341. free(old_flines);
  342. flines = (const char **)new_flines;
  343. max_fline = dst_idx - 1;
  344. last_line_pos = new_line_pos;
  345. cur_fline = new_cur_fline;
  346. /* max_lineno is screen-size independent */
  347. #if ENABLE_FEATURE_LESS_REGEXP
  348. pattern_valid = 0;
  349. #endif
  350. }
  351. #endif
  352. #if ENABLE_FEATURE_LESS_REGEXP
  353. static void fill_match_lines(unsigned pos);
  354. #else
  355. #define fill_match_lines(pos) ((void)0)
  356. #endif
  357. /* Devilishly complex routine.
  358. *
  359. * Has to deal with EOF and EPIPE on input,
  360. * with line wrapping, with last line not ending in '\n'
  361. * (possibly not ending YET!), with backspace and tabs.
  362. * It reads input again if last time we got an EOF (thus supporting
  363. * growing files) or EPIPE (watching output of slow process like make).
  364. *
  365. * Variables used:
  366. * flines[] - array of lines already read. Linewrap may cause
  367. * one source file line to occupy several flines[n].
  368. * flines[max_fline] - last line, possibly incomplete.
  369. * terminated - 1 if flines[max_fline] is 'terminated'
  370. * (if there was '\n' [which isn't stored itself, we just remember
  371. * that it was seen])
  372. * max_lineno - last line's number, this one doesn't increment
  373. * on line wrap, only on "real" new lines.
  374. * readbuf[0..readeof-1] - small preliminary buffer.
  375. * readbuf[readpos] - next character to add to current line.
  376. * last_line_pos - screen line position of next char to be read
  377. * (takes into account tabs and backspaces)
  378. * eof_error - < 0 error, == 0 EOF, > 0 not EOF/error
  379. */
  380. static void read_lines(void)
  381. {
  382. #define readbuf bb_common_bufsiz1
  383. char *current_line, *p;
  384. int w = width;
  385. char last_terminated = terminated;
  386. #if ENABLE_FEATURE_LESS_REGEXP
  387. unsigned old_max_fline = max_fline;
  388. time_t last_time = 0;
  389. unsigned seconds_p1 = 3; /* seconds_to_loop + 1 */
  390. #endif
  391. if (option_mask32 & FLAG_N)
  392. w -= 8;
  393. IF_FEATURE_LESS_REGEXP(again0:)
  394. p = current_line = ((char*)xmalloc(w + 4)) + 4;
  395. max_fline += last_terminated;
  396. if (!last_terminated) {
  397. const char *cp = flines[max_fline];
  398. strcpy(p, cp);
  399. p += strlen(current_line);
  400. free(MEMPTR(flines[max_fline]));
  401. /* last_line_pos is still valid from previous read_lines() */
  402. } else {
  403. last_line_pos = 0;
  404. }
  405. while (1) { /* read lines until we reach cur_fline or wanted_match */
  406. *p = '\0';
  407. terminated = 0;
  408. while (1) { /* read chars until we have a line */
  409. char c;
  410. /* if no unprocessed chars left, eat more */
  411. if (readpos >= readeof) {
  412. ndelay_on(0);
  413. eof_error = safe_read(STDIN_FILENO, readbuf, sizeof(readbuf));
  414. ndelay_off(0);
  415. readpos = 0;
  416. readeof = eof_error;
  417. if (eof_error <= 0)
  418. goto reached_eof;
  419. }
  420. c = readbuf[readpos];
  421. /* backspace? [needed for manpages] */
  422. /* <tab><bs> is (a) insane and */
  423. /* (b) harder to do correctly, so we refuse to do it */
  424. if (c == '\x8' && last_line_pos && p[-1] != '\t') {
  425. readpos++; /* eat it */
  426. last_line_pos--;
  427. /* was buggy (p could end up <= current_line)... */
  428. *--p = '\0';
  429. continue;
  430. }
  431. {
  432. size_t new_last_line_pos = last_line_pos + 1;
  433. if (c == '\t') {
  434. new_last_line_pos += 7;
  435. new_last_line_pos &= (~7);
  436. }
  437. if ((int)new_last_line_pos >= w)
  438. break;
  439. last_line_pos = new_last_line_pos;
  440. }
  441. /* ok, we will eat this char */
  442. readpos++;
  443. if (c == '\n') {
  444. terminated = 1;
  445. last_line_pos = 0;
  446. break;
  447. }
  448. /* NUL is substituted by '\n'! */
  449. if (c == '\0') c = '\n';
  450. *p++ = c;
  451. *p = '\0';
  452. } /* end of "read chars until we have a line" loop */
  453. /* Corner case: linewrap with only "" wrapping to next line */
  454. /* Looks ugly on screen, so we do not store this empty line */
  455. if (!last_terminated && !current_line[0]) {
  456. last_terminated = 1;
  457. max_lineno++;
  458. continue;
  459. }
  460. reached_eof:
  461. last_terminated = terminated;
  462. flines = xrealloc_vector(flines, 8, max_fline);
  463. flines[max_fline] = (char*)xrealloc(MEMPTR(current_line), strlen(current_line) + 1 + 4) + 4;
  464. LINENO(flines[max_fline]) = max_lineno;
  465. if (terminated)
  466. max_lineno++;
  467. if (max_fline >= MAXLINES) {
  468. eof_error = 0; /* Pretend we saw EOF */
  469. break;
  470. }
  471. if (!(option_mask32 & FLAG_S)
  472. ? (max_fline > cur_fline + max_displayed_line)
  473. : (max_fline >= cur_fline
  474. && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
  475. ) {
  476. #if !ENABLE_FEATURE_LESS_REGEXP
  477. break;
  478. #else
  479. if (wanted_match >= num_matches) { /* goto_match called us */
  480. fill_match_lines(old_max_fline);
  481. old_max_fline = max_fline;
  482. }
  483. if (wanted_match < num_matches)
  484. break;
  485. #endif
  486. }
  487. if (eof_error <= 0) {
  488. if (eof_error < 0) {
  489. if (errno == EAGAIN) {
  490. /* not yet eof or error, reset flag (or else
  491. * we will hog CPU - select() will return
  492. * immediately */
  493. eof_error = 1;
  494. } else {
  495. print_statusline(bb_msg_read_error);
  496. }
  497. }
  498. #if !ENABLE_FEATURE_LESS_REGEXP
  499. break;
  500. #else
  501. if (wanted_match < num_matches) {
  502. break;
  503. } else { /* goto_match called us */
  504. time_t t = time(NULL);
  505. if (t != last_time) {
  506. last_time = t;
  507. if (--seconds_p1 == 0)
  508. break;
  509. }
  510. sched_yield();
  511. goto again0; /* go loop again (max 2 seconds) */
  512. }
  513. #endif
  514. }
  515. max_fline++;
  516. current_line = ((char*)xmalloc(w + 4)) + 4;
  517. p = current_line;
  518. last_line_pos = 0;
  519. } /* end of "read lines until we reach cur_fline" loop */
  520. fill_match_lines(old_max_fline);
  521. #if ENABLE_FEATURE_LESS_REGEXP
  522. /* prevent us from being stuck in search for a match */
  523. wanted_match = -1;
  524. #endif
  525. #undef readbuf
  526. }
  527. #if ENABLE_FEATURE_LESS_FLAGS
  528. /* Interestingly, writing calc_percent as a function saves around 32 bytes
  529. * on my build. */
  530. static int calc_percent(void)
  531. {
  532. unsigned p = (100 * (cur_fline+max_displayed_line+1) + max_fline/2) / (max_fline+1);
  533. return p <= 100 ? p : 100;
  534. }
  535. /* Print a status line if -M was specified */
  536. static void m_status_print(void)
  537. {
  538. int percentage;
  539. if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
  540. return;
  541. clear_line();
  542. printf(HIGHLIGHT"%s", filename);
  543. if (num_files > 1)
  544. printf(" (file %i of %i)", current_file, num_files);
  545. printf(" lines %i-%i/%i ",
  546. cur_fline + 1, cur_fline + max_displayed_line + 1,
  547. max_fline + 1);
  548. if (cur_fline >= (int)(max_fline - max_displayed_line)) {
  549. printf("(END)"NORMAL);
  550. if (num_files > 1 && current_file != num_files)
  551. printf(HIGHLIGHT" - next: %s"NORMAL, files[current_file]);
  552. return;
  553. }
  554. percentage = calc_percent();
  555. printf("%i%%"NORMAL, percentage);
  556. }
  557. #endif
  558. /* Print the status line */
  559. static void status_print(void)
  560. {
  561. const char *p;
  562. if (less_gets_pos >= 0) /* don't touch statusline while input is done! */
  563. return;
  564. /* Change the status if flags have been set */
  565. #if ENABLE_FEATURE_LESS_FLAGS
  566. if (option_mask32 & (FLAG_M|FLAG_m)) {
  567. m_status_print();
  568. return;
  569. }
  570. /* No flags set */
  571. #endif
  572. clear_line();
  573. if (cur_fline && cur_fline < (int)(max_fline - max_displayed_line)) {
  574. bb_putchar(':');
  575. return;
  576. }
  577. p = "(END)";
  578. if (!cur_fline)
  579. p = filename;
  580. if (num_files > 1) {
  581. printf(HIGHLIGHT"%s (file %i of %i)"NORMAL,
  582. p, current_file, num_files);
  583. return;
  584. }
  585. print_hilite(p);
  586. }
  587. static void cap_cur_fline(int nlines)
  588. {
  589. int diff;
  590. if (cur_fline < 0)
  591. cur_fline = 0;
  592. if (cur_fline + max_displayed_line > max_fline + TILDES) {
  593. cur_fline -= nlines;
  594. if (cur_fline < 0)
  595. cur_fline = 0;
  596. diff = max_fline - (cur_fline + max_displayed_line) + TILDES;
  597. /* As the number of lines requested was too large, we just move
  598. * to the end of the file */
  599. if (diff > 0)
  600. cur_fline += diff;
  601. }
  602. }
  603. static const char controls[] ALIGN1 =
  604. /* NUL: never encountered; TAB: not converted */
  605. /**/"\x01\x02\x03\x04\x05\x06\x07\x08" "\x0a\x0b\x0c\x0d\x0e\x0f"
  606. "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
  607. "\x7f\x9b"; /* DEL and infamous Meta-ESC :( */
  608. static const char ctrlconv[] ALIGN1 =
  609. /* why 40 instead of 4a below? - it is a replacement for '\n'.
  610. * '\n' is a former NUL - we subst it with @, not J */
  611. "\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x4b\x4c\x4d\x4e\x4f"
  612. "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f";
  613. static void lineno_str(char *nbuf9, const char *line)
  614. {
  615. nbuf9[0] = '\0';
  616. if (option_mask32 & FLAG_N) {
  617. const char *fmt;
  618. unsigned n;
  619. if (line == empty_line_marker) {
  620. memset(nbuf9, ' ', 8);
  621. nbuf9[8] = '\0';
  622. return;
  623. }
  624. /* Width of 7 preserves tab spacing in the text */
  625. fmt = "%7u ";
  626. n = LINENO(line) + 1;
  627. if (n > 9999999) {
  628. n %= 10000000;
  629. fmt = "%07u ";
  630. }
  631. sprintf(nbuf9, fmt, n);
  632. }
  633. }
  634. #if ENABLE_FEATURE_LESS_REGEXP
  635. static void print_found(const char *line)
  636. {
  637. int match_status;
  638. int eflags;
  639. char *growline;
  640. regmatch_t match_structs;
  641. char buf[width];
  642. char nbuf9[9];
  643. const char *str = line;
  644. char *p = buf;
  645. size_t n;
  646. while (*str) {
  647. n = strcspn(str, controls);
  648. if (n) {
  649. if (!str[n]) break;
  650. memcpy(p, str, n);
  651. p += n;
  652. str += n;
  653. }
  654. n = strspn(str, controls);
  655. memset(p, '.', n);
  656. p += n;
  657. str += n;
  658. }
  659. strcpy(p, str);
  660. /* buf[] holds quarantined version of str */
  661. /* Each part of the line that matches has the HIGHLIGHT
  662. * and NORMAL escape sequences placed around it.
  663. * NB: we regex against line, but insert text
  664. * from quarantined copy (buf[]) */
  665. str = buf;
  666. growline = NULL;
  667. eflags = 0;
  668. goto start;
  669. while (match_status == 0) {
  670. char *new = xasprintf("%s%.*s"HIGHLIGHT"%.*s"NORMAL,
  671. growline ? growline : "",
  672. (int)match_structs.rm_so, str,
  673. (int)(match_structs.rm_eo - match_structs.rm_so),
  674. str + match_structs.rm_so);
  675. free(growline);
  676. growline = new;
  677. str += match_structs.rm_eo;
  678. line += match_structs.rm_eo;
  679. eflags = REG_NOTBOL;
  680. start:
  681. /* Most of the time doesn't find the regex, optimize for that */
  682. match_status = regexec(&pattern, line, 1, &match_structs, eflags);
  683. /* if even "" matches, treat it as "not a match" */
  684. if (match_structs.rm_so >= match_structs.rm_eo)
  685. match_status = 1;
  686. }
  687. lineno_str(nbuf9, line);
  688. if (!growline) {
  689. printf(CLEAR_2_EOL"%s%s\n", nbuf9, str);
  690. return;
  691. }
  692. printf(CLEAR_2_EOL"%s%s%s\n", nbuf9, growline, str);
  693. free(growline);
  694. }
  695. #else
  696. void print_found(const char *line);
  697. #endif
  698. static void print_ascii(const char *str)
  699. {
  700. char buf[width];
  701. char nbuf9[9];
  702. char *p;
  703. size_t n;
  704. lineno_str(nbuf9, str);
  705. printf(CLEAR_2_EOL"%s", nbuf9);
  706. while (*str) {
  707. n = strcspn(str, controls);
  708. if (n) {
  709. if (!str[n]) break;
  710. printf("%.*s", (int) n, str);
  711. str += n;
  712. }
  713. n = strspn(str, controls);
  714. p = buf;
  715. do {
  716. if (*str == 0x7f)
  717. *p++ = '?';
  718. else if (*str == (char)0x9b)
  719. /* VT100's CSI, aka Meta-ESC. Who's inventor? */
  720. /* I want to know who committed this sin */
  721. *p++ = '{';
  722. else
  723. *p++ = ctrlconv[(unsigned char)*str];
  724. str++;
  725. } while (--n);
  726. *p = '\0';
  727. print_hilite(buf);
  728. }
  729. puts(str);
  730. }
  731. /* Print the buffer */
  732. static void buffer_print(void)
  733. {
  734. unsigned i;
  735. move_cursor(0, 0);
  736. for (i = 0; i <= max_displayed_line; i++)
  737. if (pattern_valid)
  738. print_found(buffer[i]);
  739. else
  740. print_ascii(buffer[i]);
  741. status_print();
  742. }
  743. static void buffer_fill_and_print(void)
  744. {
  745. unsigned i;
  746. #if ENABLE_FEATURE_LESS_DASHCMD
  747. int fpos = cur_fline;
  748. if (option_mask32 & FLAG_S) {
  749. /* Go back to the beginning of this line */
  750. while (fpos && LINENO(flines[fpos]) == LINENO(flines[fpos-1]))
  751. fpos--;
  752. }
  753. i = 0;
  754. while (i <= max_displayed_line && fpos <= max_fline) {
  755. int lineno = LINENO(flines[fpos]);
  756. buffer[i] = flines[fpos];
  757. i++;
  758. do {
  759. fpos++;
  760. } while ((fpos <= max_fline)
  761. && (option_mask32 & FLAG_S)
  762. && lineno == LINENO(flines[fpos])
  763. );
  764. }
  765. #else
  766. for (i = 0; i <= max_displayed_line && cur_fline + i <= max_fline; i++) {
  767. buffer[i] = flines[cur_fline + i];
  768. }
  769. #endif
  770. for (; i <= max_displayed_line; i++) {
  771. buffer[i] = empty_line_marker;
  772. }
  773. buffer_print();
  774. }
  775. /* Move the buffer up and down in the file in order to scroll */
  776. static void buffer_down(int nlines)
  777. {
  778. cur_fline += nlines;
  779. read_lines();
  780. cap_cur_fline(nlines);
  781. buffer_fill_and_print();
  782. }
  783. static void buffer_up(int nlines)
  784. {
  785. cur_fline -= nlines;
  786. if (cur_fline < 0) cur_fline = 0;
  787. read_lines();
  788. buffer_fill_and_print();
  789. }
  790. static void buffer_line(int linenum)
  791. {
  792. if (linenum < 0)
  793. linenum = 0;
  794. cur_fline = linenum;
  795. read_lines();
  796. if (linenum + max_displayed_line > max_fline)
  797. linenum = max_fline - max_displayed_line + TILDES;
  798. if (linenum < 0)
  799. linenum = 0;
  800. cur_fline = linenum;
  801. buffer_fill_and_print();
  802. }
  803. static void open_file_and_read_lines(void)
  804. {
  805. if (filename) {
  806. xmove_fd(xopen(filename, O_RDONLY), STDIN_FILENO);
  807. } else {
  808. /* "less" with no arguments in argv[] */
  809. /* For status line only */
  810. filename = xstrdup(bb_msg_standard_input);
  811. }
  812. readpos = 0;
  813. readeof = 0;
  814. last_line_pos = 0;
  815. terminated = 1;
  816. read_lines();
  817. }
  818. /* Reinitialize everything for a new file - free the memory and start over */
  819. static void reinitialize(void)
  820. {
  821. unsigned i;
  822. if (flines) {
  823. for (i = 0; i <= max_fline; i++)
  824. free(MEMPTR(flines[i]));
  825. free(flines);
  826. flines = NULL;
  827. }
  828. max_fline = -1;
  829. cur_fline = 0;
  830. max_lineno = 0;
  831. open_file_and_read_lines();
  832. #if ENABLE_FEATURE_LESS_ASK_TERMINAL
  833. if (G.winsize_err)
  834. printf("\033[999;999H" "\033[6n");
  835. #endif
  836. buffer_fill_and_print();
  837. }
  838. static int64_t getch_nowait(void)
  839. {
  840. int rd;
  841. int64_t key64;
  842. struct pollfd pfd[2];
  843. pfd[0].fd = STDIN_FILENO;
  844. pfd[0].events = POLLIN;
  845. pfd[1].fd = kbd_fd;
  846. pfd[1].events = POLLIN;
  847. again:
  848. tcsetattr(kbd_fd, TCSANOW, &term_less);
  849. /* NB: select/poll returns whenever read will not block. Therefore:
  850. * if eof is reached, select/poll will return immediately
  851. * because read will immediately return 0 bytes.
  852. * Even if select/poll says that input is available, read CAN block
  853. * (switch fd into O_NONBLOCK'ed mode to avoid it)
  854. */
  855. rd = 1;
  856. /* Are we interested in stdin? */
  857. //TODO: reuse code for determining this
  858. if (!(option_mask32 & FLAG_S)
  859. ? !(max_fline > cur_fline + max_displayed_line)
  860. : !(max_fline >= cur_fline
  861. && max_lineno > LINENO(flines[cur_fline]) + max_displayed_line)
  862. ) {
  863. if (eof_error > 0) /* did NOT reach eof yet */
  864. rd = 0; /* yes, we are interested in stdin */
  865. }
  866. /* Position cursor if line input is done */
  867. if (less_gets_pos >= 0)
  868. move_cursor(max_displayed_line + 2, less_gets_pos + 1);
  869. fflush_all();
  870. if (kbd_input[0] == 0) { /* if nothing is buffered */
  871. #if ENABLE_FEATURE_LESS_WINCH
  872. while (1) {
  873. int r;
  874. /* NB: SIGWINCH interrupts poll() */
  875. r = poll(pfd + rd, 2 - rd, -1);
  876. if (/*r < 0 && errno == EINTR &&*/ winch_counter)
  877. return '\\'; /* anything which has no defined function */
  878. if (r) break;
  879. }
  880. #else
  881. safe_poll(pfd + rd, 2 - rd, -1);
  882. #endif
  883. }
  884. /* We have kbd_fd in O_NONBLOCK mode, read inside read_key()
  885. * would not block even if there is no input available */
  886. key64 = read_key(kbd_fd, kbd_input, /*timeout off:*/ -2);
  887. if ((int)key64 == -1) {
  888. if (errno == EAGAIN) {
  889. /* No keyboard input available. Since poll() did return,
  890. * we should have input on stdin */
  891. read_lines();
  892. buffer_fill_and_print();
  893. goto again;
  894. }
  895. /* EOF/error (ssh session got killed etc) */
  896. less_exit(0);
  897. }
  898. set_tty_cooked();
  899. return key64;
  900. }
  901. /* Grab a character from input without requiring the return key.
  902. * May return KEYCODE_xxx values.
  903. * Note that this function works best with raw input. */
  904. static int64_t less_getch(int pos)
  905. {
  906. int64_t key64;
  907. int key;
  908. again:
  909. less_gets_pos = pos;
  910. key = key64 = getch_nowait();
  911. less_gets_pos = -1;
  912. /* Discard Ctrl-something chars.
  913. * (checking only lower 32 bits is a size optimization:
  914. * upper 32 bits are used only by KEYCODE_CURSOR_POS)
  915. */
  916. if (key >= 0 && key < ' ' && key != 0x0d && key != 8)
  917. goto again;
  918. return key64;
  919. }
  920. static char* less_gets(int sz)
  921. {
  922. int c;
  923. unsigned i = 0;
  924. char *result = xzalloc(1);
  925. while (1) {
  926. c = '\0';
  927. less_gets_pos = sz + i;
  928. c = getch_nowait();
  929. if (c == 0x0d) {
  930. result[i] = '\0';
  931. less_gets_pos = -1;
  932. return result;
  933. }
  934. if (c == 0x7f)
  935. c = 8;
  936. if (c == 8 && i) {
  937. printf("\x8 \x8");
  938. i--;
  939. }
  940. if (c < ' ') /* filters out KEYCODE_xxx too (<0) */
  941. continue;
  942. if (i >= width - sz - 1)
  943. continue; /* len limit */
  944. bb_putchar(c);
  945. result[i++] = c;
  946. result = xrealloc(result, i+1);
  947. }
  948. }
  949. static void examine_file(void)
  950. {
  951. char *new_fname;
  952. print_statusline("Examine: ");
  953. new_fname = less_gets(sizeof("Examine: ") - 1);
  954. if (!new_fname[0]) {
  955. status_print();
  956. err:
  957. free(new_fname);
  958. return;
  959. }
  960. if (access(new_fname, R_OK) != 0) {
  961. print_statusline("Cannot read this file");
  962. goto err;
  963. }
  964. free(filename);
  965. filename = new_fname;
  966. /* files start by = argv. why we assume that argv is infinitely long??
  967. files[num_files] = filename;
  968. current_file = num_files + 1;
  969. num_files++; */
  970. files[0] = filename;
  971. num_files = current_file = 1;
  972. reinitialize();
  973. }
  974. /* This function changes the file currently being paged. direction can be one of the following:
  975. * -1: go back one file
  976. * 0: go to the first file
  977. * 1: go forward one file */
  978. static void change_file(int direction)
  979. {
  980. if (current_file != ((direction > 0) ? num_files : 1)) {
  981. current_file = direction ? current_file + direction : 1;
  982. free(filename);
  983. filename = xstrdup(files[current_file - 1]);
  984. reinitialize();
  985. } else {
  986. print_statusline(direction > 0 ? "No next file" : "No previous file");
  987. }
  988. }
  989. static void remove_current_file(void)
  990. {
  991. unsigned i;
  992. if (num_files < 2)
  993. return;
  994. if (current_file != 1) {
  995. change_file(-1);
  996. for (i = 3; i <= num_files; i++)
  997. files[i - 2] = files[i - 1];
  998. num_files--;
  999. } else {
  1000. change_file(1);
  1001. for (i = 2; i <= num_files; i++)
  1002. files[i - 2] = files[i - 1];
  1003. num_files--;
  1004. current_file--;
  1005. }
  1006. }
  1007. static void colon_process(void)
  1008. {
  1009. int keypress;
  1010. /* Clear the current line and print a prompt */
  1011. print_statusline(" :");
  1012. keypress = less_getch(2);
  1013. switch (keypress) {
  1014. case 'd':
  1015. remove_current_file();
  1016. break;
  1017. case 'e':
  1018. examine_file();
  1019. break;
  1020. #if ENABLE_FEATURE_LESS_FLAGS
  1021. case 'f':
  1022. m_status_print();
  1023. break;
  1024. #endif
  1025. case 'n':
  1026. change_file(1);
  1027. break;
  1028. case 'p':
  1029. change_file(-1);
  1030. break;
  1031. case 'q':
  1032. less_exit(EXIT_SUCCESS);
  1033. break;
  1034. case 'x':
  1035. change_file(0);
  1036. break;
  1037. }
  1038. }
  1039. #if ENABLE_FEATURE_LESS_REGEXP
  1040. static void normalize_match_pos(int match)
  1041. {
  1042. if (match >= num_matches)
  1043. match = num_matches - 1;
  1044. if (match < 0)
  1045. match = 0;
  1046. match_pos = match;
  1047. }
  1048. static void goto_match(int match)
  1049. {
  1050. if (!pattern_valid)
  1051. return;
  1052. if (match < 0)
  1053. match = 0;
  1054. /* Try to find next match if eof isn't reached yet */
  1055. if (match >= num_matches && eof_error > 0) {
  1056. wanted_match = match; /* "I want to read until I see N'th match" */
  1057. read_lines();
  1058. }
  1059. if (num_matches) {
  1060. normalize_match_pos(match);
  1061. buffer_line(match_lines[match_pos]);
  1062. } else {
  1063. print_statusline("No matches found");
  1064. }
  1065. }
  1066. static void fill_match_lines(unsigned pos)
  1067. {
  1068. if (!pattern_valid)
  1069. return;
  1070. /* Run the regex on each line of the current file */
  1071. while (pos <= max_fline) {
  1072. /* If this line matches */
  1073. if (regexec(&pattern, flines[pos], 0, NULL, 0) == 0
  1074. /* and we didn't match it last time */
  1075. && !(num_matches && match_lines[num_matches-1] == pos)
  1076. ) {
  1077. match_lines = xrealloc_vector(match_lines, 4, num_matches);
  1078. match_lines[num_matches++] = pos;
  1079. }
  1080. pos++;
  1081. }
  1082. }
  1083. static void regex_process(void)
  1084. {
  1085. char *uncomp_regex, *err;
  1086. /* Reset variables */
  1087. free(match_lines);
  1088. match_lines = NULL;
  1089. match_pos = 0;
  1090. num_matches = 0;
  1091. if (pattern_valid) {
  1092. regfree(&pattern);
  1093. pattern_valid = 0;
  1094. }
  1095. /* Get the uncompiled regular expression from the user */
  1096. clear_line();
  1097. bb_putchar((option_mask32 & LESS_STATE_MATCH_BACKWARDS) ? '?' : '/');
  1098. uncomp_regex = less_gets(1);
  1099. if (!uncomp_regex[0]) {
  1100. free(uncomp_regex);
  1101. buffer_print();
  1102. return;
  1103. }
  1104. /* Compile the regex and check for errors */
  1105. err = regcomp_or_errmsg(&pattern, uncomp_regex,
  1106. (option_mask32 & FLAG_I) ? REG_ICASE : 0);
  1107. free(uncomp_regex);
  1108. if (err) {
  1109. print_statusline(err);
  1110. free(err);
  1111. return;
  1112. }
  1113. pattern_valid = 1;
  1114. match_pos = 0;
  1115. fill_match_lines(0);
  1116. while (match_pos < num_matches) {
  1117. if ((int)match_lines[match_pos] > cur_fline)
  1118. break;
  1119. match_pos++;
  1120. }
  1121. if (option_mask32 & LESS_STATE_MATCH_BACKWARDS)
  1122. match_pos--;
  1123. /* It's possible that no matches are found yet.
  1124. * goto_match() will read input looking for match,
  1125. * if needed */
  1126. goto_match(match_pos);
  1127. }
  1128. #endif
  1129. static void number_process(int first_digit)
  1130. {
  1131. unsigned i;
  1132. int num;
  1133. int keypress;
  1134. char num_input[sizeof(int)*4]; /* more than enough */
  1135. num_input[0] = first_digit;
  1136. /* Clear the current line, print a prompt, and then print the digit */
  1137. clear_line();
  1138. printf(":%c", first_digit);
  1139. /* Receive input until a letter is given */
  1140. i = 1;
  1141. while (i < sizeof(num_input)-1) {
  1142. keypress = less_getch(i + 1);
  1143. if ((unsigned)keypress > 255 || !isdigit(num_input[i]))
  1144. break;
  1145. num_input[i] = keypress;
  1146. bb_putchar(keypress);
  1147. i++;
  1148. }
  1149. num_input[i] = '\0';
  1150. num = bb_strtou(num_input, NULL, 10);
  1151. /* on format error, num == -1 */
  1152. if (num < 1 || num > MAXLINES) {
  1153. buffer_print();
  1154. return;
  1155. }
  1156. /* We now know the number and the letter entered, so we process them */
  1157. switch (keypress) {
  1158. case KEYCODE_DOWN: case 'z': case 'd': case 'e': case ' ': case '\015':
  1159. buffer_down(num);
  1160. break;
  1161. case KEYCODE_UP: case 'b': case 'w': case 'y': case 'u':
  1162. buffer_up(num);
  1163. break;
  1164. case 'g': case '<': case 'G': case '>':
  1165. cur_fline = num + max_displayed_line;
  1166. read_lines();
  1167. buffer_line(num - 1);
  1168. break;
  1169. case 'p': case '%':
  1170. num = num * (max_fline / 100); /* + max_fline / 2; */
  1171. cur_fline = num + max_displayed_line;
  1172. read_lines();
  1173. buffer_line(num);
  1174. break;
  1175. #if ENABLE_FEATURE_LESS_REGEXP
  1176. case 'n':
  1177. goto_match(match_pos + num);
  1178. break;
  1179. case '/':
  1180. option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
  1181. regex_process();
  1182. break;
  1183. case '?':
  1184. option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
  1185. regex_process();
  1186. break;
  1187. #endif
  1188. }
  1189. }
  1190. #if ENABLE_FEATURE_LESS_DASHCMD
  1191. static void flag_change(void)
  1192. {
  1193. int keypress;
  1194. clear_line();
  1195. bb_putchar('-');
  1196. keypress = less_getch(1);
  1197. switch (keypress) {
  1198. case 'M':
  1199. option_mask32 ^= FLAG_M;
  1200. break;
  1201. case 'm':
  1202. option_mask32 ^= FLAG_m;
  1203. break;
  1204. case 'E':
  1205. option_mask32 ^= FLAG_E;
  1206. break;
  1207. case '~':
  1208. option_mask32 ^= FLAG_TILDE;
  1209. break;
  1210. case 'S':
  1211. option_mask32 ^= FLAG_S;
  1212. buffer_fill_and_print();
  1213. break;
  1214. #if ENABLE_FEATURE_LESS_LINENUMS
  1215. case 'N':
  1216. option_mask32 ^= FLAG_N;
  1217. re_wrap();
  1218. buffer_fill_and_print();
  1219. break;
  1220. #endif
  1221. }
  1222. }
  1223. #ifdef BLOAT
  1224. static void show_flag_status(void)
  1225. {
  1226. int keypress;
  1227. int flag_val;
  1228. clear_line();
  1229. bb_putchar('_');
  1230. keypress = less_getch(1);
  1231. switch (keypress) {
  1232. case 'M':
  1233. flag_val = option_mask32 & FLAG_M;
  1234. break;
  1235. case 'm':
  1236. flag_val = option_mask32 & FLAG_m;
  1237. break;
  1238. case '~':
  1239. flag_val = option_mask32 & FLAG_TILDE;
  1240. break;
  1241. case 'N':
  1242. flag_val = option_mask32 & FLAG_N;
  1243. break;
  1244. case 'E':
  1245. flag_val = option_mask32 & FLAG_E;
  1246. break;
  1247. default:
  1248. flag_val = 0;
  1249. break;
  1250. }
  1251. clear_line();
  1252. printf(HIGHLIGHT"The status of the flag is: %u"NORMAL, flag_val != 0);
  1253. }
  1254. #endif
  1255. #endif /* ENABLE_FEATURE_LESS_DASHCMD */
  1256. static void save_input_to_file(void)
  1257. {
  1258. const char *msg = "";
  1259. char *current_line;
  1260. unsigned i;
  1261. FILE *fp;
  1262. print_statusline("Log file: ");
  1263. current_line = less_gets(sizeof("Log file: ")-1);
  1264. if (current_line[0]) {
  1265. fp = fopen_for_write(current_line);
  1266. if (!fp) {
  1267. msg = "Error opening log file";
  1268. goto ret;
  1269. }
  1270. for (i = 0; i <= max_fline; i++)
  1271. fprintf(fp, "%s\n", flines[i]);
  1272. fclose(fp);
  1273. msg = "Done";
  1274. }
  1275. ret:
  1276. print_statusline(msg);
  1277. free(current_line);
  1278. }
  1279. #if ENABLE_FEATURE_LESS_MARKS
  1280. static void add_mark(void)
  1281. {
  1282. int letter;
  1283. print_statusline("Mark: ");
  1284. letter = less_getch(sizeof("Mark: ") - 1);
  1285. if (isalpha(letter)) {
  1286. /* If we exceed 15 marks, start overwriting previous ones */
  1287. if (num_marks == 14)
  1288. num_marks = 0;
  1289. mark_lines[num_marks][0] = letter;
  1290. mark_lines[num_marks][1] = cur_fline;
  1291. num_marks++;
  1292. } else {
  1293. print_statusline("Invalid mark letter");
  1294. }
  1295. }
  1296. static void goto_mark(void)
  1297. {
  1298. int letter;
  1299. int i;
  1300. print_statusline("Go to mark: ");
  1301. letter = less_getch(sizeof("Go to mark: ") - 1);
  1302. clear_line();
  1303. if (isalpha(letter)) {
  1304. for (i = 0; i <= num_marks; i++)
  1305. if (letter == mark_lines[i][0]) {
  1306. buffer_line(mark_lines[i][1]);
  1307. break;
  1308. }
  1309. if (num_marks == 14 && letter != mark_lines[14][0])
  1310. print_statusline("Mark not set");
  1311. } else
  1312. print_statusline("Invalid mark letter");
  1313. }
  1314. #endif
  1315. #if ENABLE_FEATURE_LESS_BRACKETS
  1316. static char opp_bracket(char bracket)
  1317. {
  1318. switch (bracket) {
  1319. case '{': case '[': /* '}' == '{' + 2. Same for '[' */
  1320. bracket++;
  1321. case '(': /* ')' == '(' + 1 */
  1322. bracket++;
  1323. break;
  1324. case '}': case ']':
  1325. bracket--;
  1326. case ')':
  1327. bracket--;
  1328. break;
  1329. };
  1330. return bracket;
  1331. }
  1332. static void match_right_bracket(char bracket)
  1333. {
  1334. unsigned i;
  1335. if (strchr(flines[cur_fline], bracket) == NULL) {
  1336. print_statusline("No bracket in top line");
  1337. return;
  1338. }
  1339. bracket = opp_bracket(bracket);
  1340. for (i = cur_fline + 1; i < max_fline; i++) {
  1341. if (strchr(flines[i], bracket) != NULL) {
  1342. buffer_line(i);
  1343. return;
  1344. }
  1345. }
  1346. print_statusline("No matching bracket found");
  1347. }
  1348. static void match_left_bracket(char bracket)
  1349. {
  1350. int i;
  1351. if (strchr(flines[cur_fline + max_displayed_line], bracket) == NULL) {
  1352. print_statusline("No bracket in bottom line");
  1353. return;
  1354. }
  1355. bracket = opp_bracket(bracket);
  1356. for (i = cur_fline + max_displayed_line; i >= 0; i--) {
  1357. if (strchr(flines[i], bracket) != NULL) {
  1358. buffer_line(i);
  1359. return;
  1360. }
  1361. }
  1362. print_statusline("No matching bracket found");
  1363. }
  1364. #endif /* FEATURE_LESS_BRACKETS */
  1365. static void keypress_process(int keypress)
  1366. {
  1367. switch (keypress) {
  1368. case KEYCODE_DOWN: case 'e': case 'j': case 0x0d:
  1369. buffer_down(1);
  1370. break;
  1371. case KEYCODE_UP: case 'y': case 'k':
  1372. buffer_up(1);
  1373. break;
  1374. case KEYCODE_PAGEDOWN: case ' ': case 'z': case 'f':
  1375. buffer_down(max_displayed_line + 1);
  1376. break;
  1377. case KEYCODE_PAGEUP: case 'w': case 'b':
  1378. buffer_up(max_displayed_line + 1);
  1379. break;
  1380. case 'd':
  1381. buffer_down((max_displayed_line + 1) / 2);
  1382. break;
  1383. case 'u':
  1384. buffer_up((max_displayed_line + 1) / 2);
  1385. break;
  1386. case KEYCODE_HOME: case 'g': case 'p': case '<': case '%':
  1387. buffer_line(0);
  1388. break;
  1389. case KEYCODE_END: case 'G': case '>':
  1390. cur_fline = MAXLINES;
  1391. read_lines();
  1392. buffer_line(cur_fline);
  1393. break;
  1394. case 'q': case 'Q':
  1395. less_exit(EXIT_SUCCESS);
  1396. break;
  1397. #if ENABLE_FEATURE_LESS_MARKS
  1398. case 'm':
  1399. add_mark();
  1400. buffer_print();
  1401. break;
  1402. case '\'':
  1403. goto_mark();
  1404. buffer_print();
  1405. break;
  1406. #endif
  1407. case 'r': case 'R':
  1408. /* TODO: (1) also bind ^R, ^L to this?
  1409. * (2) re-measure window size?
  1410. */
  1411. buffer_print();
  1412. break;
  1413. /*case 'R':
  1414. full_repaint();
  1415. break;*/
  1416. case 's':
  1417. save_input_to_file();
  1418. break;
  1419. case 'E':
  1420. examine_file();
  1421. break;
  1422. #if ENABLE_FEATURE_LESS_FLAGS
  1423. case '=':
  1424. m_status_print();
  1425. break;
  1426. #endif
  1427. #if ENABLE_FEATURE_LESS_REGEXP
  1428. case '/':
  1429. option_mask32 &= ~LESS_STATE_MATCH_BACKWARDS;
  1430. regex_process();
  1431. break;
  1432. case 'n':
  1433. goto_match(match_pos + 1);
  1434. break;
  1435. case 'N':
  1436. goto_match(match_pos - 1);
  1437. break;
  1438. case '?':
  1439. option_mask32 |= LESS_STATE_MATCH_BACKWARDS;
  1440. regex_process();
  1441. break;
  1442. #endif
  1443. #if ENABLE_FEATURE_LESS_DASHCMD
  1444. case '-':
  1445. flag_change();
  1446. buffer_print();
  1447. break;
  1448. #ifdef BLOAT
  1449. case '_':
  1450. show_flag_status();
  1451. break;
  1452. #endif
  1453. #endif
  1454. #if ENABLE_FEATURE_LESS_BRACKETS
  1455. case '{': case '(': case '[':
  1456. match_right_bracket(keypress);
  1457. break;
  1458. case '}': case ')': case ']':
  1459. match_left_bracket(keypress);
  1460. break;
  1461. #endif
  1462. case ':':
  1463. colon_process();
  1464. break;
  1465. }
  1466. if (isdigit(keypress))
  1467. number_process(keypress);
  1468. }
  1469. static void sig_catcher(int sig)
  1470. {
  1471. less_exit(- sig);
  1472. }
  1473. #if ENABLE_FEATURE_LESS_WINCH
  1474. static void sigwinch_handler(int sig UNUSED_PARAM)
  1475. {
  1476. winch_counter++;
  1477. }
  1478. #endif
  1479. int less_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1480. int less_main(int argc, char **argv)
  1481. {
  1482. INIT_G();
  1483. /* TODO: -x: do not interpret backspace, -xx: tab also */
  1484. /* -xxx: newline also */
  1485. /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */
  1486. getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S"));
  1487. argc -= optind;
  1488. argv += optind;
  1489. num_files = argc;
  1490. files = argv;
  1491. /* Another popular pager, most, detects when stdout
  1492. * is not a tty and turns into cat. This makes sense. */
  1493. if (!isatty(STDOUT_FILENO))
  1494. return bb_cat(argv);
  1495. if (!num_files) {
  1496. if (isatty(STDIN_FILENO)) {
  1497. /* Just "less"? No args and no redirection? */
  1498. bb_error_msg("missing filename");
  1499. bb_show_usage();
  1500. }
  1501. } else {
  1502. filename = xstrdup(files[0]);
  1503. }
  1504. if (option_mask32 & FLAG_TILDE)
  1505. empty_line_marker = "";
  1506. kbd_fd = open(CURRENT_TTY, O_RDONLY);
  1507. if (kbd_fd < 0)
  1508. return bb_cat(argv);
  1509. ndelay_on(kbd_fd);
  1510. tcgetattr(kbd_fd, &term_orig);
  1511. term_less = term_orig;
  1512. term_less.c_lflag &= ~(ICANON | ECHO);
  1513. term_less.c_iflag &= ~(IXON | ICRNL);
  1514. /*term_less.c_oflag &= ~ONLCR;*/
  1515. term_less.c_cc[VMIN] = 1;
  1516. term_less.c_cc[VTIME] = 0;
  1517. IF_FEATURE_LESS_ASK_TERMINAL(G.winsize_err =) get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
  1518. /* 20: two tabstops + 4 */
  1519. if (width < 20 || max_displayed_line < 3)
  1520. return bb_cat(argv);
  1521. max_displayed_line -= 2;
  1522. /* We want to restore term_orig on exit */
  1523. bb_signals(BB_FATAL_SIGS, sig_catcher);
  1524. #if ENABLE_FEATURE_LESS_WINCH
  1525. signal(SIGWINCH, sigwinch_handler);
  1526. #endif
  1527. buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
  1528. reinitialize();
  1529. while (1) {
  1530. int64_t keypress;
  1531. #if ENABLE_FEATURE_LESS_WINCH
  1532. while (WINCH_COUNTER) {
  1533. again:
  1534. winch_counter--;
  1535. IF_FEATURE_LESS_ASK_TERMINAL(G.winsize_err =) get_terminal_width_height(kbd_fd, &width, &max_displayed_line);
  1536. IF_FEATURE_LESS_ASK_TERMINAL(got_size:)
  1537. /* 20: two tabstops + 4 */
  1538. if (width < 20)
  1539. width = 20;
  1540. if (max_displayed_line < 3)
  1541. max_displayed_line = 3;
  1542. max_displayed_line -= 2;
  1543. free(buffer);
  1544. buffer = xmalloc((max_displayed_line+1) * sizeof(char *));
  1545. /* Avoid re-wrap and/or redraw if we already know
  1546. * we need to do it again. These ops are expensive */
  1547. if (WINCH_COUNTER)
  1548. goto again;
  1549. re_wrap();
  1550. if (WINCH_COUNTER)
  1551. goto again;
  1552. buffer_fill_and_print();
  1553. /* This took some time. Loop back and check,
  1554. * were there another SIGWINCH? */
  1555. }
  1556. keypress = less_getch(-1); /* -1: do not position cursor */
  1557. # if ENABLE_FEATURE_LESS_ASK_TERMINAL
  1558. if ((int32_t)keypress == KEYCODE_CURSOR_POS) {
  1559. uint32_t rc = (keypress >> 32);
  1560. width = (rc & 0x7fff);
  1561. max_displayed_line = ((rc >> 16) & 0x7fff);
  1562. goto got_size;
  1563. }
  1564. # endif
  1565. #else
  1566. keypress = less_getch(-1); /* -1: do not position cursor */
  1567. #endif
  1568. keypress_process(keypress);
  1569. }
  1570. }
  1571. /*
  1572. Help text of less version 418 is below.
  1573. If you are implementing something, keeping
  1574. key and/or command line switch compatibility is a good idea:
  1575. SUMMARY OF LESS COMMANDS
  1576. Commands marked with * may be preceded by a number, N.
  1577. Notes in parentheses indicate the behavior if N is given.
  1578. h H Display this help.
  1579. q :q Q :Q ZZ Exit.
  1580. ---------------------------------------------------------------------------
  1581. MOVING
  1582. e ^E j ^N CR * Forward one line (or N lines).
  1583. y ^Y k ^K ^P * Backward one line (or N lines).
  1584. f ^F ^V SPACE * Forward one window (or N lines).
  1585. b ^B ESC-v * Backward one window (or N lines).
  1586. z * Forward one window (and set window to N).
  1587. w * Backward one window (and set window to N).
  1588. ESC-SPACE * Forward one window, but don't stop at end-of-file.
  1589. d ^D * Forward one half-window (and set half-window to N).
  1590. u ^U * Backward one half-window (and set half-window to N).
  1591. ESC-) RightArrow * Left one half screen width (or N positions).
  1592. ESC-( LeftArrow * Right one half screen width (or N positions).
  1593. F Forward forever; like "tail -f".
  1594. r ^R ^L Repaint screen.
  1595. R Repaint screen, discarding buffered input.
  1596. ---------------------------------------------------
  1597. Default "window" is the screen height.
  1598. Default "half-window" is half of the screen height.
  1599. ---------------------------------------------------------------------------
  1600. SEARCHING
  1601. /pattern * Search forward for (N-th) matching line.
  1602. ?pattern * Search backward for (N-th) matching line.
  1603. n * Repeat previous search (for N-th occurrence).
  1604. N * Repeat previous search in reverse direction.
  1605. ESC-n * Repeat previous search, spanning files.
  1606. ESC-N * Repeat previous search, reverse dir. & spanning files.
  1607. ESC-u Undo (toggle) search highlighting.
  1608. ---------------------------------------------------
  1609. Search patterns may be modified by one or more of:
  1610. ^N or ! Search for NON-matching lines.
  1611. ^E or * Search multiple files (pass thru END OF FILE).
  1612. ^F or @ Start search at FIRST file (for /) or last file (for ?).
  1613. ^K Highlight matches, but don't move (KEEP position).
  1614. ^R Don't use REGULAR EXPRESSIONS.
  1615. ---------------------------------------------------------------------------
  1616. JUMPING
  1617. g < ESC-< * Go to first line in file (or line N).
  1618. G > ESC-> * Go to last line in file (or line N).
  1619. p % * Go to beginning of file (or N percent into file).
  1620. t * Go to the (N-th) next tag.
  1621. T * Go to the (N-th) previous tag.
  1622. { ( [ * Find close bracket } ) ].
  1623. } ) ] * Find open bracket { ( [.
  1624. ESC-^F <c1> <c2> * Find close bracket <c2>.
  1625. ESC-^B <c1> <c2> * Find open bracket <c1>
  1626. ---------------------------------------------------
  1627. Each "find close bracket" command goes forward to the close bracket
  1628. matching the (N-th) open bracket in the top line.
  1629. Each "find open bracket" command goes backward to the open bracket
  1630. matching the (N-th) close bracket in the bottom line.
  1631. m<letter> Mark the current position with <letter>.
  1632. '<letter> Go to a previously marked position.
  1633. '' Go to the previous position.
  1634. ^X^X Same as '.
  1635. ---------------------------------------------------
  1636. A mark is any upper-case or lower-case letter.
  1637. Certain marks are predefined:
  1638. ^ means beginning of the file
  1639. $ means end of the file
  1640. ---------------------------------------------------------------------------
  1641. CHANGING FILES
  1642. :e [file] Examine a new file.
  1643. ^X^V Same as :e.
  1644. :n * Examine the (N-th) next file from the command line.
  1645. :p * Examine the (N-th) previous file from the command line.
  1646. :x * Examine the first (or N-th) file from the command line.
  1647. :d Delete the current file from the command line list.
  1648. = ^G :f Print current file name.
  1649. ---------------------------------------------------------------------------
  1650. MISCELLANEOUS COMMANDS
  1651. -<flag> Toggle a command line option [see OPTIONS below].
  1652. --<name> Toggle a command line option, by name.
  1653. _<flag> Display the setting of a command line option.
  1654. __<name> Display the setting of an option, by name.
  1655. +cmd Execute the less cmd each time a new file is examined.
  1656. !command Execute the shell command with $SHELL.
  1657. |Xcommand Pipe file between current pos & mark X to shell command.
  1658. v Edit the current file with $VISUAL or $EDITOR.
  1659. V Print version number of "less".
  1660. ---------------------------------------------------------------------------
  1661. OPTIONS
  1662. Most options may be changed either on the command line,
  1663. or from within less by using the - or -- command.
  1664. Options may be given in one of two forms: either a single
  1665. character preceded by a -, or a name preceeded by --.
  1666. -? ........ --help
  1667. Display help (from command line).
  1668. -a ........ --search-skip-screen
  1669. Forward search skips current screen.
  1670. -b [N] .... --buffers=[N]
  1671. Number of buffers.
  1672. -B ........ --auto-buffers
  1673. Don't automatically allocate buffers for pipes.
  1674. -c ........ --clear-screen
  1675. Repaint by clearing rather than scrolling.
  1676. -d ........ --dumb
  1677. Dumb terminal.
  1678. -D [xn.n] . --color=xn.n
  1679. Set screen colors. (MS-DOS only)
  1680. -e -E .... --quit-at-eof --QUIT-AT-EOF
  1681. Quit at end of file.
  1682. -f ........ --force
  1683. Force open non-regular files.
  1684. -F ........ --quit-if-one-screen
  1685. Quit if entire file fits on first screen.
  1686. -g ........ --hilite-search
  1687. Highlight only last match for searches.
  1688. -G ........ --HILITE-SEARCH
  1689. Don't highlight any matches for searches.
  1690. -h [N] .... --max-back-scroll=[N]
  1691. Backward scroll limit.
  1692. -i ........ --ignore-case
  1693. Ignore case in searches that do not contain uppercase.
  1694. -I ........ --IGNORE-CASE
  1695. Ignore case in all searches.
  1696. -j [N] .... --jump-target=[N]
  1697. Screen position of target lines.
  1698. -J ........ --status-column
  1699. Display a status column at left edge of screen.
  1700. -k [file] . --lesskey-file=[file]
  1701. Use a lesskey file.
  1702. -L ........ --no-lessopen
  1703. Ignore the LESSOPEN environment variable.
  1704. -m -M .... --long-prompt --LONG-PROMPT
  1705. Set prompt style.
  1706. -n -N .... --line-numbers --LINE-NUMBERS
  1707. Don't use line numbers.
  1708. -o [file] . --log-file=[file]
  1709. Copy to log file (standard input only).
  1710. -O [file] . --LOG-FILE=[file]
  1711. Copy to log file (unconditionally overwrite).
  1712. -p [pattern] --pattern=[pattern]
  1713. Start at pattern (from command line).
  1714. -P [prompt] --prompt=[prompt]
  1715. Define new prompt.
  1716. -q -Q .... --quiet --QUIET --silent --SILENT
  1717. Quiet the terminal bell.
  1718. -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
  1719. Output "raw" control characters.
  1720. -s ........ --squeeze-blank-lines
  1721. Squeeze multiple blank lines.
  1722. -S ........ --chop-long-lines
  1723. Chop long lines.
  1724. -t [tag] .. --tag=[tag]
  1725. Find a tag.
  1726. -T [tagsfile] --tag-file=[tagsfile]
  1727. Use an alternate tags file.
  1728. -u -U .... --underline-special --UNDERLINE-SPECIAL
  1729. Change handling of backspaces.
  1730. -V ........ --version
  1731. Display the version number of "less".
  1732. -w ........ --hilite-unread
  1733. Highlight first new line after forward-screen.
  1734. -W ........ --HILITE-UNREAD
  1735. Highlight first new line after any forward movement.
  1736. -x [N[,...]] --tabs=[N[,...]]
  1737. Set tab stops.
  1738. -X ........ --no-init
  1739. Don't use termcap init/deinit strings.
  1740. --no-keypad
  1741. Don't use termcap keypad init/deinit strings.
  1742. -y [N] .... --max-forw-scroll=[N]
  1743. Forward scroll limit.
  1744. -z [N] .... --window=[N]
  1745. Set size of window.
  1746. -" [c[c]] . --quotes=[c[c]]
  1747. Set shell quote characters.
  1748. -~ ........ --tilde
  1749. Don't display tildes after end of file.
  1750. -# [N] .... --shift=[N]
  1751. Horizontal scroll amount (0 = one half screen width)
  1752. ---------------------------------------------------------------------------
  1753. LINE EDITING
  1754. These keys can be used to edit text being entered
  1755. on the "command line" at the bottom of the screen.
  1756. RightArrow ESC-l Move cursor right one character.
  1757. LeftArrow ESC-h Move cursor left one character.
  1758. CNTL-RightArrow ESC-RightArrow ESC-w Move cursor right one word.
  1759. CNTL-LeftArrow ESC-LeftArrow ESC-b Move cursor left one word.
  1760. HOME ESC-0 Move cursor to start of line.
  1761. END ESC-$ Move cursor to end of line.
  1762. BACKSPACE Delete char to left of cursor.
  1763. DELETE ESC-x Delete char under cursor.
  1764. CNTL-BACKSPACE ESC-BACKSPACE Delete word to left of cursor.
  1765. CNTL-DELETE ESC-DELETE ESC-X Delete word under cursor.
  1766. CNTL-U ESC (MS-DOS only) Delete entire line.
  1767. UpArrow ESC-k Retrieve previous command line.
  1768. DownArrow ESC-j Retrieve next command line.
  1769. TAB Complete filename & cycle.
  1770. SHIFT-TAB ESC-TAB Complete filename & reverse cycle.
  1771. CNTL-L Complete filename, list all.
  1772. */