summaryrefslogtreecommitdiff
path: root/mu/shell.c
blob: 9497b3d02e5557cd94d35006ac9339ee1b9f152e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 2010 Free Software Foundation, Inc.

   GNU Mailutils is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   GNU Mailutils is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Mailutils.  If not, see <http://www.gnu.org/licenses/>. */

#if defined(HAVE_CONFIG_H)
# include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <mailutils/mailutils.h>
#include <mailutils/tls.h>
#include "mailutils/libargp.h"
#include "mu.h"
#include "xalloc.h"

#ifdef WITH_READLINE
# include <readline/readline.h>
# include <readline/history.h>
#endif

char *mutool_shell_prompt;
mu_vartab_t mutool_prompt_vartab;
int mutool_shell_interactive;
mu_stream_t mustrin, mustrout;

static char *
expand_prompt ()
{
  char *str;
  
  if (!mutool_prompt_vartab
      || mu_vartab_expand (mutool_prompt_vartab, mutool_shell_prompt, &str))
    str = strdup (mutool_shell_prompt);
  return str;
}


static int shell_exit (int, char **);
static int shell_help (int, char **);
static int shell_prompt (int, char **);
#ifdef WITH_READLINE
static int shell_history (int, char **);
#endif

struct mutool_command default_comtab[] = {
  { "prompt",   -1, -1, shell_prompt,
    N_("STRING"),
    N_("set command prompt") },
  { "exit",       1, 1, shell_exit,    NULL,        N_("exit program") },
  { "help",       1, 2, shell_help,
    N_("[COMMAND]"),
    N_("display this text") },
  { "?",          1, 1, shell_help,
    N_("[COMMAND]"),
    N_("synonym for `help'") },
#ifdef WITH_READLINE
  { "history",    1, 1, shell_history,
    NULL,
    N_("show command history") },
#endif
  { NULL }
};

#define DESCRCOL 25
#define NUMCOLS  80
#define DESCRWIDTH (NUMCOLS - DESCRCOL)

/* Print a single comtab entry */
static void
print_comtab (mu_stream_t stream, struct mutool_command *tab)
{
  size_t size = 0;
  const char *text;
  
  if (tab->docstring == NULL)
    return;

  mu_stream_printf (stream, "%s ", tab->name);
  size += strlen (tab->name) + 1;
  if (tab->argdoc)
    {
      text = gettext (tab->argdoc);
      mu_stream_printf (stream, "%s", text);
      size += strlen (text);
    }
  if (size >= DESCRCOL)
    mu_stream_printf (stream, "\n%-*s", DESCRCOL, "");
  else
    mu_stream_printf (stream, "%-*s", (int) (DESCRCOL - size), "");

  text = gettext (tab->docstring);
  size = strlen (text);
  
  while (*text)
    {
      size_t len = size;
      if (len > DESCRWIDTH)
	{
	  /* Fold the text */
	  size_t n = 0;
	  
	  while (n < len)
	    {
	      size_t delta;
	      char *p;
	      
	      p = mu_str_skip_cset_comp (text + n, " \t");
	      delta = p - (text + n);
	      if (n + delta > DESCRWIDTH)
		break;
	      n += delta;
	      
	      p = mu_str_skip_cset (text + n, " \t");
	      delta = p - (text + n);
	      if (n + delta > DESCRWIDTH)
		break;
	      n += delta;
	    }

	  len = n;
	}
      mu_stream_write (stream, text, len, NULL);
      text += len;
      size -= len;
      mu_stream_write (stream, "\n", 1, NULL);
      if (size)
	mu_stream_printf (stream, "%-*s", DESCRCOL, "");
    }
}  

/* Print a single comtab entry.
   FIXME: Way too primitive. Rewrite. */
int
print_help (mu_stream_t stream, struct mutool_command *tab, size_t n)
{
  if (n)
    {
      for (; n > 0 && tab->name; tab++, n--)
	print_comtab (stream, tab);
    }
  else
    {
      for (; tab->name; tab++)
	print_comtab (stream, tab);
    }
  return 0;
}

/* Print all commands from TAB matching NAME.
   FIXME: Way too primitive. Rewrite. */
void
list_commands (struct mutool_command *tab, const char *name)
{
  size_t namelen = strlen (name);
  int printed = 0;
  
  for (; tab->name; tab++)
    {
      /* Print in six columns. */
      if (printed == 6)
	{
	  printed = 0;
	  mu_stream_printf (mustrout, "\n");
	}
      if (mu_c_strncasecmp (tab->name, name, namelen) == 0)
	{
	  mu_stream_printf (mustrout, "%s\t", tab->name);
	  printed++;
	}
    }
  if (printed && printed < 6)
    mu_stream_printf (mustrout, "\n");
}

static struct mutool_command *
simple_find_command (struct mutool_command *cp, const char *name)
{
  for (; cp->name; cp++)
    if (strcmp (cp->name, name) == 0)
      return cp;
  return NULL;
}


static struct mutool_command *shell_comtab;
static size_t user_command_count;

static struct mutool_command *
find_command (const char *name)
{
  return simple_find_command (shell_comtab, name);
}

