lineedit.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  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. Small bugs (simple effect):
  24. - not true viewing if terminal size (x*y symbols) less
  25. size (prompt + editor's line + 2 symbols)
  26. - not true viewing if length prompt less terminal width
  27. */
  28. #include "libbb.h"
  29. /* FIXME: obsolete CONFIG item? */
  30. #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
  31. #ifdef TEST
  32. #define ENABLE_FEATURE_EDITING 0
  33. #define ENABLE_FEATURE_TAB_COMPLETION 0
  34. #define ENABLE_FEATURE_USERNAME_COMPLETION 0
  35. #define ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT 0
  36. #endif /* TEST */
  37. /* Entire file (except TESTing part) sits inside this #if */
  38. #if ENABLE_FEATURE_EDITING
  39. #if ENABLE_LOCALE_SUPPORT
  40. #define Isprint(c) isprint(c)
  41. #else
  42. #define Isprint(c) ((c) >= ' ' && (c) != ((unsigned char)'\233'))
  43. #endif
  44. #define ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR \
  45. (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT)
  46. #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...)
  47. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  48. #undef USE_FEATURE_GETUSERNAME_AND_HOMEDIR
  49. #define USE_FEATURE_GETUSERNAME_AND_HOMEDIR(...) __VA_ARGS__
  50. #endif
  51. enum {
  52. /* We use int16_t for positions, need to limit line len */
  53. MAX_LINELEN = CONFIG_FEATURE_EDITING_MAX_LEN < 0x7ff0
  54. ? CONFIG_FEATURE_EDITING_MAX_LEN
  55. : 0x7ff0
  56. };
  57. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  58. static const char null_str[] ALIGN1 = "";
  59. #endif
  60. /* We try to minimize both static and stack usage. */
  61. struct statics {
  62. line_input_t *state;
  63. volatile unsigned cmdedit_termw; /* = 80; */ /* actual terminal width */
  64. sighandler_t previous_SIGWINCH_handler;
  65. int cmdedit_x; /* real x terminal position */
  66. int cmdedit_y; /* pseudoreal y terminal position */
  67. int cmdedit_prmt_len; /* length of prompt (without colors etc) */
  68. unsigned cursor;
  69. unsigned command_len;
  70. char *command_ps;
  71. const char *cmdedit_prompt;
  72. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  73. int num_ok_lines; /* = 1; */
  74. #endif
  75. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  76. char *user_buf;
  77. char *home_pwd_buf; /* = (char*)null_str; */
  78. #endif
  79. #if ENABLE_FEATURE_TAB_COMPLETION
  80. char **matches;
  81. unsigned num_matches;
  82. #endif
  83. #if ENABLE_FEATURE_EDITING_VI
  84. #define DELBUFSIZ 128
  85. char *delptr;
  86. smallint newdelflag; /* whether delbuf should be reused yet */
  87. char delbuf[DELBUFSIZ]; /* a place to store deleted characters */
  88. #endif
  89. /* Formerly these were big buffers on stack: */
  90. #if ENABLE_FEATURE_TAB_COMPLETION
  91. char exe_n_cwd_tab_completion__dirbuf[MAX_LINELEN];
  92. char input_tab__matchBuf[MAX_LINELEN];
  93. int16_t find_match__int_buf[MAX_LINELEN + 1]; /* need to have 9 bits at least */
  94. int16_t find_match__pos_buf[MAX_LINELEN + 1];
  95. #endif
  96. };
  97. /* Make it reside in writable memory, yet make compiler understand
  98. * that it is not going to change. */
  99. static struct statics *const ptr_to_statics __attribute__ ((section (".data")));
  100. #define S (*ptr_to_statics)
  101. #define state (S.state )
  102. #define cmdedit_termw (S.cmdedit_termw )
  103. #define previous_SIGWINCH_handler (S.previous_SIGWINCH_handler)
  104. #define cmdedit_x (S.cmdedit_x )
  105. #define cmdedit_y (S.cmdedit_y )
  106. #define cmdedit_prmt_len (S.cmdedit_prmt_len)
  107. #define cursor (S.cursor )
  108. #define command_len (S.command_len )
  109. #define command_ps (S.command_ps )
  110. #define cmdedit_prompt (S.cmdedit_prompt )
  111. #define num_ok_lines (S.num_ok_lines )
  112. #define user_buf (S.user_buf )
  113. #define home_pwd_buf (S.home_pwd_buf )
  114. #define matches (S.matches )
  115. #define num_matches (S.num_matches )
  116. #define delptr (S.delptr )
  117. #define newdelflag (S.newdelflag )
  118. #define delbuf (S.delbuf )
  119. #define INIT_S() do { \
  120. (*(struct statics**)&ptr_to_statics) = xzalloc(sizeof(S)); \
  121. barrier(); \
  122. cmdedit_termw = 80; \
  123. USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines = 1;) \
  124. USE_FEATURE_GETUSERNAME_AND_HOMEDIR(home_pwd_buf = (char*)null_str;) \
  125. } while (0)
  126. static void deinit_S(void)
  127. {
  128. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  129. /* This one is allocated only if FANCY_PROMPT is on
  130. * (otherwise it points to verbatim prompt (NOT malloced) */
  131. free((char*)cmdedit_prompt);
  132. #endif
  133. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  134. free(user_buf);
  135. if (home_pwd_buf != null_str)
  136. free(home_pwd_buf);
  137. #endif
  138. free(ptr_to_statics);
  139. }
  140. #define DEINIT_S() deinit_S()
  141. /* Put 'command_ps[cursor]', cursor++.
  142. * Advance cursor on screen. If we reached right margin, scroll text up
  143. * and remove terminal margin effect by printing 'next_char' */
  144. static void cmdedit_set_out_char(int next_char)
  145. {
  146. int c = (unsigned char)command_ps[cursor];
  147. if (c == '\0') {
  148. /* erase character after end of input string */
  149. c = ' ';
  150. }
  151. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  152. /* Display non-printable characters in reverse */
  153. if (!Isprint(c)) {
  154. if (c >= 128)
  155. c -= 128;
  156. if (c < ' ')
  157. c += '@';
  158. if (c == 127)
  159. c = '?';
  160. printf("\033[7m%c\033[0m", c);
  161. } else
  162. #endif
  163. {
  164. bb_putchar(c);
  165. }
  166. if (++cmdedit_x >= cmdedit_termw) {
  167. /* terminal is scrolled down */
  168. cmdedit_y++;
  169. cmdedit_x = 0;
  170. /* destroy "(auto)margin" */
  171. bb_putchar(next_char);
  172. bb_putchar('\b');
  173. }
  174. // Huh? What if command_ps[cursor] == '\0' (we are at the end already?)
  175. cursor++;
  176. }
  177. /* Move to end of line (by printing all chars till the end) */
  178. static void input_end(void)
  179. {
  180. while (cursor < command_len)
  181. cmdedit_set_out_char(' ');
  182. }
  183. /* Go to the next line */
  184. static void goto_new_line(void)
  185. {
  186. input_end();
  187. if (cmdedit_x)
  188. bb_putchar('\n');
  189. }
  190. static void out1str(const char *s)
  191. {
  192. if (s)
  193. fputs(s, stdout);
  194. }
  195. static void beep(void)
  196. {
  197. bb_putchar('\007');
  198. }
  199. /* Move back one character */
  200. /* (optimized for slow terminals) */
  201. static void input_backward(unsigned num)
  202. {
  203. int count_y;
  204. if (num > cursor)
  205. num = cursor;
  206. if (!num)
  207. return;
  208. cursor -= num;
  209. if (cmdedit_x >= num) {
  210. cmdedit_x -= num;
  211. if (num <= 4) {
  212. /* This is longer by 5 bytes on x86.
  213. * Also gets mysteriously
  214. * miscompiled for some ARM users.
  215. * printf(("\b\b\b\b" + 4) - num);
  216. * return;
  217. */
  218. do {
  219. bb_putchar('\b');
  220. } while (--num);
  221. return;
  222. }
  223. printf("\033[%uD", num);
  224. return;
  225. }
  226. /* Need to go one or more lines up */
  227. num -= cmdedit_x;
  228. count_y = 1 + (num / cmdedit_termw);
  229. cmdedit_y -= count_y;
  230. cmdedit_x = cmdedit_termw * count_y - num;
  231. /* go to 1st column; go up; go to correct column */
  232. printf("\r" "\033[%dA" "\033[%dC", count_y, cmdedit_x);
  233. }
  234. static void put_prompt(void)
  235. {
  236. out1str(cmdedit_prompt);
  237. cmdedit_x = cmdedit_prmt_len;
  238. cursor = 0;
  239. // Huh? what if cmdedit_prmt_len >= width?
  240. cmdedit_y = 0; /* new quasireal y */
  241. }
  242. /* draw prompt, editor line, and clear tail */
  243. static void redraw(int y, int back_cursor)
  244. {
  245. if (y > 0) /* up to start y */
  246. printf("\033[%dA", y);
  247. bb_putchar('\r');
  248. put_prompt();
  249. input_end(); /* rewrite */
  250. printf("\033[J"); /* erase after cursor */
  251. input_backward(back_cursor);
  252. }
  253. /* Delete the char in front of the cursor, optionally saving it
  254. * for later putback */
  255. #if !ENABLE_FEATURE_EDITING_VI
  256. static void input_delete(void)
  257. #define input_delete(save) input_delete()
  258. #else
  259. static void input_delete(int save)
  260. #endif
  261. {
  262. int j = cursor;
  263. if (j == command_len)
  264. return;
  265. #if ENABLE_FEATURE_EDITING_VI
  266. if (save) {
  267. if (newdelflag) {
  268. delptr = delbuf;
  269. newdelflag = 0;
  270. }
  271. if ((delptr - delbuf) < DELBUFSIZ)
  272. *delptr++ = command_ps[j];
  273. }
  274. #endif
  275. strcpy(command_ps + j, command_ps + j + 1);
  276. command_len--;
  277. input_end(); /* rewrite new line */
  278. cmdedit_set_out_char(' '); /* erase char */
  279. input_backward(cursor - j); /* back to old pos cursor */
  280. }
  281. #if ENABLE_FEATURE_EDITING_VI
  282. static void put(void)
  283. {
  284. int ocursor;
  285. int j = delptr - delbuf;
  286. if (j == 0)
  287. return;
  288. ocursor = cursor;
  289. /* open hole and then fill it */
  290. memmove(command_ps + cursor + j, command_ps + cursor, command_len - cursor + 1);
  291. strncpy(command_ps + cursor, delbuf, j);
  292. command_len += j;
  293. input_end(); /* rewrite new line */
  294. input_backward(cursor - ocursor - j + 1); /* at end of new text */
  295. }
  296. #endif
  297. /* Delete the char in back of the cursor */
  298. static void input_backspace(void)
  299. {
  300. if (cursor > 0) {
  301. input_backward(1);
  302. input_delete(0);
  303. }
  304. }
  305. /* Move forward one character */
  306. static void input_forward(void)
  307. {
  308. if (cursor < command_len)
  309. cmdedit_set_out_char(command_ps[cursor + 1]);
  310. }
  311. #if ENABLE_FEATURE_TAB_COMPLETION
  312. static void free_tab_completion_data(void)
  313. {
  314. if (matches) {
  315. while (num_matches)
  316. free(matches[--num_matches]);
  317. free(matches);
  318. matches = NULL;
  319. }
  320. }
  321. static void add_match(char *matched)
  322. {
  323. int nm = num_matches;
  324. int nm1 = nm + 1;
  325. matches = xrealloc(matches, nm1 * sizeof(char *));
  326. matches[nm] = matched;
  327. num_matches++;
  328. }
  329. #if ENABLE_FEATURE_USERNAME_COMPLETION
  330. static void username_tab_completion(char *ud, char *with_shash_flg)
  331. {
  332. struct passwd *entry;
  333. int userlen;
  334. ud++; /* ~user/... to user/... */
  335. userlen = strlen(ud);
  336. if (with_shash_flg) { /* "~/..." or "~user/..." */
  337. char *sav_ud = ud - 1;
  338. char *home = NULL;
  339. if (*ud == '/') { /* "~/..." */
  340. home = home_pwd_buf;
  341. } else {
  342. /* "~user/..." */
  343. char *temp;
  344. temp = strchr(ud, '/');
  345. *temp = '\0'; /* ~user\0 */
  346. entry = getpwnam(ud);
  347. *temp = '/'; /* restore ~user/... */
  348. ud = temp;
  349. if (entry)
  350. home = entry->pw_dir;
  351. }
  352. if (home) {
  353. if ((userlen + strlen(home) + 1) < MAX_LINELEN) {
  354. /* /home/user/... */
  355. sprintf(sav_ud, "%s%s", home, ud);
  356. }
  357. }
  358. } else {
  359. /* "~[^/]*" */
  360. /* Using _r function to avoid pulling in static buffers */
  361. char line_buff[256];
  362. struct passwd pwd;
  363. struct passwd *result;
  364. setpwent();
  365. while (!getpwent_r(&pwd, line_buff, sizeof(line_buff), &result)) {
  366. /* Null usernames should result in all users as possible completions. */
  367. if (/*!userlen || */ strncmp(ud, pwd.pw_name, userlen) == 0) {
  368. add_match(xasprintf("~%s/", pwd.pw_name));
  369. }
  370. }
  371. endpwent();
  372. }
  373. }
  374. #endif /* FEATURE_COMMAND_USERNAME_COMPLETION */
  375. enum {
  376. FIND_EXE_ONLY = 0,
  377. FIND_DIR_ONLY = 1,
  378. FIND_FILE_ONLY = 2,
  379. };
  380. static int path_parse(char ***p, int flags)
  381. {
  382. int npth;
  383. const char *pth;
  384. char *tmp;
  385. char **res;
  386. /* if not setenv PATH variable, to search cur dir "." */
  387. if (flags != FIND_EXE_ONLY)
  388. return 1;
  389. if (state->flags & WITH_PATH_LOOKUP)
  390. pth = state->path_lookup;
  391. else
  392. pth = getenv("PATH");
  393. /* PATH=<empty> or PATH=:<empty> */
  394. if (!pth || !pth[0] || LONE_CHAR(pth, ':'))
  395. return 1;
  396. tmp = (char*)pth;
  397. npth = 1; /* path component count */
  398. while (1) {
  399. tmp = strchr(tmp, ':');
  400. if (!tmp)
  401. break;
  402. if (*++tmp == '\0')
  403. break; /* :<empty> */
  404. npth++;
  405. }
  406. res = xmalloc(npth * sizeof(char*));
  407. res[0] = tmp = xstrdup(pth);
  408. npth = 1;
  409. while (1) {
  410. tmp = strchr(tmp, ':');
  411. if (!tmp)
  412. break;
  413. *tmp++ = '\0'; /* ':' -> '\0' */
  414. if (*tmp == '\0')
  415. break; /* :<empty> */
  416. res[npth++] = tmp;
  417. }
  418. *p = res;
  419. return npth;
  420. }
  421. static void exe_n_cwd_tab_completion(char *command, int type)
  422. {
  423. DIR *dir;
  424. struct dirent *next;
  425. struct stat st;
  426. char *path1[1];
  427. char **paths = path1;
  428. int npaths;
  429. int i;
  430. char *found;
  431. char *pfind = strrchr(command, '/');
  432. /* char dirbuf[MAX_LINELEN]; */
  433. #define dirbuf (S.exe_n_cwd_tab_completion__dirbuf)
  434. npaths = 1;
  435. path1[0] = (char*)".";
  436. if (pfind == NULL) {
  437. /* no dir, if flags==EXE_ONLY - get paths, else "." */
  438. npaths = path_parse(&paths, type);
  439. pfind = command;
  440. } else {
  441. /* dirbuf = ".../.../.../" */
  442. safe_strncpy(dirbuf, command, (pfind - command) + 2);
  443. #if ENABLE_FEATURE_USERNAME_COMPLETION
  444. if (dirbuf[0] == '~') /* ~/... or ~user/... */
  445. username_tab_completion(dirbuf, dirbuf);
  446. #endif
  447. paths[0] = dirbuf;
  448. /* point to 'l' in "..../last_component" */
  449. pfind++;
  450. }
  451. for (i = 0; i < npaths; i++) {
  452. dir = opendir(paths[i]);
  453. if (!dir)
  454. continue; /* don't print an error */
  455. while ((next = readdir(dir)) != NULL) {
  456. int len1;
  457. const char *str_found = next->d_name;
  458. /* matched? */
  459. if (strncmp(str_found, pfind, strlen(pfind)))
  460. continue;
  461. /* not see .name without .match */
  462. if (*str_found == '.' && *pfind == '\0') {
  463. if (NOT_LONE_CHAR(paths[i], '/') || str_found[1])
  464. continue;
  465. str_found = ""; /* only "/" */
  466. }
  467. found = concat_path_file(paths[i], str_found);
  468. /* hmm, remove in progress? */
  469. /* NB: stat() first so that we see is it a directory;
  470. * but if that fails, use lstat() so that
  471. * we still match dangling links */
  472. if (stat(found, &st) && lstat(found, &st))
  473. goto cont;
  474. /* find with dirs? */
  475. if (paths[i] != dirbuf)
  476. strcpy(found, next->d_name); /* only name */
  477. len1 = strlen(found);
  478. found = xrealloc(found, len1 + 2);
  479. found[len1] = '\0';
  480. found[len1+1] = '\0';
  481. if (S_ISDIR(st.st_mode)) {
  482. /* name is a directory */
  483. if (found[len1-1] != '/') {
  484. found[len1] = '/';
  485. }
  486. } else {
  487. /* not put found file if search only dirs for cd */
  488. if (type == FIND_DIR_ONLY)
  489. goto cont;
  490. }
  491. /* Add it to the list */
  492. add_match(found);
  493. continue;
  494. cont:
  495. free(found);
  496. }
  497. closedir(dir);
  498. }
  499. if (paths != path1) {
  500. free(paths[0]); /* allocated memory is only in first member */
  501. free(paths);
  502. }
  503. #undef dirbuf
  504. }
  505. #define QUOT (UCHAR_MAX+1)
  506. #define collapse_pos(is, in) do { \
  507. memmove(int_buf+(is), int_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
  508. memmove(pos_buf+(is), pos_buf+(in), (MAX_LINELEN+1-(is)-(in)) * sizeof(pos_buf[0])); \
  509. } while (0)
  510. static int find_match(char *matchBuf, int *len_with_quotes)
  511. {
  512. int i, j;
  513. int command_mode;
  514. int c, c2;
  515. /* int16_t int_buf[MAX_LINELEN + 1]; */
  516. /* int16_t pos_buf[MAX_LINELEN + 1]; */
  517. #define int_buf (S.find_match__int_buf)
  518. #define pos_buf (S.find_match__pos_buf)
  519. /* set to integer dimension characters and own positions */
  520. for (i = 0;; i++) {
  521. int_buf[i] = (unsigned char)matchBuf[i];
  522. if (int_buf[i] == 0) {
  523. pos_buf[i] = -1; /* indicator end line */
  524. break;
  525. }
  526. pos_buf[i] = i;
  527. }
  528. /* mask \+symbol and convert '\t' to ' ' */
  529. for (i = j = 0; matchBuf[i]; i++, j++)
  530. if (matchBuf[i] == '\\') {
  531. collapse_pos(j, j + 1);
  532. int_buf[j] |= QUOT;
  533. i++;
  534. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  535. if (matchBuf[i] == '\t') /* algorithm equivalent */
  536. int_buf[j] = ' ' | QUOT;
  537. #endif
  538. }
  539. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  540. else if (matchBuf[i] == '\t')
  541. int_buf[j] = ' ';
  542. #endif
  543. /* mask "symbols" or 'symbols' */
  544. c2 = 0;
  545. for (i = 0; int_buf[i]; i++) {
  546. c = int_buf[i];
  547. if (c == '\'' || c == '"') {
  548. if (c2 == 0)
  549. c2 = c;
  550. else {
  551. if (c == c2)
  552. c2 = 0;
  553. else
  554. int_buf[i] |= QUOT;
  555. }
  556. } else if (c2 != 0 && c != '$')
  557. int_buf[i] |= QUOT;
  558. }
  559. /* skip commands with arguments if line has commands delimiters */
  560. /* ';' ';;' '&' '|' '&&' '||' but `>&' `<&' `>|' */
  561. for (i = 0; int_buf[i]; i++) {
  562. c = int_buf[i];
  563. c2 = int_buf[i + 1];
  564. j = i ? int_buf[i - 1] : -1;
  565. command_mode = 0;
  566. if (c == ';' || c == '&' || c == '|') {
  567. command_mode = 1 + (c == c2);
  568. if (c == '&') {
  569. if (j == '>' || j == '<')
  570. command_mode = 0;
  571. } else if (c == '|' && j == '>')
  572. command_mode = 0;
  573. }
  574. if (command_mode) {
  575. collapse_pos(0, i + command_mode);
  576. i = -1; /* hack incremet */
  577. }
  578. }
  579. /* collapse `command...` */
  580. for (i = 0; int_buf[i]; i++)
  581. if (int_buf[i] == '`') {
  582. for (j = i + 1; int_buf[j]; j++)
  583. if (int_buf[j] == '`') {
  584. collapse_pos(i, j + 1);
  585. j = 0;
  586. break;
  587. }
  588. if (j) {
  589. /* not found close ` - command mode, collapse all previous */
  590. collapse_pos(0, i + 1);
  591. break;
  592. } else
  593. i--; /* hack incremet */
  594. }
  595. /* collapse (command...(command...)...) or {command...{command...}...} */
  596. c = 0; /* "recursive" level */
  597. c2 = 0;
  598. for (i = 0; int_buf[i]; i++)
  599. if (int_buf[i] == '(' || int_buf[i] == '{') {
  600. if (int_buf[i] == '(')
  601. c++;
  602. else
  603. c2++;
  604. collapse_pos(0, i + 1);
  605. i = -1; /* hack incremet */
  606. }
  607. for (i = 0; pos_buf[i] >= 0 && (c > 0 || c2 > 0); i++)
  608. if ((int_buf[i] == ')' && c > 0) || (int_buf[i] == '}' && c2 > 0)) {
  609. if (int_buf[i] == ')')
  610. c--;
  611. else
  612. c2--;
  613. collapse_pos(0, i + 1);
  614. i = -1; /* hack incremet */
  615. }
  616. /* skip first not quote space */
  617. for (i = 0; int_buf[i]; i++)
  618. if (int_buf[i] != ' ')
  619. break;
  620. if (i)
  621. collapse_pos(0, i);
  622. /* set find mode for completion */
  623. command_mode = FIND_EXE_ONLY;
  624. for (i = 0; int_buf[i]; i++)
  625. if (int_buf[i] == ' ' || int_buf[i] == '<' || int_buf[i] == '>') {
  626. if (int_buf[i] == ' ' && command_mode == FIND_EXE_ONLY
  627. && matchBuf[pos_buf[0]] == 'c'
  628. && matchBuf[pos_buf[1]] == 'd'
  629. ) {
  630. command_mode = FIND_DIR_ONLY;
  631. } else {
  632. command_mode = FIND_FILE_ONLY;
  633. break;
  634. }
  635. }
  636. for (i = 0; int_buf[i]; i++)
  637. /* "strlen" */;
  638. /* find last word */
  639. for (--i; i >= 0; i--) {
  640. c = int_buf[i];
  641. if (c == ' ' || c == '<' || c == '>' || c == '|' || c == '&') {
  642. collapse_pos(0, i + 1);
  643. break;
  644. }
  645. }
  646. /* skip first not quoted '\'' or '"' */
  647. for (i = 0; int_buf[i] == '\'' || int_buf[i] == '"'; i++)
  648. /*skip*/;
  649. /* collapse quote or unquote // or /~ */
  650. while ((int_buf[i] & ~QUOT) == '/'
  651. && ((int_buf[i+1] & ~QUOT) == '/' || (int_buf[i+1] & ~QUOT) == '~')
  652. ) {
  653. i++;
  654. }
  655. /* set only match and destroy quotes */
  656. j = 0;
  657. for (c = 0; pos_buf[i] >= 0; i++) {
  658. matchBuf[c++] = matchBuf[pos_buf[i]];
  659. j = pos_buf[i] + 1;
  660. }
  661. matchBuf[c] = '\0';
  662. /* old length matchBuf with quotes symbols */
  663. *len_with_quotes = j ? j - pos_buf[0] : 0;
  664. return command_mode;
  665. #undef int_buf
  666. #undef pos_buf
  667. }
  668. /*
  669. * display by column (original idea from ls applet,
  670. * very optimized by me :)
  671. */
  672. static void showfiles(void)
  673. {
  674. int ncols, row;
  675. int column_width = 0;
  676. int nfiles = num_matches;
  677. int nrows = nfiles;
  678. int l;
  679. /* find the longest file name- use that as the column width */
  680. for (row = 0; row < nrows; row++) {
  681. l = strlen(matches[row]);
  682. if (column_width < l)
  683. column_width = l;
  684. }
  685. column_width += 2; /* min space for columns */
  686. ncols = cmdedit_termw / column_width;
  687. if (ncols > 1) {
  688. nrows /= ncols;
  689. if (nfiles % ncols)
  690. nrows++; /* round up fractionals */
  691. } else {
  692. ncols = 1;
  693. }
  694. for (row = 0; row < nrows; row++) {
  695. int n = row;
  696. int nc;
  697. for (nc = 1; nc < ncols && n+nrows < nfiles; n += nrows, nc++) {
  698. printf("%s%-*s", matches[n],
  699. (int)(column_width - strlen(matches[n])), "");
  700. }
  701. puts(matches[n]);
  702. }
  703. }
  704. static char *add_quote_for_spec_chars(char *found)
  705. {
  706. int l = 0;
  707. char *s = xmalloc((strlen(found) + 1) * 2);
  708. while (*found) {
  709. if (strchr(" `\"#$%^&*()=+{}[]:;\'|\\<>", *found))
  710. s[l++] = '\\';
  711. s[l++] = *found++;
  712. }
  713. s[l] = 0;
  714. return s;
  715. }
  716. /* Do TAB completion */
  717. static void input_tab(smallint *lastWasTab)
  718. {
  719. if (!(state->flags & TAB_COMPLETION))
  720. return;
  721. if (!*lastWasTab) {
  722. char *tmp, *tmp1;
  723. int len_found;
  724. /* char matchBuf[MAX_LINELEN]; */
  725. #define matchBuf (S.input_tab__matchBuf)
  726. int find_type;
  727. int recalc_pos;
  728. *lastWasTab = TRUE; /* flop trigger */
  729. /* Make a local copy of the string -- up
  730. * to the position of the cursor */
  731. tmp = strncpy(matchBuf, command_ps, cursor);
  732. tmp[cursor] = '\0';
  733. find_type = find_match(matchBuf, &recalc_pos);
  734. /* Free up any memory already allocated */
  735. free_tab_completion_data();
  736. #if ENABLE_FEATURE_USERNAME_COMPLETION
  737. /* If the word starts with `~' and there is no slash in the word,
  738. * then try completing this word as a username. */
  739. if (state->flags & USERNAME_COMPLETION)
  740. if (matchBuf[0] == '~' && strchr(matchBuf, '/') == 0)
  741. username_tab_completion(matchBuf, NULL);
  742. #endif
  743. /* Try to match any executable in our path and everything
  744. * in the current working directory */
  745. if (!matches)
  746. exe_n_cwd_tab_completion(matchBuf, find_type);
  747. /* Sort, then remove any duplicates found */
  748. if (matches) {
  749. int i, n = 0;
  750. qsort_string_vector(matches, num_matches);
  751. for (i = 0; i < num_matches - 1; ++i) {
  752. if (matches[i] && matches[i+1]) { /* paranoia */
  753. if (strcmp(matches[i], matches[i+1]) == 0) {
  754. free(matches[i]);
  755. matches[i] = NULL; /* paranoia */
  756. } else {
  757. matches[n++] = matches[i];
  758. }
  759. }
  760. }
  761. matches[n] = matches[i];
  762. num_matches = n + 1;
  763. }
  764. /* Did we find exactly one match? */
  765. if (!matches || num_matches > 1) {
  766. beep();
  767. if (!matches)
  768. return; /* not found */
  769. /* find minimal match */
  770. tmp1 = xstrdup(matches[0]);
  771. for (tmp = tmp1; *tmp; tmp++)
  772. for (len_found = 1; len_found < num_matches; len_found++)
  773. if (matches[len_found][(tmp - tmp1)] != *tmp) {
  774. *tmp = '\0';
  775. break;
  776. }
  777. if (*tmp1 == '\0') { /* have unique */
  778. free(tmp1);
  779. return;
  780. }
  781. tmp = add_quote_for_spec_chars(tmp1);
  782. free(tmp1);
  783. } else { /* one match */
  784. tmp = add_quote_for_spec_chars(matches[0]);
  785. /* for next completion current found */
  786. *lastWasTab = FALSE;
  787. len_found = strlen(tmp);
  788. if (tmp[len_found-1] != '/') {
  789. tmp[len_found] = ' ';
  790. tmp[len_found+1] = '\0';
  791. }
  792. }
  793. len_found = strlen(tmp);
  794. /* have space to placed match? */
  795. if ((len_found - strlen(matchBuf) + command_len) < MAX_LINELEN) {
  796. /* before word for match */
  797. command_ps[cursor - recalc_pos] = '\0';
  798. /* save tail line */
  799. strcpy(matchBuf, command_ps + cursor);
  800. /* add match */
  801. strcat(command_ps, tmp);
  802. /* add tail */
  803. strcat(command_ps, matchBuf);
  804. /* back to begin word for match */
  805. input_backward(recalc_pos);
  806. /* new pos */
  807. recalc_pos = cursor + len_found;
  808. /* new len */
  809. command_len = strlen(command_ps);
  810. /* write out the matched command */
  811. redraw(cmdedit_y, command_len - recalc_pos);
  812. }
  813. free(tmp);
  814. #undef matchBuf
  815. } else {
  816. /* Ok -- the last char was a TAB. Since they
  817. * just hit TAB again, print a list of all the
  818. * available choices... */
  819. if (matches && num_matches > 0) {
  820. int sav_cursor = cursor; /* change goto_new_line() */
  821. /* Go to the next line */
  822. goto_new_line();
  823. showfiles();
  824. redraw(0, command_len - sav_cursor);
  825. }
  826. }
  827. }
  828. #endif /* FEATURE_COMMAND_TAB_COMPLETION */
  829. #if MAX_HISTORY > 0
  830. /* state->flags is already checked to be nonzero */
  831. static void get_previous_history(void)
  832. {
  833. if (command_ps[0] != '\0' || state->history[state->cur_history] == NULL) {
  834. free(state->history[state->cur_history]);
  835. state->history[state->cur_history] = xstrdup(command_ps);
  836. }
  837. state->cur_history--;
  838. }
  839. static int get_next_history(void)
  840. {
  841. if (state->flags & DO_HISTORY) {
  842. int ch = state->cur_history;
  843. if (ch < state->cnt_history) {
  844. get_previous_history(); /* save the current history line */
  845. state->cur_history = ch + 1;
  846. return state->cur_history;
  847. }
  848. }
  849. beep();
  850. return 0;
  851. }
  852. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  853. /* state->flags is already checked to be nonzero */
  854. static void load_history(const char *fromfile)
  855. {
  856. FILE *fp;
  857. int hi;
  858. /* cleanup old */
  859. for (hi = state->cnt_history; hi > 0;) {
  860. hi--;
  861. free(state->history[hi]);
  862. }
  863. fp = fopen(fromfile, "r");
  864. if (fp) {
  865. for (hi = 0; hi < MAX_HISTORY;) {
  866. char *hl = xmalloc_getline(fp);
  867. int l;
  868. if (!hl)
  869. break;
  870. l = strlen(hl);
  871. if (l >= MAX_LINELEN)
  872. hl[MAX_LINELEN-1] = '\0';
  873. if (l == 0 || hl[0] == ' ') {
  874. free(hl);
  875. continue;
  876. }
  877. state->history[hi++] = hl;
  878. }
  879. fclose(fp);
  880. }
  881. state->cur_history = state->cnt_history = hi;
  882. }
  883. /* state->flags is already checked to be nonzero */
  884. static void save_history(const char *tofile)
  885. {
  886. FILE *fp;
  887. fp = fopen(tofile, "w");
  888. if (fp) {
  889. int i;
  890. for (i = 0; i < state->cnt_history; i++) {
  891. fprintf(fp, "%s\n", state->history[i]);
  892. }
  893. fclose(fp);
  894. }
  895. }
  896. #else
  897. #define load_history(a) ((void)0)
  898. #define save_history(a) ((void)0)
  899. #endif /* FEATURE_COMMAND_SAVEHISTORY */
  900. static void remember_in_history(const char *str)
  901. {
  902. int i;
  903. if (!(state->flags & DO_HISTORY))
  904. return;
  905. i = state->cnt_history;
  906. free(state->history[MAX_HISTORY]);
  907. state->history[MAX_HISTORY] = NULL;
  908. /* After max history, remove the oldest command */
  909. if (i >= MAX_HISTORY) {
  910. free(state->history[0]);
  911. for (i = 0; i < MAX_HISTORY-1; i++)
  912. state->history[i] = state->history[i+1];
  913. }
  914. // Maybe "if (!i || strcmp(history[i-1], command) != 0) ..."
  915. // (i.e. do not save dups?)
  916. state->history[i++] = xstrdup(str);
  917. state->cur_history = i;
  918. state->cnt_history = i;
  919. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  920. if ((state->flags & SAVE_HISTORY) && state->hist_file)
  921. save_history(state->hist_file);
  922. #endif
  923. USE_FEATURE_EDITING_FANCY_PROMPT(num_ok_lines++;)
  924. }
  925. #else /* MAX_HISTORY == 0 */
  926. #define remember_in_history(a) ((void)0)
  927. #endif /* MAX_HISTORY */
  928. /*
  929. * This function is used to grab a character buffer
  930. * from the input file descriptor and allows you to
  931. * a string with full command editing (sort of like
  932. * a mini readline).
  933. *
  934. * The following standard commands are not implemented:
  935. * ESC-b -- Move back one word
  936. * ESC-f -- Move forward one word
  937. * ESC-d -- Delete back one word
  938. * ESC-h -- Delete forward one word
  939. * CTL-t -- Transpose two characters
  940. *
  941. * Minimalist vi-style command line editing available if configured.
  942. * vi mode implemented 2005 by Paul Fox <pgf@foxharp.boston.ma.us>
  943. */
  944. #if ENABLE_FEATURE_EDITING_VI
  945. static void
  946. vi_Word_motion(char *command, int eat)
  947. {
  948. while (cursor < command_len && !isspace(command[cursor]))
  949. input_forward();
  950. if (eat) while (cursor < command_len && isspace(command[cursor]))
  951. input_forward();
  952. }
  953. static void
  954. vi_word_motion(char *command, int eat)
  955. {
  956. if (isalnum(command[cursor]) || command[cursor] == '_') {
  957. while (cursor < command_len
  958. && (isalnum(command[cursor+1]) || command[cursor+1] == '_'))
  959. input_forward();
  960. } else if (ispunct(command[cursor])) {
  961. while (cursor < command_len && ispunct(command[cursor+1]))
  962. input_forward();
  963. }
  964. if (cursor < command_len)
  965. input_forward();
  966. if (eat && cursor < command_len && isspace(command[cursor]))
  967. while (cursor < command_len && isspace(command[cursor]))
  968. input_forward();
  969. }
  970. static void
  971. vi_End_motion(char *command)
  972. {
  973. input_forward();
  974. while (cursor < command_len && isspace(command[cursor]))
  975. input_forward();
  976. while (cursor < command_len-1 && !isspace(command[cursor+1]))
  977. input_forward();
  978. }
  979. static void
  980. vi_end_motion(char *command)
  981. {
  982. if (cursor >= command_len-1)
  983. return;
  984. input_forward();
  985. while (cursor < command_len-1 && isspace(command[cursor]))
  986. input_forward();
  987. if (cursor >= command_len-1)
  988. return;
  989. if (isalnum(command[cursor]) || command[cursor] == '_') {
  990. while (cursor < command_len-1
  991. && (isalnum(command[cursor+1]) || command[cursor+1] == '_')
  992. ) {
  993. input_forward();
  994. }
  995. } else if (ispunct(command[cursor])) {
  996. while (cursor < command_len-1 && ispunct(command[cursor+1]))
  997. input_forward();
  998. }
  999. }
  1000. static void
  1001. vi_Back_motion(char *command)
  1002. {
  1003. while (cursor > 0 && isspace(command[cursor-1]))
  1004. input_backward(1);
  1005. while (cursor > 0 && !isspace(command[cursor-1]))
  1006. input_backward(1);
  1007. }
  1008. static void
  1009. vi_back_motion(char *command)
  1010. {
  1011. if (cursor <= 0)
  1012. return;
  1013. input_backward(1);
  1014. while (cursor > 0 && isspace(command[cursor]))
  1015. input_backward(1);
  1016. if (cursor <= 0)
  1017. return;
  1018. if (isalnum(command[cursor]) || command[cursor] == '_') {
  1019. while (cursor > 0
  1020. && (isalnum(command[cursor-1]) || command[cursor-1] == '_')
  1021. ) {
  1022. input_backward(1);
  1023. }
  1024. } else if (ispunct(command[cursor])) {
  1025. while (cursor > 0 && ispunct(command[cursor-1]))
  1026. input_backward(1);
  1027. }
  1028. }
  1029. #endif
  1030. /*
  1031. * read_line_input and its helpers
  1032. */
  1033. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1034. static void parse_and_put_prompt(const char *prmt_ptr)
  1035. {
  1036. cmdedit_prompt = prmt_ptr;
  1037. cmdedit_prmt_len = strlen(prmt_ptr);
  1038. put_prompt();
  1039. }
  1040. #else
  1041. static void parse_and_put_prompt(const char *prmt_ptr)
  1042. {
  1043. int prmt_len = 0;
  1044. size_t cur_prmt_len = 0;
  1045. char flg_not_length = '[';
  1046. char *prmt_mem_ptr = xzalloc(1);
  1047. char *cwd_buf = xrealloc_getcwd_or_warn(NULL);
  1048. char cbuf[2];
  1049. char c;
  1050. char *pbuf;
  1051. cmdedit_prmt_len = 0;
  1052. if (!cwd_buf) {
  1053. cwd_buf = (char *)bb_msg_unknown;
  1054. }
  1055. cbuf[1] = '\0'; /* never changes */
  1056. while (*prmt_ptr) {
  1057. char *free_me = NULL;
  1058. pbuf = cbuf;
  1059. c = *prmt_ptr++;
  1060. if (c == '\\') {
  1061. const char *cp = prmt_ptr;
  1062. int l;
  1063. c = bb_process_escape_sequence(&prmt_ptr);
  1064. if (prmt_ptr == cp) {
  1065. if (*cp == '\0')
  1066. break;
  1067. c = *prmt_ptr++;
  1068. switch (c) {
  1069. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1070. case 'u':
  1071. pbuf = user_buf ? user_buf : (char*)"";
  1072. break;
  1073. #endif
  1074. case 'h':
  1075. pbuf = free_me = safe_gethostname();
  1076. *strchrnul(pbuf, '.') = '\0';
  1077. break;
  1078. case '$':
  1079. c = (geteuid() == 0 ? '#' : '$');
  1080. break;
  1081. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1082. case 'w':
  1083. /* /home/user[/something] -> ~[/something] */
  1084. pbuf = cwd_buf;
  1085. l = strlen(home_pwd_buf);
  1086. if (l != 0
  1087. && strncmp(home_pwd_buf, cwd_buf, l) == 0
  1088. && (cwd_buf[l]=='/' || cwd_buf[l]=='\0')
  1089. && strlen(cwd_buf + l) < PATH_MAX
  1090. ) {
  1091. pbuf = free_me = xasprintf("~%s", cwd_buf + l);
  1092. }
  1093. break;
  1094. #endif
  1095. case 'W':
  1096. pbuf = cwd_buf;
  1097. cp = strrchr(pbuf, '/');
  1098. if (cp != NULL && cp != pbuf)
  1099. pbuf += (cp-pbuf) + 1;
  1100. break;
  1101. case '!':
  1102. pbuf = free_me = xasprintf("%d", num_ok_lines);
  1103. break;
  1104. case 'e': case 'E': /* \e \E = \033 */
  1105. c = '\033';
  1106. break;
  1107. case 'x': case 'X': {
  1108. char buf2[4];
  1109. for (l = 0; l < 3;) {
  1110. unsigned h;
  1111. buf2[l++] = *prmt_ptr;
  1112. buf2[l] = '\0';
  1113. h = strtoul(buf2, &pbuf, 16);
  1114. if (h > UCHAR_MAX || (pbuf - buf2) < l) {
  1115. buf2[--l] = '\0';
  1116. break;
  1117. }
  1118. prmt_ptr++;
  1119. }
  1120. c = (char)strtoul(buf2, NULL, 16);
  1121. if (c == 0)
  1122. c = '?';
  1123. pbuf = cbuf;
  1124. break;
  1125. }
  1126. case '[': case ']':
  1127. if (c == flg_not_length) {
  1128. flg_not_length = (flg_not_length == '[' ? ']' : '[');
  1129. continue;
  1130. }
  1131. break;
  1132. } /* switch */
  1133. } /* if */
  1134. } /* if */
  1135. cbuf[0] = c;
  1136. cur_prmt_len = strlen(pbuf);
  1137. prmt_len += cur_prmt_len;
  1138. if (flg_not_length != ']')
  1139. cmdedit_prmt_len += cur_prmt_len;
  1140. prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_len+1), pbuf);
  1141. free(free_me);
  1142. } /* while */
  1143. if (cwd_buf != (char *)bb_msg_unknown)
  1144. free(cwd_buf);
  1145. cmdedit_prompt = prmt_mem_ptr;
  1146. put_prompt();
  1147. }
  1148. #endif
  1149. static void cmdedit_setwidth(unsigned w, int redraw_flg)
  1150. {
  1151. cmdedit_termw = w;
  1152. if (redraw_flg) {
  1153. /* new y for current cursor */
  1154. int new_y = (cursor + cmdedit_prmt_len) / w;
  1155. /* redraw */
  1156. redraw((new_y >= cmdedit_y ? new_y : cmdedit_y), command_len - cursor);
  1157. fflush(stdout);
  1158. }
  1159. }
  1160. static void win_changed(int nsig)
  1161. {
  1162. int width;
  1163. get_terminal_width_height(0, &width, NULL);
  1164. cmdedit_setwidth(width, nsig /* - just a yes/no flag */);
  1165. if (nsig == SIGWINCH)
  1166. signal(SIGWINCH, win_changed); /* rearm ourself */
  1167. }
  1168. /*
  1169. * The emacs and vi modes share much of the code in the big
  1170. * command loop. Commands entered when in vi's command mode (aka
  1171. * "escape mode") get an extra bit added to distinguish them --
  1172. * this keeps them from being self-inserted. This clutters the
  1173. * big switch a bit, but keeps all the code in one place.
  1174. */
  1175. #define vbit 0x100
  1176. /* leave out the "vi-mode"-only case labels if vi editing isn't
  1177. * configured. */
  1178. #define vi_case(caselabel) USE_FEATURE_EDITING(case caselabel)
  1179. /* convert uppercase ascii to equivalent control char, for readability */
  1180. #undef CTRL
  1181. #define CTRL(a) ((a) & ~0x40)
  1182. /* Returns:
  1183. * -1 on read errors or EOF, or on bare Ctrl-D,
  1184. * 0 on ctrl-C (the line entered is still returned in 'command'),
  1185. * >0 length of input string, including terminating '\n'
  1186. */
  1187. int read_line_input(const char *prompt, char *command, int maxsize, line_input_t *st)
  1188. {
  1189. #if ENABLE_FEATURE_TAB_COMPLETION
  1190. smallint lastWasTab = FALSE;
  1191. #endif
  1192. unsigned int ic;
  1193. unsigned char c;
  1194. smallint break_out = 0;
  1195. #if ENABLE_FEATURE_EDITING_VI
  1196. smallint vi_cmdmode = 0;
  1197. smalluint prevc;
  1198. #endif
  1199. struct termios initial_settings;
  1200. struct termios new_settings;
  1201. INIT_S();
  1202. if (tcgetattr(STDIN_FILENO, &initial_settings) < 0
  1203. || !(initial_settings.c_lflag & ECHO)
  1204. ) {
  1205. /* Happens when e.g. stty -echo was run before */
  1206. int len;
  1207. parse_and_put_prompt(prompt);
  1208. fflush(stdout);
  1209. if (fgets(command, maxsize, stdin) == NULL)
  1210. len = -1; /* EOF or error */
  1211. else
  1212. len = strlen(command);
  1213. DEINIT_S();
  1214. return len;
  1215. }
  1216. // FIXME: audit & improve this
  1217. if (maxsize > MAX_LINELEN)
  1218. maxsize = MAX_LINELEN;
  1219. /* With null flags, no other fields are ever used */
  1220. state = st ? st : (line_input_t*) &const_int_0;
  1221. #if ENABLE_FEATURE_EDITING_SAVEHISTORY
  1222. if ((state->flags & SAVE_HISTORY) && state->hist_file)
  1223. load_history(state->hist_file);
  1224. #endif
  1225. /* prepare before init handlers */
  1226. cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
  1227. command_len = 0;
  1228. command_ps = command;
  1229. command[0] = '\0';
  1230. new_settings = initial_settings;
  1231. new_settings.c_lflag &= ~ICANON; /* unbuffered input */
  1232. /* Turn off echoing and CTRL-C, so we can trap it */
  1233. new_settings.c_lflag &= ~(ECHO | ECHONL | ISIG);
  1234. /* Hmm, in linux c_cc[] is not parsed if ICANON is off */
  1235. new_settings.c_cc[VMIN] = 1;
  1236. new_settings.c_cc[VTIME] = 0;
  1237. /* Turn off CTRL-C, so we can trap it */
  1238. #ifndef _POSIX_VDISABLE
  1239. #define _POSIX_VDISABLE '\0'
  1240. #endif
  1241. new_settings.c_cc[VINTR] = _POSIX_VDISABLE;
  1242. tcsetattr(STDIN_FILENO, TCSANOW, &new_settings);
  1243. /* Now initialize things */
  1244. previous_SIGWINCH_handler = signal(SIGWINCH, win_changed);
  1245. win_changed(0); /* do initial resizing */
  1246. #if ENABLE_FEATURE_GETUSERNAME_AND_HOMEDIR
  1247. {
  1248. struct passwd *entry;
  1249. entry = getpwuid(geteuid());
  1250. if (entry) {
  1251. user_buf = xstrdup(entry->pw_name);
  1252. home_pwd_buf = xstrdup(entry->pw_dir);
  1253. }
  1254. }
  1255. #endif
  1256. /* Print out the command prompt */
  1257. parse_and_put_prompt(prompt);
  1258. while (1) {
  1259. fflush(NULL);
  1260. if (nonblock_safe_read(STDIN_FILENO, &c, 1) < 1) {
  1261. /* if we can't read input then exit */
  1262. goto prepare_to_die;
  1263. }
  1264. ic = c;
  1265. #if ENABLE_FEATURE_EDITING_VI
  1266. newdelflag = 1;
  1267. if (vi_cmdmode)
  1268. ic |= vbit;
  1269. #endif
  1270. switch (ic) {
  1271. case '\n':
  1272. case '\r':
  1273. vi_case('\n'|vbit:)
  1274. vi_case('\r'|vbit:)
  1275. /* Enter */
  1276. goto_new_line();
  1277. break_out = 1;
  1278. break;
  1279. case CTRL('A'):
  1280. vi_case('0'|vbit:)
  1281. /* Control-a -- Beginning of line */
  1282. input_backward(cursor);
  1283. break;
  1284. case CTRL('B'):
  1285. vi_case('h'|vbit:)
  1286. vi_case('\b'|vbit:)
  1287. vi_case('\x7f'|vbit:) /* DEL */
  1288. /* Control-b -- Move back one character */
  1289. input_backward(1);
  1290. break;
  1291. case CTRL('C'):
  1292. vi_case(CTRL('C')|vbit:)
  1293. /* Control-c -- stop gathering input */
  1294. goto_new_line();
  1295. command_len = 0;
  1296. break_out = -1; /* "do not append '\n'" */
  1297. break;
  1298. case CTRL('D'):
  1299. /* Control-d -- Delete one character, or exit
  1300. * if the len=0 and no chars to delete */
  1301. if (command_len == 0) {
  1302. errno = 0;
  1303. prepare_to_die:
  1304. /* to control stopped jobs */
  1305. break_out = command_len = -1;
  1306. break;
  1307. }
  1308. input_delete(0);
  1309. break;
  1310. case CTRL('E'):
  1311. vi_case('$'|vbit:)
  1312. /* Control-e -- End of line */
  1313. input_end();
  1314. break;
  1315. case CTRL('F'):
  1316. vi_case('l'|vbit:)
  1317. vi_case(' '|vbit:)
  1318. /* Control-f -- Move forward one character */
  1319. input_forward();
  1320. break;
  1321. case '\b':
  1322. case '\x7f': /* DEL */
  1323. /* Control-h and DEL */
  1324. input_backspace();
  1325. break;
  1326. #if ENABLE_FEATURE_TAB_COMPLETION
  1327. case '\t':
  1328. input_tab(&lastWasTab);
  1329. break;
  1330. #endif
  1331. case CTRL('K'):
  1332. /* Control-k -- clear to end of line */
  1333. command[cursor] = 0;
  1334. command_len = cursor;
  1335. printf("\033[J");
  1336. break;
  1337. case CTRL('L'):
  1338. vi_case(CTRL('L')|vbit:)
  1339. /* Control-l -- clear screen */
  1340. printf("\033[H");
  1341. redraw(0, command_len - cursor);
  1342. break;
  1343. #if MAX_HISTORY > 0
  1344. case CTRL('N'):
  1345. vi_case(CTRL('N')|vbit:)
  1346. vi_case('j'|vbit:)
  1347. /* Control-n -- Get next command in history */
  1348. if (get_next_history())
  1349. goto rewrite_line;
  1350. break;
  1351. case CTRL('P'):
  1352. vi_case(CTRL('P')|vbit:)
  1353. vi_case('k'|vbit:)
  1354. /* Control-p -- Get previous command from history */
  1355. if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
  1356. get_previous_history();
  1357. goto rewrite_line;
  1358. }
  1359. beep();
  1360. break;
  1361. #endif
  1362. case CTRL('U'):
  1363. vi_case(CTRL('U')|vbit:)
  1364. /* Control-U -- Clear line before cursor */
  1365. if (cursor) {
  1366. strcpy(command, command + cursor);
  1367. command_len -= cursor;
  1368. redraw(cmdedit_y, command_len);
  1369. }
  1370. break;
  1371. case CTRL('W'):
  1372. vi_case(CTRL('W')|vbit:)
  1373. /* Control-W -- Remove the last word */
  1374. while (cursor > 0 && isspace(command[cursor-1]))
  1375. input_backspace();
  1376. while (cursor > 0 && !isspace(command[cursor-1]))
  1377. input_backspace();
  1378. break;
  1379. #if ENABLE_FEATURE_EDITING_VI
  1380. case 'i'|vbit:
  1381. vi_cmdmode = 0;
  1382. break;
  1383. case 'I'|vbit:
  1384. input_backward(cursor);
  1385. vi_cmdmode = 0;
  1386. break;
  1387. case 'a'|vbit:
  1388. input_forward();
  1389. vi_cmdmode = 0;
  1390. break;
  1391. case 'A'|vbit:
  1392. input_end();
  1393. vi_cmdmode = 0;
  1394. break;
  1395. case 'x'|vbit:
  1396. input_delete(1);
  1397. break;
  1398. case 'X'|vbit:
  1399. if (cursor > 0) {
  1400. input_backward(1);
  1401. input_delete(1);
  1402. }
  1403. break;
  1404. case 'W'|vbit:
  1405. vi_Word_motion(command, 1);
  1406. break;
  1407. case 'w'|vbit:
  1408. vi_word_motion(command, 1);
  1409. break;
  1410. case 'E'|vbit:
  1411. vi_End_motion(command);
  1412. break;
  1413. case 'e'|vbit:
  1414. vi_end_motion(command);
  1415. break;
  1416. case 'B'|vbit:
  1417. vi_Back_motion(command);
  1418. break;
  1419. case 'b'|vbit:
  1420. vi_back_motion(command);
  1421. break;
  1422. case 'C'|vbit:
  1423. vi_cmdmode = 0;
  1424. /* fall through */
  1425. case 'D'|vbit:
  1426. goto clear_to_eol;
  1427. case 'c'|vbit:
  1428. vi_cmdmode = 0;
  1429. /* fall through */
  1430. case 'd'|vbit: {
  1431. int nc, sc;
  1432. sc = cursor;
  1433. prevc = ic;
  1434. if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1435. goto prepare_to_die;
  1436. if (c == (prevc & 0xff)) {
  1437. /* "cc", "dd" */
  1438. input_backward(cursor);
  1439. goto clear_to_eol;
  1440. break;
  1441. }
  1442. switch (c) {
  1443. case 'w':
  1444. case 'W':
  1445. case 'e':
  1446. case 'E':
  1447. switch (c) {
  1448. case 'w': /* "dw", "cw" */
  1449. vi_word_motion(command, vi_cmdmode);
  1450. break;
  1451. case 'W': /* 'dW', 'cW' */
  1452. vi_Word_motion(command, vi_cmdmode);
  1453. break;
  1454. case 'e': /* 'de', 'ce' */
  1455. vi_end_motion(command);
  1456. input_forward();
  1457. break;
  1458. case 'E': /* 'dE', 'cE' */
  1459. vi_End_motion(command);
  1460. input_forward();
  1461. break;
  1462. }
  1463. nc = cursor;
  1464. input_backward(cursor - sc);
  1465. while (nc-- > cursor)
  1466. input_delete(1);
  1467. break;
  1468. case 'b': /* "db", "cb" */
  1469. case 'B': /* implemented as B */
  1470. if (c == 'b')
  1471. vi_back_motion(command);
  1472. else
  1473. vi_Back_motion(command);
  1474. while (sc-- > cursor)
  1475. input_delete(1);
  1476. break;
  1477. case ' ': /* "d ", "c " */
  1478. input_delete(1);
  1479. break;
  1480. case '$': /* "d$", "c$" */
  1481. clear_to_eol:
  1482. while (cursor < command_len)
  1483. input_delete(1);
  1484. break;
  1485. }
  1486. break;
  1487. }
  1488. case 'p'|vbit:
  1489. input_forward();
  1490. /* fallthrough */
  1491. case 'P'|vbit:
  1492. put();
  1493. break;
  1494. case 'r'|vbit:
  1495. if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1496. goto prepare_to_die;
  1497. if (c == 0)
  1498. beep();
  1499. else {
  1500. *(command + cursor) = c;
  1501. bb_putchar(c);
  1502. bb_putchar('\b');
  1503. }
  1504. break;
  1505. #endif /* FEATURE_COMMAND_EDITING_VI */
  1506. case '\x1b': /* ESC */
  1507. #if ENABLE_FEATURE_EDITING_VI
  1508. if (state->flags & VI_MODE) {
  1509. /* ESC: insert mode --> command mode */
  1510. vi_cmdmode = 1;
  1511. input_backward(1);
  1512. break;
  1513. }
  1514. #endif
  1515. /* escape sequence follows */
  1516. if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1517. goto prepare_to_die;
  1518. /* different vt100 emulations */
  1519. if (c == '[' || c == 'O') {
  1520. vi_case('['|vbit:)
  1521. vi_case('O'|vbit:)
  1522. if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1523. goto prepare_to_die;
  1524. }
  1525. if (c >= '1' && c <= '9') {
  1526. unsigned char dummy;
  1527. if (safe_read(STDIN_FILENO, &dummy, 1) < 1)
  1528. goto prepare_to_die;
  1529. if (dummy != '~')
  1530. c = '\0';
  1531. }
  1532. switch (c) {
  1533. #if ENABLE_FEATURE_TAB_COMPLETION
  1534. case '\t': /* Alt-Tab */
  1535. input_tab(&lastWasTab);
  1536. break;
  1537. #endif
  1538. #if MAX_HISTORY > 0
  1539. case 'A':
  1540. /* Up Arrow -- Get previous command from history */
  1541. if ((state->flags & DO_HISTORY) && state->cur_history > 0) {
  1542. get_previous_history();
  1543. goto rewrite_line;
  1544. }
  1545. beep();
  1546. break;
  1547. case 'B':
  1548. /* Down Arrow -- Get next command in history */
  1549. if (!get_next_history())
  1550. break;
  1551. rewrite_line:
  1552. /* Rewrite the line with the selected history item */
  1553. /* change command */
  1554. command_len = strlen(strcpy(command, state->history[state->cur_history]));
  1555. /* redraw and go to eol (bol, in vi */
  1556. redraw(cmdedit_y, (state->flags & VI_MODE) ? 9999 : 0);
  1557. break;
  1558. #endif
  1559. case 'C':
  1560. /* Right Arrow -- Move forward one character */
  1561. input_forward();
  1562. break;
  1563. case 'D':
  1564. /* Left Arrow -- Move back one character */
  1565. input_backward(1);
  1566. break;
  1567. case '3':
  1568. /* Delete */
  1569. input_delete(0);
  1570. break;
  1571. case '1': // vt100? linux vt? or what?
  1572. case '7': // vt100? linux vt? or what?
  1573. case 'H': /* xterm's <Home> */
  1574. input_backward(cursor);
  1575. break;
  1576. case '4': // vt100? linux vt? or what?
  1577. case '8': // vt100? linux vt? or what?
  1578. case 'F': /* xterm's <End> */
  1579. input_end();
  1580. break;
  1581. default:
  1582. c = '\0';
  1583. beep();
  1584. }
  1585. break;
  1586. default: /* If it's regular input, do the normal thing */
  1587. /* Control-V -- force insert of next char */
  1588. if (c == CTRL('V')) {
  1589. if (safe_read(STDIN_FILENO, &c, 1) < 1)
  1590. goto prepare_to_die;
  1591. if (c == 0) {
  1592. beep();
  1593. break;
  1594. }
  1595. }
  1596. #if ENABLE_FEATURE_EDITING_VI
  1597. if (vi_cmdmode) /* Don't self-insert */
  1598. break;
  1599. #endif
  1600. if (command_len >= (maxsize - 2)) /* Need to leave space for enter */
  1601. break;
  1602. command_len++;
  1603. if (cursor == (command_len - 1)) { /* Append if at the end of the line */
  1604. command[cursor] = c;
  1605. command[cursor+1] = '\0';
  1606. cmdedit_set_out_char(' ');
  1607. } else { /* Insert otherwise */
  1608. int sc = cursor;
  1609. memmove(command + sc + 1, command + sc, command_len - sc);
  1610. command[sc] = c;
  1611. sc++;
  1612. /* rewrite from cursor */
  1613. input_end();
  1614. /* to prev x pos + 1 */
  1615. input_backward(cursor - sc);
  1616. }
  1617. break;
  1618. }
  1619. if (break_out) /* Enter is the command terminator, no more input. */
  1620. break;
  1621. #if ENABLE_FEATURE_TAB_COMPLETION
  1622. if (c != '\t')
  1623. lastWasTab = FALSE;
  1624. #endif
  1625. }
  1626. if (command_len > 0)
  1627. remember_in_history(command);
  1628. if (break_out > 0) {
  1629. command[command_len++] = '\n';
  1630. command[command_len] = '\0';
  1631. }
  1632. #if ENABLE_FEATURE_TAB_COMPLETION
  1633. free_tab_completion_data();
  1634. #endif
  1635. /* restore initial_settings */
  1636. tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);
  1637. /* restore SIGWINCH handler */
  1638. signal(SIGWINCH, previous_SIGWINCH_handler);
  1639. fflush(stdout);
  1640. DEINIT_S();
  1641. return command_len;
  1642. }
  1643. line_input_t *new_line_input_t(int flags)
  1644. {
  1645. line_input_t *n = xzalloc(sizeof(*n));
  1646. n->flags = flags;
  1647. return n;
  1648. }
  1649. #else
  1650. #undef read_line_input
  1651. int read_line_input(const char* prompt, char* command, int maxsize)
  1652. {
  1653. fputs(prompt, stdout);
  1654. fflush(stdout);
  1655. fgets(command, maxsize, stdin);
  1656. return strlen(command);
  1657. }
  1658. #endif /* FEATURE_COMMAND_EDITING */
  1659. /*
  1660. * Testing
  1661. */
  1662. #ifdef TEST
  1663. #include <locale.h>
  1664. const char *applet_name = "debug stuff usage";
  1665. int main(int argc, char **argv)
  1666. {
  1667. char buff[MAX_LINELEN];
  1668. char *prompt =
  1669. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  1670. "\\[\\033[32;1m\\]\\u@\\[\\x1b[33;1m\\]\\h:"
  1671. "\\[\\033[34;1m\\]\\w\\[\\033[35;1m\\] "
  1672. "\\!\\[\\e[36;1m\\]\\$ \\[\\E[0m\\]";
  1673. #else
  1674. "% ";
  1675. #endif
  1676. #if ENABLE_FEATURE_NONPRINTABLE_INVERSE_PUT
  1677. setlocale(LC_ALL, "");
  1678. #endif
  1679. while (1) {
  1680. int l;
  1681. l = read_line_input(prompt, buff);
  1682. if (l <= 0 || buff[l-1] != '\n')
  1683. break;
  1684. buff[l-1] = 0;
  1685. printf("*** read_line_input() returned line =%s=\n", buff);
  1686. }
  1687. printf("*** read_line_input() detect ^D\n");
  1688. return 0;
  1689. }
  1690. #endif /* TEST */