lineedit.c 47 KB

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