/* Print out help for ARG, or for all of the commands if ARG is
   not present. */
int
shell_help (int argc, char **argv)
{
  char *name = argv[1];
  
  if (name)
    {
      struct mutool_command *com = find_command (argv[1]);

      if (com)
	print_comtab (mustrout, com);
      else
	{
	  mu_stream_printf (mustrout,
			    "No commands match `%s'.  Possibilties are:\n",
			    name);
	  list_commands (shell_comtab, name);
	}
    }
  else
    {
      mu_stream_t str = mutool_open_pager ();
      print_help (str, shell_comtab, user_command_count);
      mu_stream_printf (str, "\n");
      print_help (str, shell_comtab + user_command_count, 0);
      mu_stream_destroy (&str);
    }
  return 0;
}

static int
shell_prompt (int argc, char **argv)
{
  int quote;
  size_t size;
  
  free (mutool_shell_prompt);
  size = mu_argcv_quoted_length (argv[1], &quote);
  mutool_shell_prompt = xmalloc (size + 1);
  mu_argcv_unquote_copy (mutool_shell_prompt, argv[1], size);
  return 0;
}

mu_stream_t
mutool_open_pager ()
{
  char *pager;
  if (mutool_shell_interactive && (pager = getenv ("PAGER")) != NULL)
    {
      mu_stream_t stream;
      int rc = mu_prog_stream_create (&stream, pager, MU_STREAM_WRITE);
      if (rc == 0)
	return stream;
      mu_error (_("cannot start pager: %s"), mu_strerror (rc));
    }
  mu_stream_ref (mustrout);
  return mustrout;
}


#ifdef WITH_READLINE
#define HISTFILE_PREFIX "~/.mu_"
#define HISTFILE_SUFFIX "_history"

static char *
get_history_file_name ()
{
  static char *filename = NULL;

  if (!filename)
    {
      char *hname;
      
      hname = xmalloc(sizeof HISTFILE_PREFIX + strlen (rl_readline_name) +
		      sizeof HISTFILE_SUFFIX - 1);
      strcpy (hname, "~/.mu_");
      strcat (hname, rl_readline_name);
      strcat (hname, HISTFILE_SUFFIX);
      filename = mu_tilde_expansion (hname, "/", NULL);
      free(hname);
    }
  return filename;
}

/* Interface to Readline Completion */

static char *shell_command_generator (const char *, int);
static char **shell_completion (char *, int, int);

/* Tell the GNU Readline library how to complete.  We want to try to complete
   on command names if this is the first word in the line, or on filenames
   if not. */
void
mutool_initialize_readline (const char *name)
{
  /* Allow conditional parsing of the ~/.inputrc file. */
  rl_readline_name = (char *) name;
  rl_attempted_completion_function = (CPPFunction *) shell_completion;
  read_history (get_history_file_name ());
}

static void
finish_readline ()
{
  write_history (get_history_file_name());
}

/* Attempt to complete on the contents of TEXT.  START and END bound the
   region of rl_line_buffer that contains the word to complete.  TEXT is
   the word to complete.  We can use the entire contents of rl_line_buffer
   in case we want to do some simple parsing.  Return the array of matches,
   or NULL if there aren't any. */
static char **
shell_completion (char *text, int start, int end MU_ARG_UNUSED)
{
  char **matches;

  matches = (char **) NULL;

  /* If this word is at the start of the line, then it is a command
     to complete.  Otherwise it is the name of a file in the current
     directory. */
  if (start == 0)
    matches = rl_completion_matches (text, shell_command_generator);

  return (matches);
}

/* Generator function for command completion.  STATE lets us know whether
   to start from scratch; without any state (i.e. STATE == 0), then we
   start at the top of the list. */
static char *
shell_command_generator (const char *text, int state)
{
  const char *name;
  static int len;
  static struct mutool_command *cmd;

  /* If this is a new word to complete, initialize now.  This includes
     saving the length of TEXT for efficiency, and initializing the index
     variable to 0. */
  if (!state)
    {
      cmd = shell_comtab;
      len = strlen (text);
    }

  if (!cmd->name)
    return NULL;
    
  
  /* Return the next name which partially matches from the command list. */
  while ((name = cmd->name))
    {
      cmd++;
      if (strncmp (name, text, len) == 0)
	return xstrdup (name);
    }

  /* If no names matched, then return NULL. */
  return NULL;
}

static char *pre_input_line;

static int
pre_input (void)
{
  rl_insert_text (pre_input_line);
  free (pre_input_line);
  rl_pre_input_hook = NULL;
  rl_redisplay ();
  return 0;
}

static int
retrieve_history (char *str)
{
  char *out;
  int rc;

  rc = history_expand (str, &out);
  switch (rc)
    {
    case -1:
      mu_error ("%s", out);
      free (out);
      return 1;

    case 0:
      break;

    case 1:
      pre_input_line = out;
      rl_pre_input_hook = pre_input;
      return 1;

    case 2:
      mu_stream_printf (mustrout, "%s\n", out);
      free (out);
      return 1;
    }
  return 0;
}

