cmdedit.c 44 KB

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