less.c 56 KB

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