static int
shell_history (int argc, char **argv)
{
  int i;
  HIST_ENTRY **hlist;
  mu_stream_t out = mutool_open_pager ();
  
  hlist = history_list ();
  for (i = 0; i < history_length; i++)
    mu_stream_printf (out, "%4d) %s\n", i + 1, hlist[i]->line);

  mu_stream_destroy (&out);
  return 0;
}

#else
# define finish_readline()
# define mutool_initialize_readline (const char *name)

char *
readline (char *prompt)
{
  static size_t size = 0;
  static char *buf = NULL;

  if (prompt)
    {
      mu_stream_printf (mustrout, "%s", prompt);
      fflush (stdout);
    }
  if (mu_stream_getline (mustrin, &buf, &size, &n) || n == 0)
    {
      free (buf);
      buf = NULL;
      size = 0;
      return NULL;
    }
  return buf;
}

void
add_history (const char *s MU_ARG_UNUSED)
{
}
#endif

/* Parse and execute a command line. */
int
execute_line (char *line)
{
  int argc;
  char **argv;
  int status = 0;

  if (mu_argcv_get (line, NULL, "#", &argc, &argv))
    {
      mu_error("cannot parse input line");
      return 0;
    }

  if (argc >= 0)
    {
      struct mutool_command *cmd = find_command (argv[0]);
      
      if (!cmd)
	mu_error ("%s: no such command.", argv[0]);
      else if (cmd->argmin > 0 && argc < cmd->argmin)
	mu_error ("%s: too few arguments", argv[0]);
      else if (cmd->argmax > 0 && argc > cmd->argmax)
	mu_error ("%s: too many arguments", argv[0]);
      else
	{
	  if (cmd->argmin <= 0 && argc != 2)
	    {
	      char *word = mu_str_skip_class (line, MU_CTYPE_SPACE);
	      char *arg = mu_str_skip_class_comp (word, MU_CTYPE_SPACE);
	      if (*arg)
		{
		  *arg++ = 0;
		  arg = mu_str_skip_class (arg, MU_CTYPE_SPACE);
		}
	      
	      mu_argcv_free (argc, argv);
	      argc = 2;
	      argv = xcalloc (argc + 1, sizeof (argv[0]));
	      argv[0] = xstrdup (word);
	      argv[1] = xstrdup (arg);
	      argv[2] = NULL;
	    }
	  status = cmd->func (argc, argv);
	}
    }
  mu_argcv_free (argc, argv);
  return status;
}

static char *
input_line_interactive ()
{
  char *p = expand_prompt ();
  char *line = readline (p);
  free (p);
  return line;
}

static char *
input_line_script ()
{
  size_t size = 0, n;
  char *buf = NULL;

  if (mu_stream_getline (mustrin, &buf, &size, &n) || n == 0)
    return NULL;
  return buf;
}

static int done;

static int
shell_exit (int argc MU_ARG_UNUSED, char **argv MU_ARG_UNUSED)
{
  done = 1;
  return 0;
}
  
int
mutool_shell (const char *name, struct mutool_command *cmd)
{
  int rc;
  size_t n;
  char *(*input_line) ();

  rc = mu_stdio_stream_create (&mustrin, MU_STDIN_FD,
			       MU_STREAM_READ);
  if (rc)
    {
      mu_diag_funcall (MU_DIAG_ERROR, "mu_stdio_stream_create",
		       "MU_STDIN_FD", rc);
      return 1;
    } 
 
  rc = mu_stdio_stream_create (&mustrout, MU_STDOUT_FD,
			       MU_STREAM_WRITE);
  if (rc)
    {
      mu_diag_funcall (MU_DIAG_ERROR, "mu_stdio_stream_create",
		       "MU_STDOUT_FD", rc);
      return 1;
    } 
 
  mutool_shell_interactive = isatty (0);
  input_line = mutool_shell_interactive ?
                             input_line_interactive : input_line_script;

  for (n = 0; cmd[n].name; n++)
    ;

  user_command_count = n;
  shell_comtab = xcalloc (n + MU_ARRAY_SIZE (default_comtab),
			  sizeof (shell_comtab[0]));
  memcpy (shell_comtab, cmd, n * sizeof (shell_comtab[0]));
  memcpy (shell_comtab + n, default_comtab, sizeof (default_comtab));

  mutool_initialize_readline (name);
  while (!done)
    {
      char *s, *line = input_line ();
      if (!line)
	break;

      /* Remove leading and trailing whitespace from the line.
         Then, if there is anything left, add it to the history list
         and execute it. */
      s = mu_str_stripws (line);

      if (*s)
	{
	  int status;

#ifdef WITH_READLINE
	  if (mutool_shell_interactive)
	    {
	      if (retrieve_history (s))
		continue;
	      add_history (s);
	    }
#endif

	  status = execute_line (s);
	  if (status != 0)
	    mu_error ("Error: %s", mu_strerror (status));
	}

      free (line);
    }
  if (mutool_shell_interactive)
    finish_readline ();
  mu_stream_destroy (&mustrin);
  mu_stream_destroy (&mustrout);
  return 0;
}

Return to:

Send suggestions and report system problems to the System administrator.