3
0

cmdedit.c 42 KB

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