lineedit.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Termios command line History and Editing.
  4. *
  5. * Copyright (c) 1986-2003 may safely be consumed by a BSD or GPL license.
  6. * Written by: Vladimir Oleynik <dzo@simtreas.ru>
  7. *
  8. * Used ideas:
  9. * Adam Rogoyski <rogoyski@cs.utexas.edu>
  10. * Dave Cinege <dcinege@psychosis.com>
  11. * Jakub Jelinek (c) 1995
  12. * Erik Andersen <andersen@codepoet.org> (Majorly adjusted for busybox)
  13. *
  14. * This code is 'as is' with no warranty.
  15. */
  16. /*
  17. * Usage and known bugs:
  18. * Terminal key codes are not extensive, and more will probably
  19. * need to be added. This version was created on Debian GNU/Linux 2.x.
  20. * Delete, Backspace, Home, End, and the arrow keys were tested
  21. * to work in an Xterm and console. Ctrl-A also works as Home.
  22. * Ctrl-E also works as End.
  23. *
  24. * lineedit does not know that the terminal escape sequences do not
  25. * take up space on the screen. The redisplay code assumes, unless
  26. * told otherwise, that each character in the prompt is a printable
  27. * character that takes up one character position on the screen.
  28. * You need to tell lineedit that some sequences of characters
  29. * in the prompt take up no screen space. Compatibly with readline,
  30. * use the \[ escape to begin a sequence of non-printing characters,
  31. * and the \] escape to signal the end of such a sequence. Example:
  32. *
  33. * PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
  34. */
  35. #include "libbb.h"
  36. #include "unicode.h"
  37. /* FIXME: obsolete CONFIG item? */
  38. #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
  39. #ifdef TEST
  40. # define ENABLE_FEATURE_EDITING 0
  41. # define ENABLE_FEATURE_TAB_COMPLETION 0
  42. # define ENABLE_FEATURE_USERNAME_COMPLETION 0
  43. # define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
  44. #endif
  45. /* Entire file (except TESTing part) sits inside this #if */
  46. #if ENABLE_FEATURE_EDITING
  47. #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
  48. (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
  49. #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
  50. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  51. #undef IF_FEATURE_GETUSERNAME_AND_HOMEDIR
  52. #define IF_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
  53. #endif
  54. #undef CHAR_T
  55. #if ENABLE_FEATURE_ASSUME_UNICODE
  56. # define BB_NUL L'\0'
  57. # define CHAR_T wchar_t
  58. # define BB_isspace(c) iswspace(c)
  59. # define BB_isalnum(c) iswalnum(c)
  60. # define BB_ispunct(c) iswpunct(c)
  61. # define BB_isprint(c) iswprint(c)
  62. /* this catches bugs */
  63. # undef isspace
  64. # undef isalnum
  65. # undef ispunct
  66. # undef isprint
  67. # define isspace isspace_must_not_be_used
  68. # define isalnum isalnum_must_not_be_used
  69. # define ispunct ispunct_must_not_be_used
  70. # define isprint isprint_must_not_be_used
  71. #else
  72. # define BB_NUL '\0'
  73. # define CHAR_T char
  74. # define BB_isspace(c) isspace(c)
  75. # define BB_isalnum(c) isalnum(c)
  76. # define BB_ispunct(c) ispunct(c)
  77. # if ENABLE_LOCALE_SUPPORT
  78. # define BB_isprint(c) isprint(c)
  79. # else
  80. # define BB_isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
  81. # endif
  82. #endif
  83. enum {
  84. /* We use int16_t for positions, need to limit line len */
  85. MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
  86. ? CONFIG_FEATURE_EDITING_MAX_LEN
  87. : 0x7ff0
  88. };
  89. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  90. static const char null_str[] ALIGN1 = "";
  91. #endif
  92. /* We try to minimize both static and stack usage. */
  93. struct lineedit_statics {
  94. line_input_t *state;
  95. volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
  96. sighandler_t previous_SIGWINCH_handler;
  97. unsigned cmdedit_x; /* real x (col) terminal position */
  98. unsigned cmdedit_y; /* pseudoreal y (row) terminal position */
  99. unsigned cmdedit_prmt_len; /* length of prompt (without colors etc) */
  100. unsigned cursor;
  101. unsigned command_len;
  102. /* *int* maxsize: we want x in "if (x > S.maxsize)"
  103. * to _not_ be promoted to unsigned */
  104. int maxsize;
  105. CHAR_T *command_ps;
  106. const char *cmdedit_prompt;
  107. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  108. int num_ok_lines; /* = 1; */
  109. #endif
  110. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  111. char *user_buf;
  112. char *home_pwd_buf; /* = (char*)null_str; */
  113. #endif
  114. #if ENABLE_FEATURE_TAB_COMPLETION
  115. char **matches;
  116. unsigned num_matches;
  117. #endif
  118. #if ENABLE_FEATURE_EDITING_VI
  119. #define DELBUFSIZ 128
  120. CHAR_T *delptr;
  121. smallint newdelflag; /* whether delbuf should be reused yet */
  122. CHAR_T delbuf[DELBUFSIZ]; /* a place to store deleted characters */
  123. #endif
  124. /* Formerly these were big buffers on stack: */
  125. #if ENABLE_FEATURE_TAB_COMPLETION
  126. char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
  127. char input_tab__matchBuf[MAX_LINELEN];
  128. int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
  129. int16_t find_match__pos_buf[MAX_LINELEN + 1];
  130. #endif
  131. };
  132. /* See lineedit_ptr_hack.c */
  133. extern struct lineedit_statics *const lineedit_ptr_to_statics;
  134. #define S (*lineedit_ptr_to_statics)
  135. #define state (S.state )
  136. #define cmdedit_termw (S.cmdedit_termw )
  137. #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
  138. #define cmdedit_x (S.cmdedit_x )
  139. #define cmdedit_y (S.cmdedit_y )
  140. #define cmdedit_prmt_len (S.cmdedit_prmt_len)
  141. #define cursor (S.cursor )
  142. #define command_len (S.command_len )
  143. #define command_ps (S.command_ps )
  144. #define cmdedit_prompt (S.cmdedit_prompt )
  145. #define num_ok_lines (S.num_ok_lines )
  146. #define user_buf (S.user_buf )
  147. #define home_pwd_buf (S.home_pwd_buf )
  148. #define matches (S.matches )
  149. #define num_matches (S.num_matches )
  150. #define delptr (S.delptr )
  151. #define newdelflag (S.newdelflag )
  152. #define delbuf (S.delbuf )
  153. #define INIT_S() do { \
  154. (*(struct lineedit_statics**)&lineedit_ptr_to_statics) = xzalloc(sizeof(S)); \
  155. barrier(); \
  156. cmdedit_termw = 80; \
  157. IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
  158. IF_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
  159. } while (0)
  160. static void deinit_S(void)
  161. {
  162. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  163. /* This one is allocated only if FANCY_PROMPT is on
  164. * (otherwise it points to verbatim prompt (NOT malloced) */
  165. free((char*)cmdedit_prompt);
  166. #endif
  167. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  168. free(user_buf);
  169. if (home_pwd_buf != null_str)
  170. free(home_pwd_buf);
  171. #endif
  172. free(lineedit_ptr_to_statics);
  173. }
  174. #define DEINIT_S() deinit_S()
  175. #if ENABLE_FEATURE_ASSUME_UNICODE
  176. static size_t load_string(const char *src, int maxsize)
  177. {
  178. ssize_t len = mbstowcs(command_ps, src, maxsize - 1);
  179. if (len < 0)
  180. len = 0;
  181. command_ps[len] = L'\0';
  182. return len;
  183. }
  184. static size_t save_string(char *dst, int maxsize)
  185. {
  186. ssize_t len = wcstombs(dst, command_ps, maxsize - 1);
  187. if (len < 0)
  188. len = 0;
  189. dst[len] = '\0';
  190. return len;
  191. }
  192. /* I thought just fputwc(c, stdout) would work. But no... */
  193. static void BB_PUTCHAR(wchar_t c)
  194. {
  195. char buf[MB_CUR_MAX + 1];
  196. mbstate_t mbst = { 0 };
  197. ssize_t len = wcrtomb(buf, c, &mbst);
  198. if (len > 0) {
  199. buf[len] = '\0';
  200. fputs(buf, stdout);
  201. }
  202. }
  203. #else
  204. static size_t load_string(const char *src, int maxsize)
  205. {
  206. safe_strncpy(command_ps, src, maxsize);
  207. return strlen(command_ps);
  208. }
  209. # if ENABLE_FEATURE_TAB_COMPLETION
  210. static void save_string(char *dst, int maxsize)
  211. {
  212. safe_strncpy(dst, command_ps, maxsize);
  213. }
  214. # endif
  215. # define BB_PUTCHAR(c) bb_putchar(c)
  216. #endif
  217. /* Put 'command_ps[cursor]', cursor++.
  218. * Advance cursor on screen. If we reached right margin, scroll text up
  219. * and remove terminal margin effect by printing 'next_char' */
  220. #define HACK_FOR_WRONG_WIDTH 1
  221. #if HACK_FOR_WRONG_WIDTH
  222. static void cmdedit_set_out_char(void)
  223. #define cmdedit_set_out_char(next_char) cmdedit_set_out_char()
  224. #else
  225. static void cmdedit_set_out_char(int next_char)
  226. #endif
  227. {
  228. CHAR_T c = command_ps[cursor];
  229. if (c == BB_NUL) {
  230. /* erase character after end of input string */
  231. c = ' ';
  232. }
  233. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  234. /* Display non-printable characters in reverse */
  235. if (!BB_isprint(c)) {
  236. if (c >= 128)
  237. c -= 128;
  238. if (c < ' ')
  239. c += '@';
  240. if (c == 127)
  241. c = '?';
  242. printf("\033[7m%c\033[0m", c);
  243. } else
  244. #endif
  245. {
  246. BB_PUTCHAR(c);
  247. }
  248. if (++cmdedit_x >= cmdedit_termw) {
  249. /* terminal is scrolled down */
  250. cmdedit_y++;
  251. cmdedit_x = 0;
  252. #if HACK_FOR_WRONG_WIDTH
  253. /* This works better if our idea of term width is wrong
  254. * and it is actually wider (often happens on serial lines).
  255. * Printing CR,LF *forces* cursor to next line.
  256. * OTOH if terminal width is correct AND terminal does NOT
  257. * have automargin (IOW: it is moving cursor to next line
  258. * by itself (which is wrong for VT-10x terminals)),
  259. * this will break things: there will be one extra empty line */
  260. puts("\r"); /* + implicit '\n' */
  261. #else
  262. /* Works ok only if cmdedit_termw is correct */
  263. /* destroy "(auto)margin" */
  264. bb_putchar(next_char);
  265. bb_putchar('\b');
  266. #endif
  267. }
  268. // Huh? What if command_ps[cursor] == BB_NUL (we are at the end already?)
  269. cursor++;
  270. }
  271. /* Move to end of line (by printing all chars till the end) */
  272. static void input_end(void)
  273. {
  274. while (cursor < command_len)
  275. cmdedit_set_out_char(' ');
  276. }
  277. /* Go to the next line */
  278. static void goto_new_line(void)
  279. {
  280. input_end();
  281. if (cmdedit_x)
  282. bb_putchar('\n');
  283. }
  284. static void out1str(const char *s)
  285. {
  286. if (s)
  287. fputs(s, stdout);
  288. }
  289. static void beep(void)
  290. {
  291. bb_putchar('\007');
  292. }
  293. /* Move back one character */
  294. /* (optimized for slow terminals) */
  295. static void input_backward(unsigned num)
  296. {
  297. int count_y;
  298. if (num > cursor)
  299. num = cursor;
  300. if (!num)
  301. return;
  302. cursor -= num;
  303. if (cmdedit_x >= num) {
  304. cmdedit_x -= num;
  305. if (num <= 4) {
  306. /* This is longer by 5 bytes on x86.
  307. * Also gets miscompiled for ARM users
  308. * (busybox.net/bugs/view.php?id=2274).
  309. * printf(("\b\b\b\b" + 4) - num);
  310. * return;
  311. */
  312. do {
  313. bb_putchar('\b');
  314. } while (--num);
  315. return;
  316. }
  317. printf("\033[%uD", num);
  318. return;
  319. }
  320. /* Need to go one or more lines up */
  321. num -= cmdedit_x;
  322. {
  323. unsigned w = cmdedit_termw; /* volatile var */
  324. count_y = 1 + (num / w);
  325. cmdedit_y -= count_y;
  326. cmdedit_x = w * count_y - num;
  327. }
  328. /* go to 1st column; go up; go to correct column */
  329. printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
  330. }
  331. static void put_prompt(void)
  332. {
  333. out1str(cmdedit_prompt);
  334. if (ENABLE_FEATURE_EDITING_ASK_TERMINAL) {
  335. /* Ask terminal where is the cursor now.
  336. * lineedit_read_key handles response and corrects
  337. * our idea of current cursor position.
  338. * Testcase: run "echo -n long_line_long_line_long_line",
  339. * then type in a long, wrapping command and try to
  340. * delete it using backspace key.
  341. * Note: we print it _after_ prompt, because
  342. * prompt may contain CR. Example: PS1='\[\r\n\]\w '
  343. */
  344. out1str("\033" "[6n");
  345. }
  346. cursor = 0;
  347. {
  348. unsigned w = cmdedit_termw; /* volatile var */
  349. cmdedit_y = cmdedit_prmt_len / w; /* new quasireal y */
  350. cmdedit_x = cmdedit_prmt_len % w;
  351. }
  352. }
  353. /* draw prompt, editor line, and clear tail */
  354. static void redraw(int y, int back_cursor)
  355. {
  356. if (y > 0) /* up to start y */
  357. printf("\033[%uA", y);
  358. bb_putchar('\r');
  359. put_prompt();
  360. input_end(); /* rewrite */
  361. printf("\033[J"); /* erase after cursor */
  362. input_backward(back_cursor);
  363. }
  364. /* Delete the char in front of the cursor, optionally saving it
  365. * for later putback */
  366. #if !ENABLE_FEATURE_EDITING_VI
  367. static void input_delete(void)
  368. #define input_delete(save) input_delete()
  369. #else
  370. static void input_delete(int save)
  371. #endif
  372. {
  373. int j = cursor;
  374. if (j == (int)command_len)
  375. return;
  376. #if ENABLE_FEATURE_EDITING_VI
  377. if (save) {
  378. if (newdelflag) {
  379. delptr = delbuf;
  380. newdelflag = 0;
  381. }
  382. if ((delptr - delbuf) < DELBUFSIZ)
  383. *delptr++ = command_ps[j];
  384. }
  385. #endif
  386. memmove(command_ps + j, command_ps + j + 1,
  387. /* (command_len + 1 [because of NUL]) - (j + 1)
  388. * simplified into (command_len - j) */
  389. (command_len - j) * sizeof(command_ps[0]));
  390. command_len--;
  391. input_end(); /* rewrite new line */
  392. cmdedit_set_out_char(' '); /* erase char */
  393. input_backward(cursor - j); /* back to old pos cursor */
  394. }
  395. #if ENABLE_FEATURE_EDITING_VI
  396. static void put(void)
  397. {
  398. int ocursor;
  399. int j = delptr - delbuf;
  400. if (j == 0)
  401. return;
  402. ocursor = cursor;
  403. /* open hole and then fill it */
  404. memmove(command_ps + cursor + j, command_ps + cursor,
  405. (command_len - cursor + 1) * sizeof(command_ps[0]));
  406. memcpy(command_ps + cursor, delbuf, j * sizeof(command_ps[0]));
  407. command_len += j;
  408. input_end(); /* rewrite new line */
  409. input_backward(cursor - ocursor - j + 1); /* at end of new text */
  410. }
  411. #endif
  412. /* Delete the char in back of the cursor */
  413. static void input_backspace(void)
  414. {
  415. if (cursor > 0) {
  416. input_backward(1);
  417. input_delete(0);
  418. }
  419. }
  420. /* Move forward one character */
  421. static void input_forward(void)
  422. {
  423. if (cursor < command_len)
  424. cmdedit_set_out_char(command_ps[cursor + 1]);
  425. }
  426. #if ENABLE_FEATURE_TAB_COMPLETION
  427. static void free_tab_completion_data(void)
  428. {
  429. if (matches) {
  430. while (num_matches)
  431. free(matches[--num_matches]);
  432. free(matches);
  433. matches = NULL;
  434. }
  435. }
  436. static void add_match(char *matched)
  437. {
  438. matches = xrealloc_vector(matches, 4, num_matches);
  439. matches[num_matches] = matched;
  440. num_matches++;
  441. }
  442. #if ENABLE_FEATURE_USERNAME_COMPLETION
  443. static void username_tab_completion(char *ud, char *with_shash_flg)
  444. {
  445. struct passwd *entry;
  446. int userlen;
  447. ud++; /* ~user/... to user/... */
  448. userlen = strlen(ud);
  449. if (with_shash_flg) { /* "~/..." or "~user/..." */
  450. char *sav_ud = ud - 1;
  451. char *home = NULL;
  452. if (*ud == '/') { /* "~/..." */
  453. home = home_pwd_buf;
  454. } else {
  455. /* "~user/..." */
  456. char *temp;
  457. temp = strchr(ud, '/');
  458. *temp = '\0'; /* ~user\0 */
  459. entry = getpwnam(ud);
  460. *temp = '/'; /* restore ~user/... */
  461. ud = temp;
  462. if (entry)
  463. home = entry->pw_dir;
  464. }
  465. if (home) {
  466. if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
  467. /* /home/user/... */
  468. sprintf(sav_ud, "%s%s", home, ud);
  469. }
  470. }
  471. } else {
  472. /* "~[^/]*" */
  473. /* Using _r function to avoid pulling in static buffers */
  474. char line_buff[256];
  475. struct passwd pwd;
  476. struct passwd *result;
  477. setpwent();
  478. while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
  479. /* Null usernames should result in all users as possible completions. */
  480. if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
  481. add_match(xasprintf("~%s/", pwd.pw_name));
  482. }
  483. }
  484. endpwent();
  485. }
  486. }
  487. #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
  488. enum {
  489. FIND_EXE_ONLY = 0,
  490. FIND_DIR_ONLY = 1,
  491. FIND_FILE_ONLY = 2,
  492. };
  493. static int path_parse(char ***p, int flags)
  494. {
  495. int npth;
  496. const char *pth;
  497. char *tmp;
  498. char **res;
  499. /* if not setenv PATH variable, to search cur dir "." */
  500. if (flags != FIND_EXE_ONLY)
  501. return 1;
  502. if (state->flags & WITH_PATH_LOOKUP)
  503. pth = state->path_lookup;
  504. else
  505. pth = getenv("PATH");
  506. /* PATH=<empty> or PATH=:<empty> */
  507. if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
  508. return 1;
  509. tmp = (char*)pth;
  510. npth = 1; /* path component count */
  511. while (1) {
  512. tmp = strchr(tmp, ':');
  513. if (!tmp)
  514. break;
  515. if (*++tmp == '\0')
  516. break; /* :<empty> */
  517. npth++;
  518. }
  519. res = xmalloc(npth * sizeof(char*));
  520. res[0] = tmp = xstrdup(pth);
  521. npth = 1;
  522. while (1) {
  523. tmp = strchr(tmp, ':');
  524. if (!tmp)
  525. break;
  526. *tmp++ = '\0'; /* ':' -> '\0' */
  527. if (*tmp == '\0')
  528. break; /* :<empty> */
  529. res[npth++] = tmp;
  530. }
  531. *p = res;
  532. return npth;
  533. }
  534. static void exe_n_cwd_tab_completion(char *command, int type)
  535. {
  536. DIR *dir;
  537. struct dirent *next;
  538. struct stat st;
  539. char *path1[1];
  540. char **paths = path1;
  541. int npaths;
  542. int i;
  543. char *found;
  544. char *pfind = strrchr(command, '/');
  545. /* char dirbuf[MAX_LINELEN]; */
  546. #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
  547. npaths = 1;
  548. path1[0] = (char*)".";
  549. if (pfind == NULL) {
  550. /* no dir, if flags==EXE_ONLY - get paths, else "." */
  551. npaths = path_parse(&paths, type);
  552. pfind = command;
  553. } else {
  554. /* dirbuf = ".../.../.../" */
  555. safe_strncpy(dirbuf, command, (pfind - command) + 2);
  556. #if ENABLE_FEATURE_USERNAME_COMPLETION
  557. if (dirbuf[0] == '~') /* ~/... or ~user/... */
  558. username_tab_completion(dirbuf, dirbuf);
  559. #endif
  560. paths[0] = dirbuf;
  561. /* point to 'l' in "..../last_component" */
  562. pfind++;
  563. }
  564. for (i = 0; i < npaths; i++) {
  565. dir = opendir(paths[i]);
  566. if (!dir)
  567. continue; /* don't print an error */
  568. while ((next = readdir(dir)) != NULL) {
  569. int len1;
  570. const char *str_found = next->d_name;
  571. /* matched? */
  572. if (strncmp(str_found, pfind, strlen(pfind)))
  573. continue;
  574. /* not see .name without .match */
  575. if (*str_found == '.' && *pfind == '\0') {
  576. if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
  577. continue;
  578. str_found = ""; /* only "/" */
  579. }
  580. found = concat_path_file(paths[i], str_found);
  581. /* hmm, remove in progress? */
  582. /* NB: stat() first so that we see is it a directory;
  583. * but if that fails, use lstat() so that
  584. * we still match dangling links */
  585. if (stat(found, &st) && lstat(found, &st))
  586. goto cont;
  587. /* find with dirs? */
  588. if (paths[i] != dirbuf)
  589. strcpy(found, next->d_name); /* only name */
  590. len1 = strlen(found);
  591. found = xrealloc(found, len1 + 2);
  592. found[len1] = '\0';
  593. found[len1+1] = '\0';
  594. if (S_ISDIR(st.st_mode)) {
  595. /* name is a directory */
  596. if (found[len1-1] != '/') {
  597. found[len1] = '/';
  598. }
  599. } else {
  600. /* not put found file if search only dirs for cd */
  601. if (type == FIND_DIR_ONLY)
  602. goto cont;
  603. }
  604. /* Add it to the list */
  605. add_match(found);
  606. continue;
  607. cont:
  608. free(found);
  609. }
  610. closedir(dir);
  611. }
  612. if (paths != path1) {
  613. free(paths[0]); /* allocated memory is only in first member */
  614. free(paths);
  615. }
  616. #undef dirbuf
  617. }
  618. /* QUOT is used on elements of int_buf[], which are bytes,
  619. * not Unicode chars. Therefore it works correctly even in Unicode mode.
  620. */
  621. #define QUOT (UCHAR_MAX+1)
  622. #define int_buf (S.find_match__int_buf)
  623. #define pos_buf (S.find_match__pos_buf)
  624. /* is must be <= in */
  625. static void collapse_pos(int is, int in)
  626. {
  627. memmove(int_buf+is, int_buf+in, (MAX_LINELEN+1-in)*sizeof(int_buf[0]));
  628. memmove(pos_buf+is, pos_buf+in, (MAX_LINELEN+1-in)*sizeof(pos_buf[0]));
  629. }
  630. static NOINLINE int find_match(char *matchBuf, int *len_with_quotes)
  631. {
  632. int i, j;
  633. int command_mode;
  634. int c, c2;
  635. /* Were local, but it uses too much stack */
  636. /* int16_t int_buf[MAX_LINELEN + 1]; */
  637. /* int16_t pos_buf[MAX_LINELEN + 1]; */
  638. /* set to integer dimension characters and own positions */
  639. for (i = 0;; i++) {
  640. int_buf[i] = (unsigned char)matchBuf[i];
  641. if (int_buf[i] == 0) {
  642. pos_buf[i] = -1; /* end-fo-line indicator */
  643. break;
  644. }
  645. pos_buf[i] = i;
  646. }
  647. /* mask \+symbol and convert '\t' to ' ' */
  648. for (i = j = 0; matchBuf[i]; i++, j++)
  649. if (matchBuf[i] == '\\') {
  650. collapse_pos(j, j + 1);
  651. int_buf[j] |= QUOT;
  652. i++;
  653. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  654. if (matchBuf[i] == '\t') /* algorithm equivalent */
  655. int_buf[j] = ' ' | QUOT;
  656. #endif
  657. }
  658. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  659. else if (matchBuf[i] == '\t')
  660. int_buf[j] = ' ';
  661. #endif
  662. /* mask "symbols" or 'symbols' */
  663. c2 = 0;
  664. for (i = 0; int_buf[i]; i++) {
  665. c = int_buf[i];
  666. if (c == '\'' || c == '"') {
  667. if (c2 == 0)
  668. c2 = c;
  669. else {
  670. if (c == c2)
  671. c2 = 0;
  672. else
  673. int_buf[i] |= QUOT;
  674. }
  675. } else if (c2 != 0 && c != '$')
  676. int_buf[i] |= QUOT;
  677. }
  678. /* skip commands with arguments if line has commands delimiters */
  679. /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
  680. for (i = 0; int_buf[i]; i++) {
  681. c = int_buf[i];
  682. c2 = int_buf[i + 1];
  683. j = i ? int_buf[i - 1] : -1;
  684. command_mode = 0;
  685. if (c == ';' || c == '&' || c == '|') {
  686. command_mode = 1 + (c == c2);
  687. if (c == '&') {
  688. if (j == '>' || j == '<')
  689. command_mode = 0;
  690. } else if (c == '|' && j == '>')
  691. command_mode = 0;
  692. }
  693. if (command_mode) {
  694. collapse_pos(0, i + command_mode);
  695. i = -1; /* hack incremet */
  696. }
  697. }
  698. /* collapse `command...` */
  699. for (i = 0; int_buf[i]; i++) {
  700. if (int_buf[i] == '`') {
  701. for (j = i + 1; int_buf[j]; j++)
  702. if (int_buf[j] == '`') {
  703. collapse_pos(i, j + 1);
  704. j = 0;
  705. break;
  706. }
  707. if (j) {
  708. /* not found closing ` - command mode, collapse all previous */
  709. collapse_pos(0, i + 1);
  710. break;
  711. } else
  712. i--; /* hack incremet */
  713. }
  714. }
  715. /* collapse (command...(command...)...) or {command...{command...}...} */
  716. c = 0; /* "recursive" level */
  717. c2 = 0;
  718. for (i = 0; int_buf[i]; i++) {
  719. if (int_buf[i] == '(' || int_buf[i] == '{') {
  720. if (int_buf[i] == '(')
  721. c++;
  722. else
  723. c2++;
  724. collapse_pos(0, i + 1);
  725. i = -1; /* hack incremet */
  726. }
  727. }
  728. for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++) {
  729. if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
  730. if (int_buf[i] == ')')
  731. c--;
  732. else
  733. c2--;
  734. collapse_pos(0, i + 1);
  735. i = -1; /* hack incremet */
  736. }
  737. }
  738. /* skip first not quote space */
  739. for (i = 0; int_buf[i]; i++)
  740. if (int_buf[i] != ' ')
  741. break;
  742. if (i)
  743. collapse_pos(0, i);
  744. /* set find mode for completion */
  745. command_mode = FIND_EXE_ONLY;
  746. for (i = 0; int_buf[i]; i++) {
  747. if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
  748. if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
  749. && matchBuf[pos_buf[0]] == 'c'
  750. && matchBuf[pos_buf[1]] == 'd'
  751. ) {
  752. command_mode = FIND_DIR_ONLY;
  753. } else {
  754. command_mode = FIND_FILE_ONLY;
  755. break;
  756. }
  757. }
  758. }
  759. for (i = 0; int_buf[i]; i++)
  760. /* "strlen" */;
  761. /* find last word */
  762. for (--i; i >= 0; i--) {
  763. c = int_buf[i];
  764. if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
  765. collapse_pos(0, i + 1);
  766. break;
  767. }
  768. }
  769. /* skip first not quoted '\'' or '"' */
  770. for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
  771. /*skip*/;
  772. /* collapse quote or unquote // or /~ */
  773. while ((int_buf[i] & ~QUOT) == '/'
  774. && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
  775. ) {
  776. i++;
  777. }
  778. /* set only match and destroy quotes */
  779. j = 0;
  780. for (c = 0; pos_buf[i] >= 0; i++) {
  781. matchBuf[c++] = matchBuf[pos_buf[i]];
  782. j = pos_buf[i] + 1;
  783. }
  784. matchBuf[c] = '\0';
  785. /* old length matchBuf with quotes symbols */
  786. *len_with_quotes = j ? j - pos_buf[0] : 0;
  787. return command_mode;
  788. }
  789. #undef int_buf
  790. #undef pos_buf
  791. /*
  792. * display by column (original idea from ls applet,
  793. * very optimized by me :)
  794. */
  795. static void showfiles(void)
  796. {
  797. int ncols, row;
  798. int column_width = 0;
  799. int nfiles = num_matches;
  800. int nrows = nfiles;
  801. int l;
  802. /* find the longest file name - use that as the column width */
  803. for (row = 0; row < nrows; row++) {
  804. l = bb_mbstrlen(matches[row]);
  805. if (column_width < l)
  806. column_width = l;
  807. }
  808. column_width += 2; /* min space for columns */
  809. ncols = cmdedit_termw / column_width;
  810. if (ncols > 1) {
  811. nrows /= ncols;
  812. if (nfiles % ncols)
  813. nrows++; /* round up fractionals */
  814. } else {
  815. ncols = 1;
  816. }
  817. for (row = 0; row < nrows; row++) {
  818. int n = row;
  819. int nc;
  820. for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
  821. printf("%s%-*s", matches[n],
  822. (int)(column_width - bb_mbstrlen(matches[n])), ""
  823. );
  824. }
  825. puts(matches[n]);
  826. }
  827. }
  828. static char *add_quote_for_spec_chars(char *found)
  829. {
  830. int l = 0;
  831. char *s = xzalloc((strlen(found) + 1) * 2);
  832. while (*found) {
  833. if (strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", *found))
  834. s[l++] = '\\';
  835. s[l++] = *found++;
  836. }
  837. /* s[l] = '\0'; - already is */
  838. return s;
  839. }
  840. /* Do TAB completion */
  841. static void input_tab(smallint *lastWasTab)
  842. {
  843. if (!(state->flags & TAB_COMPLETION))
  844. return;
  845. if (!*lastWasTab) {
  846. char *tmp, *tmp1;
  847. size_t len_found;
  848. /* char matchBuf[MAX_LINELEN]; */
  849. #define matchBuf (S.input_tab__matchBuf)
  850. int find_type;
  851. int recalc_pos;
  852. #if ENABLE_FEATURE_ASSUME_UNICODE
  853. /* cursor pos in command converted to multibyte form */
  854. int cursor_mb;
  855. #endif
  856. *lastWasTab = TRUE; /* flop trigger */
  857. /* Make a local copy of the string --
  858. * up to the position of the cursor */
  859. save_string(matchBuf, cursor + 1);
  860. #if ENABLE_FEATURE_ASSUME_UNICODE
  861. cursor_mb = strlen(matchBuf);
  862. #endif
  863. tmp = matchBuf;
  864. find_type = find_match(matchBuf, &recalc_pos);
  865. /* Free up any memory already allocated */
  866. free_tab_completion_data();
  867. #if ENABLE_FEATURE_USERNAME_COMPLETION
  868. /* If the word starts with `~' and there is no slash in the word,
  869. * then try completing this word as a username. */
  870. if (state->flags & USERNAME_COMPLETION)
  871. if (matchBuf[0] == '~' && strchr(matchBuf, '/') == NULL)
  872. username_tab_completion(matchBuf, NULL);
  873. #endif
  874. /* Try to match any executable in our path and everything
  875. * in the current working directory */
  876. if (!matches)
  877. exe_n_cwd_tab_completion(matchBuf, find_type);
  878. /* Sort, then remove any duplicates found */
  879. if (matches) {
  880. unsigned i;
  881. int n = 0;
  882. qsort_string_vector(matches, num_matches);
  883. for (i = 0; i < num_matches - 1; ++i) {
  884. if (matches[i] && matches[i+1]) { /* paranoia */
  885. if (strcmp(matches[i], matches[i+1]) == 0) {
  886. free(matches[i]);
  887. matches[i] = NULL; /* paranoia */
  888. } else {
  889. matches[n++] = matches[i];
  890. }
  891. }
  892. }
  893. matches[n] = matches[i];
  894. num_matches = n + 1;
  895. }
  896. /* Did we find exactly one match? */
  897. if (!matches || num_matches > 1) { /* no */
  898. beep();
  899. if (!matches)
  900. return; /* not found */
  901. /* find minimal match */
  902. tmp1 = xstrdup(matches[0]);
  903. for (tmp = tmp1; *tmp; tmp++) {
  904. for (len_found = 1; len_found < num_matches; len_found++) {
  905. if (matches[len_found][tmp - tmp1] != *tmp) {
  906. *tmp = '\0';
  907. break;
  908. }
  909. }
  910. }
  911. if (*tmp1 == '\0') { /* have unique */
  912. free(tmp1);
  913. return;
  914. }
  915. tmp = add_quote_for_spec_chars(tmp1);
  916. free(tmp1);
  917. } else { /* one match */
  918. tmp = add_quote_for_spec_chars(matches[0]);
  919. /* for next completion current found */
  920. *lastWasTab = FALSE;
  921. len_found = strlen(tmp);
  922. if (tmp[len_found-1] != '/') {
  923. tmp[len_found] = ' ';
  924. tmp[len_found+1] = '\0';
  925. }
  926. }
  927. len_found = strlen(tmp);
  928. #if !ENABLE_FEATURE_ASSUME_UNICODE
  929. /* have space to place the match? */
  930. /* The result consists of three parts with these lengths: */
  931. /* (cursor - recalc_pos) + len_found + (command_len - cursor) */
  932. /* it simplifies into: */
  933. if ((int)(len_found + command_len - recalc_pos) < S.maxsize) {
  934. /* save tail */
  935. strcpy(matchBuf, command_ps + cursor);
  936. /* add match and tail */
  937. sprintf(&command_ps[cursor - recalc_pos], "%s%s", tmp, matchBuf);
  938. command_len = strlen(command_ps);
  939. /* new pos */
  940. recalc_pos = cursor - recalc_pos + len_found;
  941. /* write out the matched command */
  942. redraw(cmdedit_y, command_len - recalc_pos);
  943. }
  944. #else
  945. {
  946. char command[MAX_LINELEN];
  947. int len = save_string(command, sizeof(command));
  948. /* have space to place the match? */
  949. /* (cursor_mb - recalc_pos) + len_found + (len - cursor_mb) */
  950. if ((int)(len_found + len - recalc_pos) < MAX_LINELEN) {
  951. /* save tail */
  952. strcpy(matchBuf, command + cursor_mb);
  953. /* where do we want to have cursor after all? */
  954. strcpy(&command[cursor_mb - recalc_pos], tmp);
  955. len = load_string(command, S.maxsize);
  956. /* add match and tail */
  957. sprintf(&command[cursor_mb - recalc_pos], "%s%s", tmp, matchBuf);
  958. command_len = load_string(command, S.maxsize);
  959. /* write out the matched command */
  960. redraw(cmdedit_y, command_len - len);
  961. }
  962. }
  963. #endif
  964. free(tmp);
  965. #undef matchBuf
  966. } else {
  967. /* Ok -- the last char was a TAB. Since they
  968. * just hit TAB again, print a list of all the
  969. * available choices... */
  970. if (matches && num_matches > 0) {
  971. /* changed by goto_new_line() */
  972. int sav_cursor = cursor;
  973. /* Go to the next line */
  974. goto_new_line();
  975. showfiles();
  976. redraw(0, command_len - sav_cursor);
  977. }
  978. }
  979. }
  980. #endif /* FEATURE_COMMAND_TAB_COMPLETION */
  981. line_input_t* FAST_FUNC new_line_input_t(int flags)
  982. {
  983. line_input_t *n = xzalloc(sizeof(*n));
  984. n->flags = flags;
  985. return n;
  986. }
  987. #if MAX_HISTORY > 0
  988. static void save_command_ps_at_cur_history(void)
  989. {
  990. if (command_ps[0] != BB_NUL) {
  991. int cur = state->cur_history;
  992. free(state->history[cur]);
  993. #if ENABLE_FEATURE_ASSUME_UNICODE
  994. {
  995. char tbuf[MAX_LINELEN];
  996. save_string(tbuf, sizeof(tbuf));
  997. state->history[cur] = xstrdup(tbuf);
  998. }
  999. #else
  1000. state->history[cur] = xstrdup(command_ps);
  1001. #endif
  1002. }
  1003. }
  1004. /* state->flags is already checked to be nonzero */
  1005. static int get_previous_history(void)
  1006. {
  1007. if ((state->flags & DO_HISTORY) && state->cur_history) {
  1008. save_command_ps_at_cur_history();
  1009. state->cur_history--;
  1010. return 1;
  1011. }
  1012. beep();
  1013. return 0;
  1014. }
  1015. static int get_next_history(void)
  1016. {
  1017. if (state->flags & DO_HISTORY) {
  1018. if (state->cur_history < state->cnt_history) {
  1019. save_command_ps_at_cur_history(); /* save the current history line */
  1020. return ++state->cur_history;
  1021. }
  1022. }
  1023. beep();
  1024. return 0;
  1025. }
  1026. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1027. /* We try to ensure that concurrent additions to the history
  1028. * do not overwrite each other.
  1029. * Otherwise shell users get unhappy.
  1030. *
  1031. * History file is trimmed lazily, when it grows several times longer
  1032. * than configured MAX_HISTORY lines.
  1033. */
  1034. static void free_line_input_t(line_input_t *n)
  1035. {
  1036. int i = n->cnt_history;
  1037. while (i > 0)
  1038. free(n->history[--i]);
  1039. free(n);
  1040. }
  1041. /* state->flags is already checked to be nonzero */
  1042. static void load_history(line_input_t *st_parm)
  1043. {
  1044. char *temp_h[MAX_HISTORY];
  1045. char *line;
  1046. FILE *fp;
  1047. unsigned idx, i, line_len;
  1048. /* NB: do not trash old history if file can't be opened */
  1049. fp = fopen_for_read(st_parm->hist_file);
  1050. if (fp) {
  1051. /* clean up old history */
  1052. for (idx = st_parm->cnt_history; idx > 0;) {
  1053. idx--;
  1054. free(st_parm->history[idx]);
  1055. st_parm->history[idx] = NULL;
  1056. }
  1057. /* fill temp_h[], retaining only last MAX_HISTORY lines */
  1058. memset(temp_h, 0, sizeof(temp_h));
  1059. st_parm->cnt_history_in_file = idx = 0;
  1060. while ((line = xmalloc_fgetline(fp)) != NULL) {
  1061. if (line[0] == '\0') {
  1062. free(line);
  1063. continue;
  1064. }
  1065. free(temp_h[idx]);
  1066. temp_h[idx] = line;
  1067. st_parm->cnt_history_in_file++;
  1068. idx++;
  1069. if (idx == MAX_HISTORY)
  1070. idx = 0;
  1071. }
  1072. fclose(fp);
  1073. /* find first non-NULL temp_h[], if any */
  1074. if (st_parm->cnt_history_in_file) {
  1075. while (temp_h[idx] == NULL) {
  1076. idx++;
  1077. if (idx == MAX_HISTORY)
  1078. idx = 0;
  1079. }
  1080. }
  1081. /* copy temp_h[] to st_parm->history[] */
  1082. for (i = 0; i < MAX_HISTORY;) {
  1083. line = temp_h[idx];
  1084. if (!line)
  1085. break;
  1086. idx++;
  1087. if (idx == MAX_HISTORY)
  1088. idx = 0;
  1089. line_len = strlen(line);
  1090. if (line_len >= MAX_LINELEN)
  1091. line[MAX_LINELEN-1] = '\0';
  1092. st_parm->history[i++] = line;
  1093. }
  1094. st_parm->cnt_history = i;
  1095. }
  1096. }
  1097. /* state->flags is already checked to be nonzero */
  1098. static void save_history(char *str)
  1099. {
  1100. int fd;
  1101. int len, len2;
  1102. fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0666);
  1103. if (fd < 0)
  1104. return;
  1105. xlseek(fd, 0, SEEK_END); /* paranoia */
  1106. len = strlen(str);
  1107. str[len] = '\n'; /* we (try to) do atomic write */
  1108. len2 = full_write(fd, str, len + 1);
  1109. str[len] = '\0';
  1110. close(fd);
  1111. if (len2 != len + 1)
  1112. return; /* "wtf?" */
  1113. /* did we write so much that history file needs trimming? */
  1114. state->cnt_history_in_file++;
  1115. if (state->cnt_history_in_file > MAX_HISTORY * 4) {
  1116. FILE *fp;
  1117. char *new_name;
  1118. line_input_t *st_temp;
  1119. int i;
  1120. /* we may have concurrently written entries from others.
  1121. * load them */
  1122. st_temp = new_line_input_t(state->flags);
  1123. st_temp->hist_file = state->hist_file;
  1124. load_history(st_temp);
  1125. /* write out temp file and replace hist_file atomically */
  1126. new_name = xasprintf("%s.%u.new", state->hist_file, (int) getpid());
  1127. fp = fopen_for_write(new_name);
  1128. if (fp) {
  1129. for (i = 0; i < st_temp->cnt_history; i++)
  1130. fprintf(fp, "%s\n", st_temp->history[i]);
  1131. fclose(fp);
  1132. if (rename(new_name, state->hist_file) == 0)
  1133. state->cnt_history_in_file = st_temp->cnt_history;
  1134. }
  1135. free(new_name);
  1136. free_line_input_t(st_temp);
  1137. }
  1138. }
  1139. #else
  1140. #define load_history(a) ((void)0)
  1141. #define save_history(a) ((void)0)
  1142. #endif /* FEATURE_COMMAND_SAVEHISTORY */
  1143. static void remember_in_history(char *str)
  1144. {
  1145. int i;
  1146. if (!(state->flags & DO_HISTORY))
  1147. return;
  1148. if (str[0] == '\0')
  1149. return;
  1150. i = state->cnt_history;
  1151. /* Don't save dupes */
  1152. if (i && strcmp(state->history[i-1], str) == 0)
  1153. return;
  1154. free(state->history[MAX_HISTORY]); /* redundant, paranoia */
  1155. state->history[MAX_HISTORY] = NULL; /* redundant, paranoia */
  1156. /* If history[] is full, remove the oldest command */
  1157. /* we need to keep history[MAX_HISTORY] empty, hence >=, not > */
  1158. if (i >= MAX_HISTORY) {
  1159. free(state->history[0]);
  1160. for (i = 0; i < MAX_HISTORY-1; i++)
  1161. state->history[i] = state->history[i+1];
  1162. /* i == MAX_HISTORY-1 */
  1163. }
  1164. /* i <= MAX_HISTORY-1 */
  1165. state->history[i++] = xstrdup(str);
  1166. /* i <= MAX_HISTORY */
  1167. state->cur_history = i;
  1168. state->cnt_history = i;
  1169. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1170. if ((state->flags & SAVE_HISTORY) && state->hist_file)
  1171. save_history(str);
  1172. #endif
  1173. IF_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
  1174. }
  1175. #else /* MAX_HISTORY == 0 */
  1176. #define remember_in_history(a) ((void)0)
  1177. #endif /* MAX_HISTORY */
  1178. /*
  1179. * This function is used to grab a character buffer
  1180. * from the input file descriptor and allows you to
  1181. * a string with full command editing (sort of like
  1182. * a mini readline).
  1183. *
  1184. * The following standard commands are not implemented:
  1185. * ESC-b -- Move back one word
  1186. * ESC-f -- Move forward one word
  1187. * ESC-d -- Delete back one word
  1188. * ESC-h -- Delete forward one word
  1189. * CTL-t -- Transpose two characters
  1190. *
  1191. * Minimalist vi-style command line editing available if configured.
  1192. * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
  1193. */
  1194. #if ENABLE_FEATURE_EDITING_VI
  1195. static void
  1196. vi_Word_motion(int eat)
  1197. {
  1198. CHAR_T *command = command_ps;
  1199. while (cursor < command_len && !BB_isspace(command[cursor]))
  1200. input_forward();
  1201. if (eat) while (cursor < command_len && BB_isspace(command[cursor]))
  1202. input_forward();
  1203. }
  1204. static void
  1205. vi_word_motion(int eat)
  1206. {
  1207. CHAR_T *command = command_ps;
  1208. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1209. while (cursor < command_len
  1210. && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
  1211. ) {
  1212. input_forward();
  1213. }
  1214. } else if (BB_ispunct(command[cursor])) {
  1215. while (cursor < command_len && BB_ispunct(command[cursor+1]))
  1216. input_forward();
  1217. }
  1218. if (cursor < command_len)
  1219. input_forward();
  1220. if (eat) {
  1221. while (cursor < command_len && BB_isspace(command[cursor]))
  1222. input_forward();
  1223. }
  1224. }
  1225. static void
  1226. vi_End_motion(void)
  1227. {
  1228. CHAR_T *command = command_ps;
  1229. input_forward();
  1230. while (cursor < command_len && BB_isspace(command[cursor]))
  1231. input_forward();
  1232. while (cursor < command_len-1 && !BB_isspace(command[cursor+1]))
  1233. input_forward();
  1234. }
  1235. static void
  1236. vi_end_motion(void)
  1237. {
  1238. CHAR_T *command = command_ps;
  1239. if (cursor >= command_len-1)
  1240. return;
  1241. input_forward();
  1242. while (cursor < command_len-1 && BB_isspace(command[cursor]))
  1243. input_forward();
  1244. if (cursor >= command_len-1)
  1245. return;
  1246. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1247. while (cursor < command_len-1
  1248. && (BB_isalnum(command[cursor+1]) || command[cursor+1] == '_')
  1249. ) {
  1250. input_forward();
  1251. }
  1252. } else if (BB_ispunct(command[cursor])) {
  1253. while (cursor < command_len-1 && BB_ispunct(command[cursor+1]))
  1254. input_forward();
  1255. }
  1256. }
  1257. static void
  1258. vi_Back_motion(void)
  1259. {
  1260. CHAR_T *command = command_ps;
  1261. while (cursor > 0 && BB_isspace(command[cursor-1]))
  1262. input_backward(1);
  1263. while (cursor > 0 && !BB_isspace(command[cursor-1]))
  1264. input_backward(1);
  1265. }
  1266. static void
  1267. vi_back_motion(void)
  1268. {
  1269. CHAR_T *command = command_ps;
  1270. if (cursor <= 0)
  1271. return;
  1272. input_backward(1);
  1273. while (cursor > 0 && BB_isspace(command[cursor]))
  1274. input_backward(1);
  1275. if (cursor <= 0)
  1276. return;
  1277. if (BB_isalnum(command[cursor]) || command[cursor] == '_') {
  1278. while (cursor > 0
  1279. && (BB_isalnum(command[cursor-1]) || command[cursor-1] == '_')
  1280. ) {
  1281. input_backward(1);
  1282. }
  1283. } else if (BB_ispunct(command[cursor])) {
  1284. while (cursor > 0 && BB_ispunct(command[cursor-1]))
  1285. input_backward(1);
  1286. }
  1287. }
  1288. #endif
  1289. /*
  1290. * read_line_input and its helpers
  1291. */
  1292. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1293. static void parse_and_put_prompt(const char *prmt_ptr)
  1294. {
  1295. cmdedit_prompt = prmt_ptr;
  1296. cmdedit_prmt_len = strlen(prmt_ptr);
  1297. put_prompt();
  1298. }
  1299. #else
  1300. static void parse_and_put_prompt(const char *prmt_ptr)
  1301. {
  1302. int prmt_len = 0;
  1303. size_t cur_prmt_len = 0;
  1304. char flg_not_length = '[';
  1305. char *prmt_mem_ptr = xzalloc(1);
  1306. char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
  1307. char cbuf[2];
  1308. char c;
  1309. char *pbuf;
  1310. cmdedit_prmt_len = 0;
  1311. if (!cwd_buf) {
  1312. cwd_buf = (char *)bb_msg_unknown;
  1313. }
  1314. cbuf[1] = '\0'; /* never changes */
  1315. while (*prmt_ptr) {
  1316. char *free_me = NULL;
  1317. pbuf = cbuf;
  1318. c = *prmt_ptr++;
  1319. if (c == '\\') {
  1320. const char *cp = prmt_ptr;
  1321. int l;
  1322. c = bb_process_escape_sequence(&prmt_ptr);
  1323. if (prmt_ptr == cp) {
  1324. if (*cp == '\0')
  1325. break;
  1326. c = *prmt_ptr++;
  1327. switch (c) {
  1328. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1329. case 'u':
  1330. pbuf = user_buf ? user_buf : (char*)"";
  1331. break;
  1332. #endif
  1333. case 'h':
  1334. pbuf = free_me = safe_gethostname();
  1335. *strchrnul(pbuf, '.') = '\0';
  1336. break;
  1337. case '$':
  1338. c = (geteuid() == 0 ? '#' : '$');
  1339. break;
  1340. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1341. case 'w':
  1342. /* /home/user[/something] -> ~[/something] */
  1343. pbuf = cwd_buf;
  1344. l = strlen(home_pwd_buf);
  1345. if (l != 0
  1346. && strncmp(home_pwd_buf, cwd_buf, l) == 0
  1347. && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
  1348. && strlen(cwd_buf + l) < PATH_MAX
  1349. ) {
  1350. pbuf = free_me = xasprintf("~%s", cwd_buf + l);
  1351. }
  1352. break;
  1353. #endif
  1354. case 'W':
  1355. pbuf = cwd_buf;
  1356. cp = strrchr(pbuf, '/');
  1357. if (cp != NULL && cp != pbuf)
  1358. pbuf += (cp-pbuf) + 1;
  1359. break;
  1360. case '!':
  1361. pbuf = free_me = xasprintf("%d", num_ok_lines);
  1362. break;
  1363. case 'e': case 'E': /* \e \E = \033 */
  1364. c = '\033';
  1365. break;
  1366. case 'x': case 'X': {
  1367. char buf2[4];
  1368. for (l = 0; l < 3;) {
  1369. unsigned h;
  1370. buf2[l++] = *prmt_ptr;
  1371. buf2[l] = '\0';
  1372. h = strtoul(buf2, &pbuf, 16);
  1373. if (h > UCHAR_MAX || (pbuf - buf2) < l) {
  1374. buf2[--l] = '\0';
  1375. break;
  1376. }
  1377. prmt_ptr++;
  1378. }
  1379. c = (char)strtoul(buf2, NULL, 16);
  1380. if (c == 0)
  1381. c = '?';
  1382. pbuf = cbuf;
  1383. break;
  1384. }
  1385. case '[': case ']':
  1386. if (c == flg_not_length) {
  1387. flg_not_length = (flg_not_length == '[' ? ']' : '[');
  1388. continue;
  1389. }
  1390. break;
  1391. } /* switch */
  1392. } /* if */
  1393. } /* if */
  1394. cbuf[0] = c;
  1395. cur_prmt_len = strlen(pbuf);
  1396. prmt_len += cur_prmt_len;
  1397. if (flg_not_length != ']')
  1398. cmdedit_prmt_len += cur_prmt_len;
  1399. prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
  1400. free(free_me);
  1401. } /* while */
  1402. if (cwd_buf != (char *)bb_msg_unknown)
  1403. free(cwd_buf);
  1404. cmdedit_prompt = prmt_mem_ptr;
  1405. put_prompt();
  1406. }
  1407. #endif
  1408. static void cmdedit_setwidth(unsigned w, int redraw_flg)
  1409. {
  1410. cmdedit_termw = w;
  1411. if (redraw_flg) {
  1412. /* new y for current cursor */
  1413. int new_y = (cursor + cmdedit_prmt_len) / w;
  1414. /* redraw */
  1415. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1416. fflush(stdout);
  1417. }
  1418. }
  1419. static void win_changed(int nsig)
  1420. {
  1421. unsigned width;
  1422. get_terminal_width_height(0, &width, NULL);
  1423. cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
  1424. if (nsig == SIGWINCH)
  1425. signal(SIGWINCH, win_changed); /* rearm ourself */
  1426. }
  1427. static int lineedit_read_key(char *read_key_buffer)
  1428. {
  1429. int64_t ic;
  1430. struct pollfd pfd;
  1431. int delay = -1;
  1432. #if ENABLE_FEATURE_ASSUME_UNICODE
  1433. char unicode_buf[MB_CUR_MAX + 1];
  1434. int unicode_idx = 0;
  1435. #endif
  1436. pfd.fd = STDIN_FILENO;
  1437. pfd.events = POLLIN;
  1438. do {
  1439. poll_again:
  1440. if (read_key_buffer[0] == 0) {
  1441. /* Wait for input. Can't just call read_key,
  1442. * it returns at once if stdin
  1443. * is in non-blocking mode. */
  1444. safe_poll(&pfd, 1, delay);
  1445. }
  1446. /* Note: read_key sets errno to 0 on success: */
  1447. ic = read_key(STDIN_FILENO, read_key_buffer);
  1448. if (ENABLE_FEATURE_EDITING_ASK_TERMINAL
  1449. && (int32_t)ic == KEYCODE_CURSOR_POS
  1450. ) {
  1451. int col = ((ic >> 32) & 0x7fff) - 1;
  1452. if (col > cmdedit_prmt_len) {
  1453. cmdedit_x += (col - cmdedit_prmt_len);
  1454. while (cmdedit_x >= cmdedit_termw) {
  1455. cmdedit_x -= cmdedit_termw;
  1456. cmdedit_y++;
  1457. }
  1458. }
  1459. goto poll_again;
  1460. }
  1461. #if ENABLE_FEATURE_ASSUME_UNICODE
  1462. {
  1463. wchar_t wc;
  1464. if ((int32_t)ic < 0) /* KEYCODE_xxx */
  1465. return ic;
  1466. unicode_buf[unicode_idx++] = ic;
  1467. unicode_buf[unicode_idx] = '\0';
  1468. if (mbstowcs(&wc, unicode_buf, 1) != 1 && unicode_idx < MB_CUR_MAX) {
  1469. delay = 50;
  1470. goto poll_again;
  1471. }
  1472. ic = wc;
  1473. }
  1474. #endif
  1475. } while (errno == EAGAIN);
  1476. return ic;
  1477. }
  1478. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1479. * configured. */
  1480. #define vi_case(caselabel) IF_FEATURE_EDITING_VI(case caselabel)
  1481. /* convert uppercase ascii to equivalent control char, for readability */
  1482. #undef CTRL
  1483. #define CTRL(a) ((a) & ~0x40)
  1484. /* maxsize must be >= 2.
  1485. * Returns:
  1486. * -1 on read errors or EOF, or on bare Ctrl-D,
  1487. * 0 on ctrl-C (the line entered is still returned in 'command'),
  1488. * >0 length of input string, including terminating '\n'
  1489. */
  1490. int FAST_FUNC read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
  1491. {
  1492. int len;
  1493. #if ENABLE_FEATURE_TAB_COMPLETION
  1494. smallint lastWasTab = FALSE;
  1495. #endif
  1496. smallint break_out = 0;
  1497. #if ENABLE_FEATURE_EDITING_VI
  1498. smallint vi_cmdmode = 0;
  1499. #endif
  1500. struct termios initial_settings;
  1501. struct termios new_settings;
  1502. char read_key_buffer[KEYCODE_BUFFER_SIZE];
  1503. INIT_S();
  1504. if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
  1505. || !(initial_settings.c_lflag & ECHO)
  1506. ) {
  1507. /* Happens when e.g. stty -echo was run before */
  1508. parse_and_put_prompt(prompt);
  1509. fflush(stdout);
  1510. if (fgets(command, maxsize, stdin) == NULL)
  1511. len = -1; /* EOF or error */
  1512. else
  1513. len = strlen(command);
  1514. DEINIT_S();
  1515. return len;
  1516. }
  1517. check_unicode_in_env();
  1518. // FIXME: audit & improve this
  1519. if (maxsize > MAX_LINELEN)
  1520. maxsize = MAX_LINELEN;
  1521. S.maxsize = maxsize;
  1522. /* With null flags, no other fields are ever used */
  1523. state = st ? st : (line_input_t*) &const_int_0;
  1524. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1525. if ((state->flags & SAVE_HISTORY) && state->hist_file)
  1526. if (state->cnt_history == 0)
  1527. load_history(state);
  1528. #endif
  1529. if (state->flags & DO_HISTORY)
  1530. state->cur_history = state->cnt_history;
  1531. /* prepare before init handlers */
  1532. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  1533. command_len = 0;
  1534. #if ENABLE_FEATURE_ASSUME_UNICODE
  1535. command_ps = xzalloc(maxsize * sizeof(command_ps[0]));
  1536. #else
  1537. command_ps = command;
  1538. command[0] = '\0';
  1539. #endif
  1540. #define command command_must_not_be_used
  1541. new_settings = initial_settings;
  1542. new_settings.c_lflag &= ~ICANON; /* unbuffered input */
  1543. /* Turn off echoing and CTRL-C, so we can trap it */
  1544. new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
  1545. /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
  1546. new_settings.c_cc[VMIN] = 1;
  1547. new_settings.c_cc[VTIME] = 0;
  1548. /* Turn off CTRL-C, so we can trap it */
  1549. #ifndef _POSIX_VDISABLE
  1550. #define _POSIX_VDISABLE '\0'
  1551. #endif
  1552. new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
  1553. tcsetattr_stdin_TCSANOW(&new_settings);
  1554. /* Now initialize things */
  1555. previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
  1556. win_changed(0); /* do initial resizing */
  1557. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1558. {
  1559. struct passwd *entry;
  1560. entry = getpwuid(geteuid());
  1561. if (entry) {
  1562. user_buf = xstrdup(entry->pw_name);
  1563. home_pwd_buf = xstrdup(entry->pw_dir);
  1564. }
  1565. }
  1566. #endif
  1567. #if 0
  1568. for (i = 0; i <= MAX_HISTORY; i++)
  1569. bb_error_msg("history[%d]:'%s'", i, state->history[i]);
  1570. bb_error_msg("cur_history:%d cnt_history:%d", state->cur_history, state->cnt_history);
  1571. #endif
  1572. /* Print out the command prompt */
  1573. parse_and_put_prompt(prompt);
  1574. read_key_buffer[0] = 0;
  1575. while (1) {
  1576. /*
  1577. * The emacs and vi modes share much of the code in the big
  1578. * command loop. Commands entered when in vi's command mode
  1579. * (aka "escape mode") get an extra bit added to distinguish
  1580. * them - this keeps them from being self-inserted. This
  1581. * clutters the big switch a bit, but keeps all the code
  1582. * in one place.
  1583. */
  1584. enum {
  1585. VI_CMDMODE_BIT = 0x40000000,
  1586. /* 0x80000000 bit flags KEYCODE_xxx */
  1587. };
  1588. int32_t ic;
  1589. fflush(NULL);
  1590. ic = lineedit_read_key(read_key_buffer);
  1591. #if ENABLE_FEATURE_EDITING_VI
  1592. newdelflag = 1;
  1593. if (vi_cmdmode) {
  1594. /* btw, since KEYCODE_xxx are all < 0, this doesn't
  1595. * change ic if it contains one of them: */
  1596. ic |= VI_CMDMODE_BIT;
  1597. }
  1598. #endif
  1599. switch (ic) {
  1600. case '\n':
  1601. case '\r':
  1602. vi_case('\n'|VI_CMDMODE_BIT:)
  1603. vi_case('\r'|VI_CMDMODE_BIT:)
  1604. /* Enter */
  1605. goto_new_line();
  1606. break_out = 1;
  1607. break;
  1608. case CTRL('A'):
  1609. vi_case('0'|VI_CMDMODE_BIT:)
  1610. /* Control-a -- Beginning of line */
  1611. input_backward(cursor);
  1612. break;
  1613. case CTRL('B'):
  1614. vi_case('h'|VI_CMDMODE_BIT:)
  1615. vi_case('\b'|VI_CMDMODE_BIT:)
  1616. vi_case('\x7f'|VI_CMDMODE_BIT:) /* DEL */
  1617. /* Control-b -- Move back one character */
  1618. input_backward(1);
  1619. break;
  1620. case CTRL('C'):
  1621. vi_case(CTRL('C')|VI_CMDMODE_BIT:)
  1622. /* Control-c -- stop gathering input */
  1623. goto_new_line();
  1624. command_len = 0;
  1625. break_out = -1; /* "do not append '\n'" */
  1626. break;
  1627. case CTRL('D'):
  1628. /* Control-d -- Delete one character, or exit
  1629. * if the len=0 and no chars to delete */
  1630. if (command_len == 0) {
  1631. errno = 0;
  1632. #if ENABLE_FEATURE_EDITING_VI
  1633. prepare_to_die:
  1634. #endif
  1635. /* to control stopped jobs */
  1636. break_out = command_len = -1;
  1637. break;
  1638. }
  1639. input_delete(0);
  1640. break;
  1641. case CTRL('E'):
  1642. vi_case('$'|VI_CMDMODE_BIT:)
  1643. /* Control-e -- End of line */
  1644. input_end();
  1645. break;
  1646. case CTRL('F'):
  1647. vi_case('l'|VI_CMDMODE_BIT:)
  1648. vi_case(' '|VI_CMDMODE_BIT:)
  1649. /* Control-f -- Move forward one character */
  1650. input_forward();
  1651. break;
  1652. case '\b':
  1653. case '\x7f': /* DEL */
  1654. /* Control-h and DEL */
  1655. input_backspace();
  1656. break;
  1657. #if ENABLE_FEATURE_TAB_COMPLETION
  1658. case '\t':
  1659. input_tab(&lastWasTab);
  1660. break;
  1661. #endif
  1662. case CTRL('K'):
  1663. /* Control-k -- clear to end of line */
  1664. command_ps[cursor] = BB_NUL;
  1665. command_len = cursor;
  1666. printf("\033[J");
  1667. break;
  1668. case CTRL('L'):
  1669. vi_case(CTRL('L')|VI_CMDMODE_BIT:)
  1670. /* Control-l -- clear screen */
  1671. printf("\033[H");
  1672. redraw(0, command_len - cursor);
  1673. break;
  1674. #if MAX_HISTORY > 0
  1675. case CTRL('N'):
  1676. vi_case(CTRL('N')|VI_CMDMODE_BIT:)
  1677. vi_case('j'|VI_CMDMODE_BIT:)
  1678. /* Control-n -- Get next command in history */
  1679. if (get_next_history())
  1680. goto rewrite_line;
  1681. break;
  1682. case CTRL('P'):
  1683. vi_case(CTRL('P')|VI_CMDMODE_BIT:)
  1684. vi_case('k'|VI_CMDMODE_BIT:)
  1685. /* Control-p -- Get previous command from history */
  1686. if (get_previous_history())
  1687. goto rewrite_line;
  1688. break;
  1689. #endif
  1690. case CTRL('U'):
  1691. vi_case(CTRL('U')|VI_CMDMODE_BIT:)
  1692. /* Control-U -- Clear line before cursor */
  1693. if (cursor) {
  1694. command_len -= cursor;
  1695. memmove(command_ps, command_ps + cursor,
  1696. (command_len + 1) * sizeof(command_ps[0]));
  1697. redraw(cmdedit_y, command_len);
  1698. }
  1699. break;
  1700. case CTRL('W'):
  1701. vi_case(CTRL('W')|VI_CMDMODE_BIT:)
  1702. /* Control-W -- Remove the last word */
  1703. while (cursor > 0 && BB_isspace(command_ps[cursor-1]))
  1704. input_backspace();
  1705. while (cursor > 0 && !BB_isspace(command_ps[cursor-1]))
  1706. input_backspace();
  1707. break;
  1708. #if ENABLE_FEATURE_EDITING_VI
  1709. case 'i'|VI_CMDMODE_BIT:
  1710. vi_cmdmode = 0;
  1711. break;
  1712. case 'I'|VI_CMDMODE_BIT:
  1713. input_backward(cursor);
  1714. vi_cmdmode = 0;
  1715. break;
  1716. case 'a'|VI_CMDMODE_BIT:
  1717. input_forward();
  1718. vi_cmdmode = 0;
  1719. break;
  1720. case 'A'|VI_CMDMODE_BIT:
  1721. input_end();
  1722. vi_cmdmode = 0;
  1723. break;
  1724. case 'x'|VI_CMDMODE_BIT:
  1725. input_delete(1);
  1726. break;
  1727. case 'X'|VI_CMDMODE_BIT:
  1728. if (cursor > 0) {
  1729. input_backward(1);
  1730. input_delete(1);
  1731. }
  1732. break;
  1733. case 'W'|VI_CMDMODE_BIT:
  1734. vi_Word_motion(1);
  1735. break;
  1736. case 'w'|VI_CMDMODE_BIT:
  1737. vi_word_motion(1);
  1738. break;
  1739. case 'E'|VI_CMDMODE_BIT:
  1740. vi_End_motion();
  1741. break;
  1742. case 'e'|VI_CMDMODE_BIT:
  1743. vi_end_motion();
  1744. break;
  1745. case 'B'|VI_CMDMODE_BIT:
  1746. vi_Back_motion();
  1747. break;
  1748. case 'b'|VI_CMDMODE_BIT:
  1749. vi_back_motion();
  1750. break;
  1751. case 'C'|VI_CMDMODE_BIT:
  1752. vi_cmdmode = 0;
  1753. /* fall through */
  1754. case 'D'|VI_CMDMODE_BIT:
  1755. goto clear_to_eol;
  1756. case 'c'|VI_CMDMODE_BIT:
  1757. vi_cmdmode = 0;
  1758. /* fall through */
  1759. case 'd'|VI_CMDMODE_BIT: {
  1760. int nc, sc;
  1761. int prev_ic;
  1762. sc = cursor;
  1763. prev_ic = ic;
  1764. ic = lineedit_read_key(read_key_buffer);
  1765. if (errno) /* error */
  1766. goto prepare_to_die;
  1767. if ((ic | VI_CMDMODE_BIT) == prev_ic) {
  1768. /* "cc", "dd" */
  1769. input_backward(cursor);
  1770. goto clear_to_eol;
  1771. break;
  1772. }
  1773. switch (ic) {
  1774. case 'w':
  1775. case 'W':
  1776. case 'e':
  1777. case 'E':
  1778. switch (ic) {
  1779. case 'w': /* "dw", "cw" */
  1780. vi_word_motion(vi_cmdmode);
  1781. break;
  1782. case 'W': /* 'dW', 'cW' */
  1783. vi_Word_motion(vi_cmdmode);
  1784. break;
  1785. case 'e': /* 'de', 'ce' */
  1786. vi_end_motion();
  1787. input_forward();
  1788. break;
  1789. case 'E': /* 'dE', 'cE' */
  1790. vi_End_motion();
  1791. input_forward();
  1792. break;
  1793. }
  1794. nc = cursor;
  1795. input_backward(cursor - sc);
  1796. while (nc-- > cursor)
  1797. input_delete(1);
  1798. break;
  1799. case 'b': /* "db", "cb" */
  1800. case 'B': /* implemented as B */
  1801. if (ic == 'b')
  1802. vi_back_motion();
  1803. else
  1804. vi_Back_motion();
  1805. while (sc-- > cursor)
  1806. input_delete(1);
  1807. break;
  1808. case ' ': /* "d ", "c " */
  1809. input_delete(1);
  1810. break;
  1811. case '$': /* "d$", "c$" */
  1812. clear_to_eol:
  1813. while (cursor < command_len)
  1814. input_delete(1);
  1815. break;
  1816. }
  1817. break;
  1818. }
  1819. case 'p'|VI_CMDMODE_BIT:
  1820. input_forward();
  1821. /* fallthrough */
  1822. case 'P'|VI_CMDMODE_BIT:
  1823. put();
  1824. break;
  1825. case 'r'|VI_CMDMODE_BIT:
  1826. ic = lineedit_read_key(read_key_buffer);
  1827. if (errno) /* error */
  1828. goto prepare_to_die;
  1829. if (ic < ' ' || ic > 255) {
  1830. beep();
  1831. } else {
  1832. command_ps[cursor] = ic;
  1833. bb_putchar(ic);
  1834. bb_putchar('\b');
  1835. }
  1836. break;
  1837. case '\x1b': /* ESC */
  1838. if (state->flags & VI_MODE) {
  1839. /* insert mode --> command mode */
  1840. vi_cmdmode = 1;
  1841. input_backward(1);
  1842. }
  1843. break;
  1844. #endif /* FEATURE_COMMAND_EDITING_VI */
  1845. #if MAX_HISTORY > 0
  1846. case KEYCODE_UP:
  1847. if (get_previous_history())
  1848. goto rewrite_line;
  1849. beep();
  1850. break;
  1851. case KEYCODE_DOWN:
  1852. if (!get_next_history())
  1853. break;
  1854. rewrite_line:
  1855. /* Rewrite the line with the selected history item */
  1856. /* change command */
  1857. command_len = load_string(state->history[state->cur_history] ? : "", maxsize);
  1858. /* redraw and go to eol (bol, in vi) */
  1859. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  1860. break;
  1861. #endif
  1862. case KEYCODE_RIGHT:
  1863. input_forward();
  1864. break;
  1865. case KEYCODE_LEFT:
  1866. input_backward(1);
  1867. break;
  1868. case KEYCODE_DELETE:
  1869. input_delete(0);
  1870. break;
  1871. case KEYCODE_HOME:
  1872. input_backward(cursor);
  1873. break;
  1874. case KEYCODE_END:
  1875. input_end();
  1876. break;
  1877. default:
  1878. // /* Control-V -- force insert of next char */
  1879. // if (c == CTRL('V')) {
  1880. // if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1881. // goto prepare_to_die;
  1882. // if (c == 0) {
  1883. // beep();
  1884. // break;
  1885. // }
  1886. // }
  1887. if (ic < ' '
  1888. || (!ENABLE_FEATURE_ASSUME_UNICODE && ic >= 256)
  1889. || (ENABLE_FEATURE_ASSUME_UNICODE && ic >= VI_CMDMODE_BIT)
  1890. ) {
  1891. /* If VI_CMDMODE_BIT is set, ic is >= 256
  1892. * and command mode ignores unexpected chars.
  1893. * Otherwise, we are here if ic is a
  1894. * control char or an unhandled ESC sequence,
  1895. * which is also ignored.
  1896. */
  1897. break;
  1898. }
  1899. if ((int)command_len >= (maxsize - 2)) {
  1900. /* Not enough space for the char and EOL */
  1901. break;
  1902. }
  1903. command_len++;
  1904. if (cursor == (command_len - 1)) {
  1905. /* We are at the end, append */
  1906. command_ps[cursor] = ic;
  1907. command_ps[cursor + 1] = BB_NUL;
  1908. cmdedit_set_out_char(' ');
  1909. } else {
  1910. /* In the middle, insert */
  1911. int sc = cursor;
  1912. memmove(command_ps + sc + 1, command_ps + sc,
  1913. (command_len - sc) * sizeof(command_ps[0]));
  1914. command_ps[sc] = ic;
  1915. sc++;
  1916. /* rewrite from cursor */
  1917. input_end();
  1918. /* to prev x pos + 1 */
  1919. input_backward(cursor - sc);
  1920. }
  1921. break;
  1922. } /* switch (input_key) */
  1923. if (break_out)
  1924. break;
  1925. #if ENABLE_FEATURE_TAB_COMPLETION
  1926. ic &= ~VI_CMDMODE_BIT;
  1927. if (ic != '\t')
  1928. lastWasTab = FALSE;
  1929. #endif
  1930. } /* while (1) */
  1931. /* Stop bug catching using "command_must_not_be_used" trick */
  1932. #undef command
  1933. #if ENABLE_FEATURE_ASSUME_UNICODE
  1934. command_len = save_string(command, maxsize - 1);
  1935. free(command_ps);
  1936. #endif
  1937. if (command_len > 0)
  1938. remember_in_history(command);
  1939. if (break_out > 0) {
  1940. command[command_len++] = '\n';
  1941. command[command_len] = '\0';
  1942. }
  1943. #if ENABLE_FEATURE_TAB_COMPLETION
  1944. free_tab_completion_data();
  1945. #endif
  1946. /* restore initial_settings */
  1947. tcsetattr_stdin_TCSANOW(&initial_settings);
  1948. /* restore SIGWINCH handler */
  1949. signal(SIGWINCH, previous_SIGWINCH_handler);
  1950. fflush(stdout);
  1951. len = command_len;
  1952. DEINIT_S();
  1953. return len; /* can't return command_len, DEINIT_S() destroys it */
  1954. }
  1955. #else
  1956. #undef read_line_input
  1957. int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
  1958. {
  1959. fputs(prompt, stdout);
  1960. fflush(stdout);
  1961. fgets(command, maxsize, stdin);
  1962. return strlen(command);
  1963. }
  1964. #endif /* FEATURE_EDITING */
  1965. /*
  1966. * Testing
  1967. */
  1968. #ifdef TEST
  1969. #include <locale.h>
  1970. const char *applet_name = "debug stuff usage";
  1971. int main(int argc, char **argv)
  1972. {
  1973. char buff[MAX_LINELEN];
  1974. char *prompt =
  1975. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1976. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  1977. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  1978. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
  1979. #else
  1980. "% ";
  1981. #endif
  1982. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  1983. setlocale(LC_ALL, "");
  1984. #endif
  1985. while (1) {
  1986. int l;
  1987. l = read_line_input(prompt, buff);
  1988. if (l <= 0 || buff[l-1] != '\n')
  1989. break;
  1990. buff[l-1] = 0;
  1991. printf("*** read_line_input() returned line =%s=\n", buff);
  1992. }
  1993. printf("*** read_line_input() detect ^D\n");
  1994. return 0;
  1995. }
  1996. #endif /* TEST */