input_complete.c 41 KB

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