3
0

less.c 56 KB

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