lineedit.c 40 KB

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