input_complete.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. /*
  2. Input line filename/username/hostname/variable/command completion.
  3. (Let mc type for you...)
  4. Copyright (C) 1995, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
  5. 2007, 2011
  6. the Free Software Foundation, Inc.
  7. Written by:
  8. Jakub Jelinek, 1995
  9. This file is part of the Midnight Commander.
  10. The Midnight Commander is free software: you can redistribute it
  11. and/or modify it under the terms of the GNU General Public License as
  12. published by the Free Software Foundation, either version 3 of the License,
  13. or (at your option) any later version.
  14. The Midnight Commander is distributed in the hope that it will be useful,
  15. but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. GNU General Public License for more details.
  18. You should have received a copy of the GNU General Public License
  19. along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. /** \file complete.c
  22. * \brief Source: Input line filename/username/hostname/variable/command completion
  23. */
  24. #include <config.h>
  25. #include <ctype.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <dirent.h>
  30. #include <sys/types.h>
  31. #include <sys/stat.h>
  32. #include <pwd.h>
  33. #include <unistd.h>
  34. #include "lib/global.h"
  35. #include "lib/tty/tty.h"
  36. #include "lib/tty/key.h" /* XCTRL and ALT macros */
  37. #include "lib/vfs/vfs.h"
  38. #include "lib/strescape.h"
  39. #include "lib/strutil.h"
  40. #include "lib/util.h"
  41. #include "lib/widget.h"
  42. #include "input_complete.h"
  43. /*** global variables ****************************************************************************/
  44. /* Linux declares environ in <unistd.h>, so don't repeat it here. */
  45. #if (!(defined(__linux__) && defined (__USE_GNU)) && !defined(__CYGWIN__))
  46. extern char **environ;
  47. #endif
  48. /*** file scope macro definitions ****************************************************************/
  49. /* #define DO_COMPLETION_DEBUG */
  50. #ifdef DO_COMPLETION_DEBUG
  51. #define SHOW_C_CTX(func) fprintf(stderr, "%s: text='%s' flags=%s\n", func, text, show_c_flags(flags))
  52. #else
  53. #define SHOW_C_CTX(func)
  54. #endif /* DO_CMPLETION_DEBUG */
  55. #define whitespace(c) ((c) == ' ' || (c) == '\t')
  56. #define cr_whitespace(c) (whitespace (c) || (c) == '\n' || (c) == '\r')
  57. #define DO_INSERTION 1
  58. #define DO_QUERY 2
  59. /*** file scope type declarations ****************************************************************/
  60. typedef char *CompletionFunction (const char *text, int state, input_complete_t flags);
  61. /*** file scope variables ************************************************************************/
  62. static char **hosts = NULL;
  63. static char **hosts_p = NULL;
  64. static int hosts_alloclen = 0;
  65. static int query_height, query_width;
  66. static WInput *input;
  67. static int min_end;
  68. static int start = 0;
  69. static int end = 0;
  70. /*** file scope functions ************************************************************************/
  71. /* --------------------------------------------------------------------------------------------- */
  72. #ifdef DO_COMPLETION_DEBUG
  73. /**
  74. * Useful to print/debug completion flags
  75. */
  76. static const char *
  77. show_c_flags (input_complete_t flags)
  78. {
  79. static char s_cf[] = "FHCVUDS";
  80. s_cf[0] = (flags & INPUT_COMPLETE_FILENAMES) ? 'F' : ' ';
  81. s_cf[1] = (flags & INPUT_COMPLETE_HOSTNAMES) ? 'H' : ' ';
  82. s_cf[2] = (flags & INPUT_COMPLETE_COMMANDS) ? 'C' : ' ';
  83. s_cf[3] = (flags & INPUT_COMPLETE_VARIABLES) ? 'V' : ' ';
  84. s_cf[4] = (flags & INPUT_COMPLETE_USERNAMES) ? 'U' : ' ';
  85. s_cf[5] = (flags & INPUT_COMPLETE_CD) ? 'D' : ' ';
  86. s_cf[6] = (flags & INPUT_COMPLETE_SHELL_ESC) ? 'S' : ' ';
  87. return s_cf;
  88. }
  89. #endif /* DO_CMPLETION_DEBUG */
  90. /* --------------------------------------------------------------------------------------------- */
  91. static char *
  92. filename_completion_function (const char *text, int state, input_complete_t flags)
  93. {
  94. static DIR *directory;
  95. static char *filename = NULL;
  96. static char *dirname = NULL;
  97. static char *users_dirname = NULL;
  98. static size_t filename_len;
  99. int isdir = 1, isexec = 0;
  100. static vfs_path_t *dirname_vpath = NULL;
  101. struct dirent *entry = NULL;
  102. SHOW_C_CTX ("filename_completion_function");
  103. if (text && (flags & INPUT_COMPLETE_SHELL_ESC))
  104. {
  105. char *u_text;
  106. char *result;
  107. char *e_result;
  108. u_text = strutils_shell_unescape (text);
  109. result = filename_completion_function (u_text, state, flags & (~INPUT_COMPLETE_SHELL_ESC));
  110. g_free (u_text);
  111. e_result = strutils_shell_escape (result);
  112. g_free (result);
  113. return e_result;
  114. }
  115. /* If we're starting the match process, initialize us a bit. */
  116. if (state == 0)
  117. {
  118. const char *temp;
  119. g_free (dirname);
  120. g_free (filename);
  121. g_free (users_dirname);
  122. vfs_path_free (dirname_vpath);
  123. if ((*text != '\0') && (temp = strrchr (text, PATH_SEP)) != NULL)
  124. {
  125. filename = g_strdup (++temp);
  126. dirname = g_strndup (text, temp - text);
  127. }
  128. else
  129. {
  130. dirname = g_strdup (".");
  131. filename = g_strdup (text);
  132. }
  133. dirname_vpath = vfs_path_from_str (dirname);
  134. /* We aren't done yet. We also support the "~user" syntax. */
  135. /* Save the version of the directory that the user typed. */
  136. users_dirname = dirname;
  137. dirname = tilde_expand (dirname);
  138. canonicalize_pathname (dirname);
  139. /* Here we should do something with variable expansion
  140. and `command`.
  141. Maybe a dream - UNIMPLEMENTED yet. */
  142. directory = mc_opendir (dirname_vpath);
  143. filename_len = strlen (filename);
  144. }
  145. /* Now that we have some state, we can read the directory. */
  146. while (directory && (entry = mc_readdir (directory)))
  147. {
  148. if (!str_is_valid_string (entry->d_name))
  149. continue;
  150. /* Special case for no filename.
  151. All entries except "." and ".." match. */
  152. if (filename_len == 0)
  153. {
  154. if (!strcmp (entry->d_name, ".") || !strcmp (entry->d_name, ".."))
  155. continue;
  156. }
  157. else
  158. {
  159. /* Otherwise, if these match up to the length of filename, then
  160. it may be a match. */
  161. if ((entry->d_name[0] != filename[0]) ||
  162. ((NLENGTH (entry)) < filename_len) ||
  163. strncmp (filename, entry->d_name, filename_len))
  164. continue;
  165. }
  166. isdir = 1;
  167. isexec = 0;
  168. {
  169. struct stat tempstat;
  170. vfs_path_t *tmp_vpath;
  171. tmp_vpath = vfs_path_build_filename (dirname, entry->d_name, (char *) NULL);
  172. /* Unix version */
  173. if (mc_stat (tmp_vpath, &tempstat) == 0)
  174. {
  175. uid_t my_uid = getuid ();
  176. gid_t my_gid = getgid ();
  177. if (!S_ISDIR (tempstat.st_mode))
  178. {
  179. isdir = 0;
  180. if ((!my_uid && (tempstat.st_mode & 0111)) ||
  181. (my_uid == tempstat.st_uid && (tempstat.st_mode & 0100)) ||
  182. (my_gid == tempstat.st_gid && (tempstat.st_mode & 0010)) ||
  183. (tempstat.st_mode & 0001))
  184. isexec = 1;
  185. }
  186. }
  187. else
  188. {
  189. /* stat failed, strange. not a dir in any case */
  190. isdir = 0;
  191. }
  192. vfs_path_free (tmp_vpath);
  193. }
  194. if ((flags & INPUT_COMPLETE_COMMANDS) && (isexec || isdir))
  195. break;
  196. if ((flags & INPUT_COMPLETE_CD) && isdir)
  197. break;
  198. if (flags & (INPUT_COMPLETE_FILENAMES))
  199. break;
  200. }
  201. if (entry == NULL)
  202. {
  203. if (directory)
  204. {
  205. mc_closedir (directory);
  206. directory = NULL;
  207. }
  208. g_free (dirname);
  209. dirname = NULL;
  210. vfs_path_free (dirname_vpath);
  211. dirname_vpath = NULL;
  212. g_free (filename);
  213. filename = NULL;
  214. g_free (users_dirname);
  215. users_dirname = NULL;
  216. return NULL;
  217. }
  218. else
  219. {
  220. char *temp;
  221. if (users_dirname && (users_dirname[0] != '.' || users_dirname[1]))
  222. {
  223. size_t dirlen = strlen (users_dirname);
  224. temp = g_malloc (3 + dirlen + NLENGTH (entry));
  225. strcpy (temp, users_dirname);
  226. /* We need a `/' at the end. */
  227. if (users_dirname[dirlen - 1] != PATH_SEP)
  228. {
  229. temp[dirlen] = PATH_SEP;
  230. temp[dirlen + 1] = '\0';
  231. }
  232. strcat (temp, entry->d_name);
  233. }
  234. else
  235. {
  236. temp = g_malloc (2 + NLENGTH (entry));
  237. strcpy (temp, entry->d_name);
  238. }
  239. if (isdir)
  240. strcat (temp, PATH_SEP_STR);
  241. return temp;
  242. }
  243. }
  244. /* --------------------------------------------------------------------------------------------- */
  245. /** We assume here that text[0] == '~' , if you want to call it in another way,
  246. you have to change the code */
  247. static char *
  248. username_completion_function (const char *text, int state, input_complete_t flags)
  249. {
  250. static struct passwd *entry;
  251. static size_t userlen;
  252. (void) flags;
  253. SHOW_C_CTX ("username_completion_function");
  254. if (text[0] == '\\' && text[1] == '~')
  255. text++;
  256. if (state == 0)
  257. { /* Initialization stuff */
  258. setpwent ();
  259. userlen = strlen (text + 1);
  260. }
  261. while ((entry = getpwent ()) != NULL)
  262. {
  263. /* Null usernames should result in all users as possible completions. */
  264. if (userlen == 0)
  265. break;
  266. if (text[1] == entry->pw_name[0] && !strncmp (text + 1, entry->pw_name, userlen))
  267. break;
  268. }
  269. if (entry != NULL)
  270. return g_strconcat ("~", entry->pw_name, PATH_SEP_STR, (char *) NULL);
  271. endpwent ();
  272. return NULL;
  273. }
  274. /* --------------------------------------------------------------------------------------------- */
  275. /** We assume text [0] == '$' and want to have a look at text [1], if it is
  276. equal to '{', so that we should append '}' at the end */
  277. static char *
  278. variable_completion_function (const char *text, int state, input_complete_t flags)
  279. {
  280. static char **env_p;
  281. static int varlen, isbrace;
  282. const char *p = NULL;
  283. (void) flags;
  284. SHOW_C_CTX ("variable_completion_function");
  285. if (state == 0)
  286. { /* Initialization stuff */
  287. isbrace = (text[1] == '{');
  288. varlen = strlen (text + 1 + isbrace);
  289. env_p = environ;
  290. }
  291. while (*env_p)
  292. {
  293. p = strchr (*env_p, '=');
  294. if (p && p - *env_p >= varlen && !strncmp (text + 1 + isbrace, *env_p, varlen))
  295. break;
  296. env_p++;
  297. }
  298. if (*env_p == NULL)
  299. return NULL;
  300. {
  301. char *temp = g_malloc (2 + 2 * isbrace + p - *env_p);
  302. *temp = '$';
  303. if (isbrace)
  304. temp[1] = '{';
  305. memcpy (temp + 1 + isbrace, *env_p, p - *env_p);
  306. if (isbrace)
  307. strcpy (temp + 2 + (p - *env_p), "}");
  308. else
  309. temp[1 + p - *env_p] = 0;
  310. env_p++;
  311. return temp;
  312. }
  313. }
  314. /* --------------------------------------------------------------------------------------------- */
  315. static void
  316. fetch_hosts (const char *filename)
  317. {
  318. FILE *file = fopen (filename, "r");
  319. char buffer[256], *name;
  320. char *lc_start;
  321. char *bi;
  322. if (!file)
  323. return;
  324. while (fgets (buffer, 255, file) != NULL)
  325. {
  326. /* Skip to first character. */
  327. for (bi = buffer; bi[0] != '\0' && str_isspace (bi); str_next_char (&bi));
  328. /* Ignore comments... */
  329. if (bi[0] == '#')
  330. continue;
  331. /* Handle $include. */
  332. if (!strncmp (bi, "$include ", 9))
  333. {
  334. char *includefile = bi + 9;
  335. char *t;
  336. /* Find start of filename. */
  337. while (*includefile && whitespace (*includefile))
  338. includefile++;
  339. t = includefile;
  340. /* Find end of filename. */
  341. while (t[0] != '\0' && !str_isspace (t))
  342. str_next_char (&t);
  343. *t = '\0';
  344. fetch_hosts (includefile);
  345. continue;
  346. }
  347. /* Skip IP #s. */
  348. while (bi[0] != '\0' && !str_isspace (bi))
  349. str_next_char (&bi);
  350. /* Get the host names separated by white space. */
  351. while (bi[0] != '\0' && bi[0] != '#')
  352. {
  353. while (bi[0] != '\0' && str_isspace (bi))
  354. str_next_char (&bi);
  355. if (bi[0] == '#')
  356. continue;
  357. for (lc_start = bi; bi[0] != '\0' && !str_isspace (bi); str_next_char (&bi));
  358. if (bi - lc_start == 0)
  359. continue;
  360. name = g_strndup (lc_start, bi - lc_start);
  361. {
  362. char **host_p;
  363. if (hosts_p - hosts >= hosts_alloclen)
  364. {
  365. int j = hosts_p - hosts;
  366. hosts =
  367. g_realloc ((void *) hosts, ((hosts_alloclen += 30) + 1) * sizeof (char *));
  368. hosts_p = hosts + j;
  369. }
  370. for (host_p = hosts; host_p < hosts_p; host_p++)
  371. if (!strcmp (name, *host_p))
  372. break; /* We do not want any duplicates */
  373. if (host_p == hosts_p)
  374. {
  375. *(hosts_p++) = name;
  376. *hosts_p = NULL;
  377. }
  378. else
  379. g_free (name);
  380. }
  381. }
  382. }
  383. fclose (file);
  384. }
  385. /* --------------------------------------------------------------------------------------------- */
  386. static char *
  387. hostname_completion_function (const char *text, int state, input_complete_t flags)
  388. {
  389. static char **host_p;
  390. static int textstart, textlen;
  391. (void) flags;
  392. SHOW_C_CTX ("hostname_completion_function");
  393. if (!state)
  394. { /* Initialization stuff */
  395. const char *p;
  396. if (hosts != NULL)
  397. {
  398. for (host_p = hosts; *host_p; host_p++)
  399. g_free (*host_p);
  400. g_free (hosts);
  401. }
  402. hosts = g_new (char *, (hosts_alloclen = 30) + 1);
  403. *hosts = NULL;
  404. hosts_p = hosts;
  405. fetch_hosts ((p = getenv ("HOSTFILE")) ? p : "/etc/hosts");
  406. host_p = hosts;
  407. textstart = (*text == '@') ? 1 : 0;
  408. textlen = strlen (text + textstart);
  409. }
  410. while (*host_p)
  411. {
  412. if (!textlen)
  413. break; /* Match all of them */
  414. else if (!strncmp (text + textstart, *host_p, textlen))
  415. break;
  416. host_p++;
  417. }
  418. if (!*host_p)
  419. {
  420. for (host_p = hosts; *host_p; host_p++)
  421. g_free (*host_p);
  422. g_free (hosts);
  423. hosts = NULL;
  424. return NULL;
  425. }
  426. else
  427. {
  428. char *temp = g_malloc (2 + strlen (*host_p));
  429. if (textstart)
  430. *temp = '@';
  431. strcpy (temp + textstart, *host_p);
  432. host_p++;
  433. return temp;
  434. }
  435. }
  436. /* --------------------------------------------------------------------------------------------- */
  437. /**
  438. * This is the function to call when the word to complete is in a position
  439. * where a command word can be found. It looks around $PATH, looking for
  440. * commands that match. It also scans aliases, function names, and the
  441. * table of shell built-ins.
  442. */
  443. static char *
  444. command_completion_function (const char *_text, int state, input_complete_t flags)
  445. {
  446. char *text;
  447. static const char *path_end;
  448. static gboolean isabsolute;
  449. static int phase;
  450. static size_t text_len;
  451. static const char *const *words;
  452. static char *path;
  453. static char *cur_path;
  454. static char *cur_word;
  455. static int init_state;
  456. static const char *const bash_reserved[] = {
  457. "if", "then", "else", "elif", "fi", "case", "esac", "for",
  458. "select", "while", "until", "do", "done", "in", "function", 0
  459. };
  460. static const char *const bash_builtins[] = {
  461. "alias", "bg", "bind", "break", "builtin", "cd", "command",
  462. "continue", "declare", "dirs", "echo", "enable", "eval",
  463. "exec", "exit", "export", "fc", "fg", "getopts", "hash",
  464. "help", "history", "jobs", "kill", "let", "local", "logout",
  465. "popd", "pushd", "pwd", "read", "readonly", "return", "set",
  466. "shift", "source", "suspend", "test", "times", "trap", "type",
  467. "typeset", "ulimit", "umask", "unalias", "unset", "wait", 0
  468. };
  469. char *p, *found;
  470. SHOW_C_CTX ("command_completion_function");
  471. if (!(flags & INPUT_COMPLETE_COMMANDS))
  472. return 0;
  473. text = strutils_shell_unescape (_text);
  474. flags &= ~INPUT_COMPLETE_SHELL_ESC;
  475. if (state == 0)
  476. { /* Initialize us a little bit */
  477. isabsolute = strchr (text, PATH_SEP) != NULL;
  478. if (!isabsolute)
  479. {
  480. words = bash_reserved;
  481. phase = 0;
  482. text_len = strlen (text);
  483. if (path == NULL)
  484. {
  485. path = g_strdup (getenv ("PATH"));
  486. if (path != NULL)
  487. {
  488. p = path;
  489. path_end = strchr (p, '\0');
  490. while ((p = strchr (p, PATH_ENV_SEP)) != NULL)
  491. {
  492. *p++ = '\0';
  493. }
  494. }
  495. }
  496. }
  497. }
  498. if (isabsolute)
  499. {
  500. p = filename_completion_function (text, state, flags);
  501. if (p != NULL)
  502. {
  503. char *temp_p = p;
  504. p = strutils_shell_escape (p);
  505. g_free (temp_p);
  506. }
  507. g_free (text);
  508. return p;
  509. }
  510. found = NULL;
  511. switch (phase)
  512. {
  513. case 0: /* Reserved words */
  514. while (*words)
  515. {
  516. if (strncmp (*words, text, text_len) == 0)
  517. {
  518. g_free (text);
  519. return g_strdup (*(words++));
  520. }
  521. words++;
  522. }
  523. phase++;
  524. words = bash_builtins;
  525. case 1: /* Builtin commands */
  526. while (*words)
  527. {
  528. if (strncmp (*words, text, text_len) == 0)
  529. {
  530. g_free (text);
  531. return g_strdup (*(words++));
  532. }
  533. words++;
  534. }
  535. phase++;
  536. if (!path)
  537. break;
  538. cur_path = path;
  539. cur_word = NULL;
  540. case 2: /* And looking through the $PATH */
  541. while (!found)
  542. {
  543. if (!cur_word)
  544. {
  545. char *expanded;
  546. if (cur_path >= path_end)
  547. break;
  548. expanded = tilde_expand (*cur_path ? cur_path : ".");
  549. cur_word = mc_build_filename (expanded, text, NULL);
  550. g_free (expanded);
  551. canonicalize_pathname (cur_word);
  552. cur_path = strchr (cur_path, 0) + 1;
  553. init_state = state;
  554. }
  555. found = filename_completion_function (cur_word, state - init_state, flags);
  556. if (!found)
  557. {
  558. g_free (cur_word);
  559. cur_word = NULL;
  560. }
  561. }
  562. }
  563. if (found == NULL)
  564. {
  565. g_free (path);
  566. path = NULL;
  567. }
  568. else
  569. {
  570. p = strrchr (found, PATH_SEP);
  571. if (p != NULL)
  572. {
  573. char *tmp = found;
  574. found = strutils_shell_escape (p + 1);
  575. g_free (tmp);
  576. }
  577. }
  578. g_free (text);
  579. return found;
  580. }
  581. /* --------------------------------------------------------------------------------------------- */
  582. static int
  583. match_compare (const void *a, const void *b)
  584. {
  585. return strcmp (*(char **) a, *(char **) b);
  586. }
  587. /* --------------------------------------------------------------------------------------------- */
  588. /** Returns an array of char * matches with the longest common denominator
  589. in the 1st entry. Then a NULL terminated list of different possible
  590. completions follows.
  591. You have to supply your own CompletionFunction with the word you
  592. want to complete as the first argument and an count of previous matches
  593. as the second.
  594. In case no matches were found we return NULL. */
  595. static char **
  596. completion_matches (const char *text, CompletionFunction entry_function, input_complete_t flags)
  597. {
  598. /* Number of slots in match_list. */
  599. int match_list_size;
  600. /* The list of matches. */
  601. char **match_list = g_new (char *, (match_list_size = 30) + 1);
  602. /* Number of matches actually found. */
  603. int matches = 0;
  604. /* Temporary string binder. */
  605. char *string;
  606. match_list[1] = NULL;
  607. while ((string = (*entry_function) (text, matches, flags)) != NULL)
  608. {
  609. if (matches + 1 == match_list_size)
  610. match_list =
  611. (char **) g_realloc (match_list, ((match_list_size += 30) + 1) * sizeof (char *));
  612. match_list[++matches] = string;
  613. match_list[matches + 1] = NULL;
  614. }
  615. /* If there were any matches, then look through them finding out the
  616. lowest common denominator. That then becomes match_list[0]. */
  617. if (matches)
  618. {
  619. register int i = 1;
  620. int low = 4096; /* Count of max-matched characters. */
  621. /* If only one match, just use that. */
  622. if (matches == 1)
  623. {
  624. match_list[0] = match_list[1];
  625. match_list[1] = NULL;
  626. }
  627. else
  628. {
  629. int j;
  630. qsort (match_list + 1, matches, sizeof (char *), match_compare);
  631. /* And compare each member of the list with
  632. the next, finding out where they stop matching.
  633. If we find two equal strings, we have to put one away... */
  634. j = i + 1;
  635. while (j < matches + 1)
  636. {
  637. char *si, *sj;
  638. char *ni, *nj;
  639. for (si = match_list[i], sj = match_list[j]; si[0] && sj[0];)
  640. {
  641. ni = str_get_next_char (si);
  642. nj = str_get_next_char (sj);
  643. if (ni - si != nj - sj)
  644. break;
  645. if (strncmp (si, sj, ni - si) != 0)
  646. break;
  647. si = ni;
  648. sj = nj;
  649. }
  650. if (si[0] == '\0' && sj[0] == '\0')
  651. { /* Two equal strings */
  652. g_free (match_list[j]);
  653. j++;
  654. if (j > matches)
  655. break;
  656. continue; /* Look for a run of equal strings */
  657. }
  658. else if (low > si - match_list[i])
  659. low = si - match_list[i];
  660. if (i + 1 != j) /* So there's some gap */
  661. match_list[i + 1] = match_list[j];
  662. i++;
  663. j++;
  664. }
  665. matches = i;
  666. match_list[matches + 1] = NULL;
  667. match_list[0] = g_strndup (match_list[1], low);
  668. }
  669. }
  670. else
  671. { /* There were no matches. */
  672. g_free (match_list);
  673. match_list = NULL;
  674. }
  675. return match_list;
  676. }
  677. /* --------------------------------------------------------------------------------------------- */
  678. /** Check if directory completion is needed */
  679. static gboolean
  680. check_is_cd (const char *text, int lc_start, input_complete_t flags)
  681. {
  682. char *p, *q;
  683. SHOW_C_CTX ("check_is_cd");
  684. if ((flags & INPUT_COMPLETE_CD) == 0)
  685. return FALSE;
  686. /* Skip initial spaces */
  687. p = (char *) text;
  688. q = (char *) text + lc_start;
  689. while (p < q && p[0] != '\0' && str_isspace (p))
  690. str_next_char (&p);
  691. /* Check if the command is "cd" and the cursor is after it */
  692. return (p[0] == 'c' && p[1] == 'd' && str_isspace (p + 2) && p + 2 < q);
  693. }
  694. /* --------------------------------------------------------------------------------------------- */
  695. /** Returns an array of matches, or NULL if none. */
  696. static char **
  697. try_complete (char *text, int *lc_start, int *lc_end, input_complete_t flags)
  698. {
  699. size_t in_command_position = 0;
  700. char *word;
  701. char **matches = NULL;
  702. char *p = NULL, *q = NULL, *r = NULL;
  703. gboolean is_cd;
  704. SHOW_C_CTX ("try_complete");
  705. word = g_strndup (text + *lc_start, *lc_end - *lc_start);
  706. is_cd = check_is_cd (text, *lc_start, flags);
  707. /* Determine if this could be a command word. It is if it appears at
  708. the start of the line (ignoring preceding whitespace), or if it
  709. appears after a character that separates commands. And we have to
  710. be in a INPUT_COMPLETE_COMMANDS flagged Input line. */
  711. if (!is_cd && (flags & INPUT_COMPLETE_COMMANDS))
  712. {
  713. const char *command_separator_chars = ";|&{(`";
  714. char *ti;
  715. if (*lc_start == 0)
  716. ti = text;
  717. else
  718. {
  719. ti = str_get_prev_char (&text[*lc_start]);
  720. while (ti > text && (ti[0] == ' ' || ti[0] == '\t'))
  721. str_prev_char (&ti);
  722. }
  723. if (ti == text)
  724. in_command_position++;
  725. else if (strchr (command_separator_chars, ti[0]) != NULL)
  726. {
  727. int this_char, prev_char;
  728. in_command_position++;
  729. if (ti != text)
  730. {
  731. /* Handle the two character tokens `>&', `<&', and `>|'.
  732. We are not in a command position after one of these. */
  733. this_char = ti[0];
  734. prev_char = str_get_prev_char (ti)[0];
  735. /* Quoted */
  736. if ((this_char == '&' && (prev_char == '<' || prev_char == '>'))
  737. || (this_char == '|' && prev_char == '>') || (ti != text
  738. && str_get_prev_char (ti)[0] ==
  739. '\\'))
  740. in_command_position = 0;
  741. }
  742. }
  743. }
  744. if (flags & INPUT_COMPLETE_COMMANDS)
  745. p = strrchr (word, '`');
  746. if (flags & (INPUT_COMPLETE_COMMANDS | INPUT_COMPLETE_VARIABLES))
  747. {
  748. q = strrchr (word, '$');
  749. /* don't substitute variable in \$ case */
  750. if (q != NULL && q != word && q[-1] == '\\')
  751. {
  752. size_t qlen;
  753. qlen = strlen (q);
  754. /* drop '\\' */
  755. memmove (q - 1, q, qlen + 1);
  756. /* adjust flags */
  757. flags &= ~INPUT_COMPLETE_VARIABLES;
  758. q = NULL;
  759. }
  760. }
  761. if (flags & INPUT_COMPLETE_HOSTNAMES)
  762. r = strrchr (word, '@');
  763. if (q && q[1] == '(' && (flags & INPUT_COMPLETE_COMMANDS))
  764. {
  765. if (q > p)
  766. p = str_get_next_char (q);
  767. q = NULL;
  768. }
  769. /* Command substitution? */
  770. if (p > q && p > r)
  771. {
  772. SHOW_C_CTX ("try_complete:cmd_backq_subst");
  773. matches = completion_matches (str_cget_next_char (p),
  774. command_completion_function,
  775. flags & (~INPUT_COMPLETE_FILENAMES));
  776. if (matches)
  777. *lc_start += str_get_next_char (p) - word;
  778. }
  779. /* Variable name? */
  780. else if (q > p && q > r)
  781. {
  782. SHOW_C_CTX ("try_complete:var_subst");
  783. matches = completion_matches (q, variable_completion_function, flags);
  784. if (matches)
  785. *lc_start += q - word;
  786. }
  787. /* Starts with '@', then look through the known hostnames for
  788. completion first. */
  789. else if (r > p && r > q)
  790. {
  791. SHOW_C_CTX ("try_complete:host_subst");
  792. matches = completion_matches (r, hostname_completion_function, flags);
  793. if (matches)
  794. *lc_start += r - word;
  795. }
  796. /* Starts with `~' and there is no slash in the word, then
  797. try completing this word as a username. */
  798. if (!matches && *word == '~' && (flags & INPUT_COMPLETE_USERNAMES) && !strchr (word, PATH_SEP))
  799. {
  800. SHOW_C_CTX ("try_complete:user_subst");
  801. matches = completion_matches (word, username_completion_function, flags);
  802. }
  803. /* And finally if this word is in a command position, then
  804. complete over possible command names, including aliases, functions,
  805. and command names. */
  806. if (!matches && in_command_position != 0)
  807. {
  808. SHOW_C_CTX ("try_complete:cmd_subst");
  809. matches =
  810. completion_matches (word, command_completion_function,
  811. flags & (~INPUT_COMPLETE_FILENAMES));
  812. }
  813. else if (!matches && (flags & INPUT_COMPLETE_FILENAMES))
  814. {
  815. if (is_cd)
  816. flags &= ~(INPUT_COMPLETE_FILENAMES | INPUT_COMPLETE_COMMANDS);
  817. SHOW_C_CTX ("try_complete:filename_subst_1");
  818. matches = completion_matches (word, filename_completion_function, flags);
  819. if (!matches && is_cd && *word != PATH_SEP && *word != '~')
  820. {
  821. q = text + *lc_start;
  822. for (p = text; *p && p < q && (*p == ' ' || *p == '\t'); str_next_char (&p));
  823. if (!strncmp (p, "cd", 2))
  824. for (p += 2; *p && p < q && (*p == ' ' || *p == '\t'); str_next_char (&p));
  825. if (p == q)
  826. {
  827. char *const cdpath_ref = g_strdup (getenv ("CDPATH"));
  828. char *cdpath = cdpath_ref;
  829. char c, *s;
  830. if (cdpath == NULL)
  831. c = 0;
  832. else
  833. c = ':';
  834. while (!matches && c == ':')
  835. {
  836. s = strchr (cdpath, ':');
  837. if (s == NULL)
  838. s = strchr (cdpath, 0);
  839. c = *s;
  840. *s = 0;
  841. if (*cdpath)
  842. {
  843. r = mc_build_filename (cdpath, word, NULL);
  844. SHOW_C_CTX ("try_complete:filename_subst_2");
  845. matches = completion_matches (r, filename_completion_function, flags);
  846. g_free (r);
  847. }
  848. *s = c;
  849. cdpath = str_get_next_char (s);
  850. }
  851. g_free (cdpath_ref);
  852. }
  853. }
  854. }
  855. g_free (word);
  856. return matches;
  857. }
  858. /* --------------------------------------------------------------------------------------------- */
  859. static int
  860. insert_text (WInput * in, char *text, ssize_t size)
  861. {
  862. int buff_len = str_length (in->buffer);
  863. size = min (size, (ssize_t) strlen (text)) + start - end;
  864. if (strlen (in->buffer) + size >= (size_t) in->current_max_size)
  865. {
  866. /* Expand the buffer */
  867. char *narea = g_try_realloc (in->buffer, in->current_max_size + size + in->field_width);
  868. if (narea != NULL)
  869. {
  870. in->buffer = narea;
  871. in->current_max_size += size + in->field_width;
  872. }
  873. }
  874. if (strlen (in->buffer) + 1 < (size_t) in->current_max_size)
  875. {
  876. if (size > 0)
  877. {
  878. int i = strlen (&in->buffer[end]);
  879. for (; i >= 0; i--)
  880. in->buffer[end + size + i] = in->buffer[end + i];
  881. }
  882. else if (size < 0)
  883. {
  884. char *p = in->buffer + end + size, *q = in->buffer + end;
  885. while (*q)
  886. *(p++) = *(q++);
  887. *p = 0;
  888. }
  889. memcpy (in->buffer + start, text, size - start + end);
  890. in->point += str_length (in->buffer) - buff_len;
  891. input_update (in, TRUE);
  892. end += size;
  893. }
  894. return size != 0;
  895. }
  896. /* --------------------------------------------------------------------------------------------- */
  897. static cb_ret_t
  898. query_callback (Dlg_head * h, Widget * sender, dlg_msg_t msg, int parm, void *data)
  899. {
  900. static char buff[MB_LEN_MAX] = "";
  901. static int bl = 0;
  902. switch (msg)
  903. {
  904. case DLG_KEY:
  905. switch (parm)
  906. {
  907. case KEY_LEFT:
  908. case KEY_RIGHT:
  909. bl = 0;
  910. h->ret_value = 0;
  911. dlg_stop (h);
  912. return MSG_HANDLED;
  913. case KEY_BACKSPACE:
  914. bl = 0;
  915. /* exit from completion list if input line is empty */
  916. if (end == 0)
  917. {
  918. h->ret_value = 0;
  919. dlg_stop (h);
  920. }
  921. /* Refill the list box and start again */
  922. else if (end == min_end)
  923. {
  924. end = str_get_prev_char (&input->buffer[end]) - input->buffer;
  925. input_handle_char (input, parm);
  926. h->ret_value = B_USER;
  927. dlg_stop (h);
  928. return MSG_HANDLED;
  929. }
  930. else
  931. {
  932. int new_end;
  933. int i;
  934. GList *e;
  935. new_end = str_get_prev_char (&input->buffer[end]) - input->buffer;
  936. for (i = 0, e = ((WListbox *) h->current->data)->list;
  937. e != NULL; i++, e = g_list_next (e))
  938. {
  939. WLEntry *le = (WLEntry *) e->data;
  940. if (strncmp (input->buffer + start, le->text, new_end - start) == 0)
  941. {
  942. listbox_select_entry ((WListbox *) h->current->data, i);
  943. end = new_end;
  944. input_handle_char (input, parm);
  945. send_message ((Widget *) h->current->data, WIDGET_DRAW, 0);
  946. break;
  947. }
  948. }
  949. }
  950. return MSG_HANDLED;
  951. default:
  952. if (parm < 32 || parm > 255)
  953. {
  954. bl = 0;
  955. if (input_key_is_in_map (input, parm) != 2)
  956. return MSG_NOT_HANDLED;
  957. if (end == min_end)
  958. return MSG_HANDLED;
  959. /* This means we want to refill the list box and start again */
  960. h->ret_value = B_USER;
  961. dlg_stop (h);
  962. return MSG_HANDLED;
  963. }
  964. else
  965. {
  966. GList *e;
  967. int i;
  968. int need_redraw = 0;
  969. int low = 4096;
  970. char *last_text = NULL;
  971. buff[bl++] = (char) parm;
  972. buff[bl] = '\0';
  973. switch (str_is_valid_char (buff, bl))
  974. {
  975. case -1:
  976. bl = 0;
  977. /* fallthrough */
  978. case -2:
  979. return MSG_HANDLED;
  980. }
  981. for (i = 0, e = ((WListbox *) h->current->data)->list;
  982. e != NULL; i++, e = g_list_next (e))
  983. {
  984. WLEntry *le = (WLEntry *) e->data;
  985. if (strncmp (input->buffer + start, le->text, end - start) == 0
  986. && strncmp (&le->text[end - start], buff, bl) == 0)
  987. {
  988. if (need_redraw == 0)
  989. {
  990. need_redraw = 1;
  991. listbox_select_entry ((WListbox *) h->current->data, i);
  992. last_text = le->text;
  993. }
  994. else
  995. {
  996. char *si, *sl;
  997. int si_num = 0;
  998. int sl_num = 0;
  999. /* count symbols between start and end */
  1000. for (si = le->text + start; si < le->text + end;
  1001. str_next_char (&si), si_num++)
  1002. ;
  1003. for (sl = last_text + start; sl < last_text + end;
  1004. str_next_char (&sl), sl_num++)
  1005. ;
  1006. /* pointers to next symbols */
  1007. si = &le->text[str_offset_to_pos (le->text, ++si_num)];
  1008. sl = &last_text[str_offset_to_pos (last_text, ++sl_num)];
  1009. while (si[0] != '\0' && sl[0] != '\0')
  1010. {
  1011. char *nexti, *nextl;
  1012. nexti = str_get_next_char (si);
  1013. nextl = str_get_next_char (sl);
  1014. if (nexti - si != nextl - sl || strncmp (si, sl, nexti - si) != 0)
  1015. break;
  1016. si = nexti;
  1017. sl = nextl;
  1018. si_num++;
  1019. }
  1020. last_text = le->text;
  1021. si = &last_text[str_offset_to_pos (last_text, si_num)];
  1022. if (low > si - last_text)
  1023. low = si - last_text;
  1024. need_redraw = 2;
  1025. }
  1026. }
  1027. }
  1028. if (need_redraw == 2)
  1029. {
  1030. insert_text (input, last_text, low);
  1031. send_message ((Widget *) h->current->data, WIDGET_DRAW, 0);
  1032. }
  1033. else if (need_redraw == 1)
  1034. {
  1035. h->ret_value = B_ENTER;
  1036. dlg_stop (h);
  1037. }
  1038. bl = 0;
  1039. }
  1040. return MSG_HANDLED;
  1041. }
  1042. break;
  1043. default:
  1044. return default_dlg_callback (h, sender, msg, parm, data);
  1045. }
  1046. }
  1047. /* --------------------------------------------------------------------------------------------- */
  1048. /** Returns 1 if the user would like to see us again */
  1049. static int
  1050. complete_engine (WInput * in, int what_to_do)
  1051. {
  1052. if (in->completions != NULL && str_offset_to_pos (in->buffer, in->point) != end)
  1053. input_free_completions (in);
  1054. if (in->completions == NULL)
  1055. {
  1056. char *s;
  1057. end = str_offset_to_pos (in->buffer, in->point);
  1058. s = in->buffer;
  1059. if (in->point != 0)
  1060. {
  1061. /* get symbol before in->point */
  1062. size_t i;
  1063. for (i = in->point - 1; i > 0; i--)
  1064. str_next_char (&s);
  1065. }
  1066. for (; s >= in->buffer; str_prev_char (&s))
  1067. {
  1068. start = s - in->buffer;
  1069. if (strchr (" \t;|<>", *s) != NULL)
  1070. break;
  1071. }
  1072. if (start < end)
  1073. {
  1074. str_next_char (&s);
  1075. start = s - in->buffer;
  1076. }
  1077. in->completions = try_complete (in->buffer, &start, &end, in->completion_flags);
  1078. }
  1079. if (in->completions != NULL)
  1080. {
  1081. if (what_to_do & DO_INSERTION || ((what_to_do & DO_QUERY) && !in->completions[1]))
  1082. {
  1083. char *lc_complete = in->completions[0];
  1084. if (insert_text (in, lc_complete, strlen (lc_complete)))
  1085. {
  1086. if (in->completions[1])
  1087. tty_beep ();
  1088. else
  1089. input_free_completions (in);
  1090. }
  1091. else
  1092. tty_beep ();
  1093. }
  1094. if ((what_to_do & DO_QUERY) && in->completions && in->completions[1])
  1095. {
  1096. int maxlen = 0, i, count = 0;
  1097. int x, y, w, h;
  1098. int start_x, start_y;
  1099. char **p, *q;
  1100. Dlg_head *query_dlg;
  1101. WListbox *query_list;
  1102. for (p = in->completions + 1; *p != NULL; count++, p++)
  1103. {
  1104. i = str_term_width1 (*p);
  1105. if (i > maxlen)
  1106. maxlen = i;
  1107. }
  1108. start_x = in->widget.x;
  1109. start_y = in->widget.y;
  1110. if (start_y - 2 >= count)
  1111. {
  1112. y = start_y - 2 - count;
  1113. h = 2 + count;
  1114. }
  1115. else
  1116. {
  1117. if (start_y >= LINES - start_y - 1)
  1118. {
  1119. y = 0;
  1120. h = start_y;
  1121. }
  1122. else
  1123. {
  1124. y = start_y + 1;
  1125. h = LINES - start_y - 1;
  1126. }
  1127. }
  1128. x = start - in->term_first_shown - 2 + start_x;
  1129. w = maxlen + 4;
  1130. if (x + w > COLS)
  1131. x = COLS - w;
  1132. if (x < 0)
  1133. x = 0;
  1134. if (x + w > COLS)
  1135. w = COLS;
  1136. input = in;
  1137. min_end = end;
  1138. query_height = h;
  1139. query_width = w;
  1140. query_dlg = create_dlg (TRUE, y, x, query_height, query_width,
  1141. dialog_colors, query_callback, NULL,
  1142. "[Completion]", NULL, DLG_COMPACT);
  1143. query_list = listbox_new (1, 1, h - 2, w - 2, FALSE, NULL);
  1144. add_widget (query_dlg, query_list);
  1145. for (p = in->completions + 1; *p; p++)
  1146. listbox_add_item (query_list, LISTBOX_APPEND_AT_END, 0, *p, NULL);
  1147. run_dlg (query_dlg);
  1148. q = NULL;
  1149. if (query_dlg->ret_value == B_ENTER)
  1150. {
  1151. listbox_get_current (query_list, &q, NULL);
  1152. if (q)
  1153. insert_text (in, q, strlen (q));
  1154. }
  1155. if (q || end != min_end)
  1156. input_free_completions (in);
  1157. i = query_dlg->ret_value; /* B_USER if user wants to start over again */
  1158. destroy_dlg (query_dlg);
  1159. if (i == B_USER)
  1160. return 1;
  1161. }
  1162. }
  1163. else
  1164. tty_beep ();
  1165. return 0;
  1166. }
  1167. /* --------------------------------------------------------------------------------------------- */
  1168. /*** public functions ****************************************************************************/
  1169. /* --------------------------------------------------------------------------------------------- */
  1170. /* declared in lib/widget/input.h */
  1171. void
  1172. complete (WInput * in)
  1173. {
  1174. int engine_flags;
  1175. if (!str_is_valid_string (in->buffer))
  1176. return;
  1177. if (in->completions != NULL)
  1178. engine_flags = DO_QUERY;
  1179. else
  1180. {
  1181. engine_flags = DO_INSERTION;
  1182. if (mc_global.widget.show_all_if_ambiguous)
  1183. engine_flags |= DO_QUERY;
  1184. }
  1185. while (complete_engine (in, engine_flags))
  1186. ;
  1187. }
  1188. /* --------------------------------------------------------------------------------------------- */