1 /**
2  * @file
3  * Generate the help-page and GUI display it
4  *
5  * @authors
6  * Copyright (C) 1996-2000,2009 Michael R. Elkins <me@mutt.org>
7  *
8  * @copyright
9  * This program is free software: you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License as published by the Free Software
11  * Foundation, either version 2 of the License, or (at your option) any later
12  * version.
13  *
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License along with
20  * this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 /**
24  * @page neo_help Generate the help-page and GUI display it
25  *
26  * Generate and help-page and GUI display it
27  */
28 
29 #include "config.h"
30 #include <stddef.h>
31 #include <limits.h>
32 #include <stdbool.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <wchar.h>
36 #include "mutt/lib.h"
37 #include "config/lib.h"
38 #include "core/lib.h"
39 #include "gui/lib.h"
40 #include "menu/lib.h"
41 #include "pager/lib.h"
42 #include "functions.h"
43 #include "keymap.h"
44 #include "muttlib.h"
45 #include "opcodes.h"
46 #include "protos.h" // IWYU pragma: keep
47 
48 /**
49  * help_lookup_function - Find a keybinding for an operation
50  * @param op   Operation, e.g. OP_DELETE
51  * @param menu Current Menu, e.g. #MENU_PAGER
52  * @retval ptr  Key binding
53  * @retval NULL No key binding found
54  */
help_lookup_function(int op,enum MenuType menu)55 static const struct Binding *help_lookup_function(int op, enum MenuType menu)
56 {
57   const struct Binding *map = NULL;
58 
59   if (menu != MENU_PAGER)
60   {
61     /* first look in the generic map for the function */
62     for (int i = 0; OpGeneric[i].name; i++)
63       if (OpGeneric[i].op == op)
64         return &OpGeneric[i];
65   }
66 
67   map = km_get_table(menu);
68   if (map)
69   {
70     for (int i = 0; map[i].name; i++)
71       if (map[i].op == op)
72         return &map[i];
73   }
74 
75   return NULL;
76 }
77 
78 /**
79  * print_macro - Print a macro string to a file
80  * @param[in]  fp       File to write to
81  * @param[in]  maxwidth Maximum width in screen columns
82  * @param[out] macro    Macro string
83  * @retval num Number of screen columns used
84  *
85  * The `macro` pointer is move past the string we've printed
86  */
print_macro(FILE * fp,int maxwidth,const char ** macro)87 static int print_macro(FILE *fp, int maxwidth, const char **macro)
88 {
89   int n = maxwidth;
90   wchar_t wc;
91   size_t k;
92   size_t len = mutt_str_len(*macro);
93   mbstate_t mbstate1, mbstate2;
94 
95   memset(&mbstate1, 0, sizeof(mbstate1));
96   memset(&mbstate2, 0, sizeof(mbstate2));
97   for (; len && (k = mbrtowc(&wc, *macro, len, &mbstate1)); *macro += k, len -= k)
98   {
99     if ((k == (size_t) (-1)) || (k == (size_t) (-2)))
100     {
101       if (k == (size_t) (-1))
102         memset(&mbstate1, 0, sizeof(mbstate1));
103       k = (k == (size_t) (-1)) ? 1 : len;
104       wc = ReplacementChar;
105     }
106     /* glibc-2.1.3's wcwidth() returns 1 for unprintable chars! */
107     const int w = wcwidth(wc);
108     if (IsWPrint(wc) && (w >= 0))
109     {
110       if (w > n)
111         break;
112       n -= w;
113       {
114         char buf[MB_LEN_MAX * 2];
115         size_t n1, n2;
116         if (((n1 = wcrtomb(buf, wc, &mbstate2)) != (size_t) (-1)) &&
117             ((n2 = wcrtomb(buf + n1, 0, &mbstate2)) != (size_t) (-1)))
118         {
119           fputs(buf, fp);
120         }
121       }
122     }
123     else if ((wc < 0x20) || (wc == 0x7f))
124     {
125       if (n < 2)
126         break;
127       n -= 2;
128       if (wc == '\033') // Escape
129         fprintf(fp, "\\e");
130       else if (wc == '\n')
131         fprintf(fp, "\\n");
132       else if (wc == '\r')
133         fprintf(fp, "\\r");
134       else if (wc == '\t')
135         fprintf(fp, "\\t");
136       else
137         fprintf(fp, "^%c", (char) ((wc + '@') & 0x7f));
138     }
139     else
140     {
141       if (n < 1)
142         break;
143       n -= 1;
144       fprintf(fp, "?");
145     }
146   }
147   return maxwidth - n;
148 }
149 
150 /**
151  * get_wrapped_width - Wrap a string at a sensible place
152  * @param t   String to wrap
153  * @param wid Maximum width
154  * @retval num Break after this many characters
155  *
156  * If the string's too long, look for some whitespace to break at.
157  */
get_wrapped_width(const char * t,size_t wid)158 static int get_wrapped_width(const char *t, size_t wid)
159 {
160   wchar_t wc;
161   size_t k;
162   size_t m, n;
163   size_t len = mutt_str_len(t);
164   const char *s = t;
165   mbstate_t mbstate;
166 
167   memset(&mbstate, 0, sizeof(mbstate));
168   for (m = wid, n = 0; len && (k = mbrtowc(&wc, s, len, &mbstate)) && (n <= wid);
169        s += k, len -= k)
170   {
171     if (*s == ' ')
172       m = n;
173     if ((k == (size_t) (-1)) || (k == (size_t) (-2)))
174     {
175       if (k == (size_t) (-1))
176         memset(&mbstate, 0, sizeof(mbstate));
177       k = (k == (size_t) (-1)) ? 1 : len;
178       wc = ReplacementChar;
179     }
180     if (!IsWPrint(wc))
181       wc = '?';
182     n += wcwidth(wc);
183   }
184   if (n > wid)
185     n = m;
186   else
187     n = wid;
188   return n;
189 }
190 
191 /**
192  * pad - Write some padding to a file
193  * @param fp  File to write to
194  * @param col Current screen column
195  * @param i   Screen column to pad until
196  * @retval num
197  * - `i` - Padding was added
198  * - `col` - Content was already wider than col
199  */
pad(FILE * fp,int col,int i)200 static int pad(FILE *fp, int col, int i)
201 {
202   if (col < i)
203   {
204     char fmt[32] = { 0 };
205     snprintf(fmt, sizeof(fmt), "%%-%ds", i - col);
206     fprintf(fp, fmt, "");
207     return i;
208   }
209   fputc(' ', fp);
210   return col + 1;
211 }
212 
213 /**
214  * format_line - Write a formatted line to a file
215  * @param fp      File to write to
216  * @param ismacro Layout mode, see below
217  * @param t1      Text part 1
218  * @param t2      Text part 2
219  * @param t3      Text part 3
220  * @param wraplen Width to wrap to
221  *
222  * Assemble the three columns of text.
223  *
224  * `ismacro` can be:
225  * *  1 : Macro with a description
226  * *  0 : Non-macro
227  * * -1 : Macro with no description
228  */
format_line(FILE * fp,int ismacro,const char * t1,const char * t2,const char * t3,int wraplen)229 static void format_line(FILE *fp, int ismacro, const char *t1, const char *t2,
230                         const char *t3, int wraplen)
231 {
232   int col;
233   int col_b;
234 
235   fputs(t1, fp);
236 
237   /* don't try to press string into one line with less than 40 characters. */
238   bool split = (wraplen < 40);
239   if (split)
240   {
241     col = 0;
242     col_b = 1024;
243     fputc('\n', fp);
244   }
245   else
246   {
247     const int col_a = (wraplen > 83) ? (wraplen - 32) >> 2 : 12;
248     col_b = (wraplen > 49) ? (wraplen - 10) >> 1 : 19;
249     col = pad(fp, mutt_strwidth(t1), col_a);
250   }
251 
252   const char *const c_pager = cs_subset_string(NeoMutt->sub, "pager");
253   if (ismacro > 0)
254   {
255     if (!c_pager || mutt_str_equal(c_pager, "builtin"))
256       fputs("_\010", fp); // Ctrl-H (backspace)
257     fputs("M ", fp);
258     col += 2;
259 
260     if (!split)
261     {
262       col += print_macro(fp, col_b - col - 4, &t2);
263       if (mutt_strwidth(t2) > col_b - col)
264         t2 = "...";
265     }
266   }
267 
268   col += print_macro(fp, col_b - col - 1, &t2);
269   if (split)
270     fputc('\n', fp);
271   else
272     col = pad(fp, col, col_b);
273 
274   if (split)
275   {
276     print_macro(fp, 1024, &t3);
277     fputc('\n', fp);
278   }
279   else
280   {
281     while (*t3)
282     {
283       int n = wraplen - col;
284 
285       if (ismacro >= 0)
286       {
287         SKIPWS(t3);
288         n = get_wrapped_width(t3, n);
289       }
290 
291       n = print_macro(fp, n, &t3);
292 
293       if (*t3)
294       {
295         if (mutt_str_equal(c_pager, "builtin"))
296         {
297           n += col - wraplen;
298           const bool c_markers = cs_subset_bool(NeoMutt->sub, "markers");
299           if (c_markers)
300             n++;
301         }
302         else
303         {
304           fputc('\n', fp);
305           n = 0;
306         }
307         col = pad(fp, n, col_b);
308       }
309     }
310   }
311 
312   fputc('\n', fp);
313 }
314 
315 /**
316  * dump_menu - Write all the key bindings to a file
317  * @param fp      File to write to
318  * @param menu    Current Menu, e.g. #MENU_PAGER
319  * @param wraplen Width to wrap to
320  */
dump_menu(FILE * fp,enum MenuType menu,int wraplen)321 static void dump_menu(FILE *fp, enum MenuType menu, int wraplen)
322 {
323   struct Keymap *map = NULL;
324   const struct Binding *b = NULL;
325   char buf[128];
326 
327   STAILQ_FOREACH(map, &Keymaps[menu], entries)
328   {
329     if (map->op != OP_NULL)
330     {
331       km_expand_key(buf, sizeof(buf), map);
332 
333       if (map->op == OP_MACRO)
334       {
335         if (map->desc)
336           format_line(fp, 1, buf, map->macro, map->desc, wraplen);
337         else
338           format_line(fp, -1, buf, "macro", map->macro, wraplen);
339       }
340       else
341       {
342         b = help_lookup_function(map->op, menu);
343         format_line(fp, 0, buf, b ? b->name : "UNKNOWN",
344                     b ? _(OpStrings[b->op][1]) : _("ERROR: please report this bug"), wraplen);
345       }
346     }
347   }
348 }
349 
350 /**
351  * is_bound - Does a function have a keybinding?
352  * @param km_list Keymap to examine
353  * @param op      Operation, e.g. OP_DELETE
354  * @retval true A key is bound to that operation
355  */
is_bound(struct KeymapList * km_list,int op)356 static bool is_bound(struct KeymapList *km_list, int op)
357 {
358   struct Keymap *map = NULL;
359   STAILQ_FOREACH(map, km_list, entries)
360   {
361     if (map->op == op)
362       return true;
363   }
364   return false;
365 }
366 
367 /**
368  * dump_unbound - Write out all the operations with no key bindings
369  * @param fp      File to write to
370  * @param funcs   All the bindings for the current menu
371  * @param km_list First key map to consider
372  * @param aux     Second key map to consider
373  * @param wraplen Width to wrap to
374  */
dump_unbound(FILE * fp,const struct Binding * funcs,struct KeymapList * km_list,struct KeymapList * aux,int wraplen)375 static void dump_unbound(FILE *fp, const struct Binding *funcs,
376                          struct KeymapList *km_list, struct KeymapList *aux, int wraplen)
377 {
378   for (int i = 0; funcs[i].name; i++)
379   {
380     if (!is_bound(km_list, funcs[i].op) && (!aux || !is_bound(aux, funcs[i].op)))
381       format_line(fp, 0, funcs[i].name, "", _(OpStrings[funcs[i].op][1]), wraplen);
382   }
383 }
384 
385 /**
386  * mutt_help - Display the help menu
387  * @param menu    Current Menu
388  */
mutt_help(enum MenuType menu)389 void mutt_help(enum MenuType menu)
390 {
391   const int wraplen = AllDialogsWindow->state.cols;
392   char banner[128];
393   FILE *fp = NULL;
394 
395   /* We don't use the buffer pool because of the extended lifetime of t */
396   struct Buffer t = mutt_buffer_make(PATH_MAX);
397   mutt_buffer_mktemp(&t);
398 
399   const struct Binding *funcs = km_get_table(menu);
400   const char *desc = mutt_map_get_name(menu, MenuNames);
401   if (!desc)
402     desc = _("<UNKNOWN>");
403 
404   struct PagerData pdata = { 0 };
405   struct PagerView pview = { &pdata };
406 
407   pview.mode = PAGER_MODE_HELP;
408   pview.flags = MUTT_PAGER_RETWINCH | MUTT_PAGER_MARKER | MUTT_PAGER_NSKIP | MUTT_PAGER_NOWRAP;
409 
410   do
411   {
412     fp = mutt_file_fopen(mutt_buffer_string(&t), "w");
413     if (!fp)
414     {
415       mutt_perror(mutt_buffer_string(&t));
416       goto cleanup;
417     }
418 
419     dump_menu(fp, menu, wraplen);
420     if ((menu != MENU_EDITOR) && (menu != MENU_PAGER))
421     {
422       fprintf(fp, "\n%s\n\n", _("Generic bindings:"));
423       dump_menu(fp, MENU_GENERIC, wraplen);
424     }
425 
426     fprintf(fp, "\n%s\n\n", _("Unbound functions:"));
427     if (funcs)
428       dump_unbound(fp, funcs, &Keymaps[menu], NULL, wraplen);
429     if (menu != MENU_PAGER)
430       dump_unbound(fp, OpGeneric, &Keymaps[MENU_GENERIC], &Keymaps[menu], wraplen);
431 
432     mutt_file_fclose(&fp);
433 
434     snprintf(banner, sizeof(banner), _("Help for %s"), desc);
435     pdata.fname = mutt_buffer_string(&t);
436     pview.banner = banner;
437   } while (mutt_do_pager(&pview, NULL) == OP_REFORMAT_WINCH);
438 
439 cleanup:
440   mutt_buffer_dealloc(&t);
441 }
442