NeoMutt  2020-06-26-89-g172cd3
Teaching an old dog new tricks
DOXYGEN
mutt_lua.c
Go to the documentation of this file.
1 
30 #ifndef LUA_COMPAT_ALL
31 #define LUA_COMPAT_ALL
32 #endif
33 #ifndef LUA_COMPAT_5_1
34 #define LUA_COMPAT_5_1
35 #endif
36 
37 #include "config.h"
38 #include <lauxlib.h>
39 #include <limits.h>
40 #include <lua.h>
41 #include <lualib.h>
42 #include <stdbool.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include "mutt/lib.h"
46 #include "config/lib.h"
47 #include "core/lib.h"
48 #include "mutt.h"
49 #include "mutt_lua.h"
50 #include "init.h"
51 #include "mutt_commands.h"
52 #include "muttlib.h"
53 #include "myvar.h"
54 
60 static int handle_panic(lua_State *l)
61 {
62  mutt_debug(LL_DEBUG1, "lua runtime panic: %s\n", lua_tostring(l, -1));
63  mutt_error("Lua runtime panic: %s", lua_tostring(l, -1));
64  lua_pop(l, 1);
65  return -1;
66 }
67 
73 static int handle_error(lua_State *l)
74 {
75  mutt_debug(LL_DEBUG1, "lua runtime error: %s\n", lua_tostring(l, -1));
76  mutt_error("Lua runtime error: %s", lua_tostring(l, -1));
77  lua_pop(l, 1);
78  return -1;
79 }
80 
87 static int lua_mutt_call(lua_State *l)
88 {
89  mutt_debug(LL_DEBUG2, " * lua_mutt_call()\n");
90  struct Buffer *err = mutt_buffer_pool_get();
91  struct Buffer *token = mutt_buffer_pool_get();
92  char buf[1024] = { 0 };
93  const struct Command *cmd = NULL;
94  int rc = 0;
95 
96  if (lua_gettop(l) == 0)
97  {
98  luaL_error(l, "Error command argument required.");
99  return -1;
100  }
101 
102  cmd = mutt_command_get(lua_tostring(l, 1));
103  if (!cmd)
104  {
105  luaL_error(l, "Error command %s not found.", lua_tostring(l, 1));
106  return -1;
107  }
108 
109  for (int i = 2; i <= lua_gettop(l); i++)
110  {
111  const char *s = lua_tostring(l, i);
112  mutt_strn_cat(buf, sizeof(buf), s, mutt_str_len(s));
113  mutt_strn_cat(buf, sizeof(buf), " ", 1);
114  }
115 
116  struct Buffer expn = mutt_buffer_make(0);
117  expn.data = buf;
118  expn.dptr = buf;
119  expn.dsize = mutt_str_len(buf);
120 
121  if (cmd->parse(token, &expn, cmd->data, err))
122  {
123  luaL_error(l, "NeoMutt error: %s", mutt_b2s(err));
124  rc = -1;
125  }
126  else
127  {
128  if (!lua_pushstring(l, mutt_b2s(err)))
129  handle_error(l);
130  else
131  rc++;
132  }
133 
134  mutt_buffer_pool_release(&token);
136  return rc;
137 }
138 
145 static int lua_mutt_set(lua_State *l)
146 {
147  const char *param = lua_tostring(l, -2);
148  mutt_debug(LL_DEBUG2, " * lua_mutt_set(%s)\n", param);
149 
150  if (mutt_str_startswith(param, "my_"))
151  {
152  const char *val = lua_tostring(l, -1);
153  myvar_set(param, val);
154  return 0;
155  }
156 
157  struct HashElem *he = cs_subset_lookup(NeoMutt->sub, param);
158  if (!he)
159  {
160  luaL_error(l, "NeoMutt parameter not found %s", param);
161  return -1;
162  }
163 
164  struct ConfigDef *cdef = he->data;
165 
166  int rc = 0;
167  struct Buffer err = mutt_buffer_make(256);
168 
169  switch (DTYPE(cdef->type))
170  {
171  case DT_ADDRESS:
172  case DT_ENUM:
173  case DT_MBTABLE:
174  case DT_PATH:
175  case DT_REGEX:
176  case DT_SLIST:
177  case DT_SORT:
178  case DT_STRING:
179  {
180  const char *value = lua_tostring(l, -1);
181  size_t val_size = lua_strlen(l, -1);
182  struct Buffer value_buf = mutt_buffer_make(val_size);
183  mutt_buffer_strcpy_n(&value_buf, value, val_size);
184  if (DTYPE(he->type) == DT_PATH)
185  mutt_buffer_expand_path(&value_buf);
186 
187  int rv = cs_subset_he_string_set(NeoMutt->sub, he, value_buf.data, &err);
188  mutt_buffer_dealloc(&value_buf);
189  if (CSR_RESULT(rv) != CSR_SUCCESS)
190  rc = -1;
191  break;
192  }
193  case DT_NUMBER:
194  case DT_QUAD:
195  {
196  const intptr_t value = lua_tointeger(l, -1);
197  int rv = cs_subset_he_native_set(NeoMutt->sub, he, value, &err);
198  if (CSR_RESULT(rv) != CSR_SUCCESS)
199  rc = -1;
200  break;
201  }
202  case DT_BOOL:
203  {
204  const intptr_t value = lua_toboolean(l, -1);
205  int rv = cs_subset_he_native_set(NeoMutt->sub, he, value, &err);
206  if (CSR_RESULT(rv) != CSR_SUCCESS)
207  rc = -1;
208  break;
209  }
210  default:
211  luaL_error(l, "Unsupported NeoMutt parameter type %d for %s", DTYPE(cdef->type), param);
212  rc = -1;
213  break;
214  }
215 
216  mutt_buffer_dealloc(&err);
217  return rc;
218 }
219 
226 static int lua_mutt_get(lua_State *l)
227 {
228  const char *param = lua_tostring(l, -1);
229  mutt_debug(LL_DEBUG2, " * lua_mutt_get(%s)\n", param);
230 
231  if (mutt_str_startswith(param, "my_"))
232  {
233  const char *mv = myvar_get(param);
234  if (!mv)
235  {
236  luaL_error(l, "NeoMutt parameter not found %s", param);
237  return -1;
238  }
239 
240  lua_pushstring(l, mv);
241  return 1;
242  }
243 
244  struct HashElem *he = cs_subset_lookup(NeoMutt->sub, param);
245  if (!he)
246  {
247  mutt_debug(LL_DEBUG2, " * error\n");
248  luaL_error(l, "NeoMutt parameter not found %s", param);
249  return -1;
250  }
251 
252  struct ConfigDef *cdef = he->data;
253 
254  switch (DTYPE(cdef->type))
255  {
256  case DT_ADDRESS:
257  case DT_ENUM:
258  case DT_MBTABLE:
259  case DT_REGEX:
260  case DT_SLIST:
261  case DT_SORT:
262  case DT_STRING:
263  {
264  struct Buffer value = mutt_buffer_make(256);
265  int rc = cs_subset_he_string_get(NeoMutt->sub, he, &value);
266  if (CSR_RESULT(rc) != CSR_SUCCESS)
267  {
268  mutt_buffer_dealloc(&value);
269  return -1;
270  }
271 
272  struct Buffer escaped = mutt_buffer_make(256);
273  escape_string(&escaped, value.data);
274  lua_pushstring(l, escaped.data);
275  mutt_buffer_dealloc(&value);
276  mutt_buffer_dealloc(&escaped);
277  return 1;
278  }
279  case DT_QUAD:
280  lua_pushinteger(l, *(unsigned char *) cdef->var);
281  return 1;
282  case DT_NUMBER:
283  lua_pushinteger(l, (signed short) *((unsigned long *) cdef->var));
284  return 1;
285  case DT_BOOL:
286  lua_pushboolean(l, *((bool *) cdef->var));
287  return 1;
288  default:
289  luaL_error(l, "NeoMutt parameter type %d unknown for %s", cdef->type, param);
290  return -1;
291  }
292 }
293 
300 static int lua_mutt_enter(lua_State *l)
301 {
302  mutt_debug(LL_DEBUG2, " * lua_mutt_enter()\n");
303  struct Buffer *err = mutt_buffer_pool_get();
304  char *buf = mutt_str_dup(lua_tostring(l, -1));
305  int rc = 0;
306 
307  if (mutt_parse_rc_line(buf, err))
308  {
309  luaL_error(l, "NeoMutt error: %s", mutt_b2s(err));
310  rc = -1;
311  }
312  else
313  {
314  if (!lua_pushstring(l, mutt_b2s(err)))
315  handle_error(l);
316  else
317  rc++;
318  }
319 
320  FREE(&buf);
322 
323  return rc;
324 }
325 
331 static int lua_mutt_message(lua_State *l)
332 {
333  mutt_debug(LL_DEBUG2, " * lua_mutt_message()\n");
334  const char *msg = lua_tostring(l, -1);
335  if (msg)
336  mutt_message(msg);
337  return 0;
338 }
339 
345 static int lua_mutt_error(lua_State *l)
346 {
347  mutt_debug(LL_DEBUG2, " * lua_mutt_error()\n");
348  const char *msg = lua_tostring(l, -1);
349  if (msg)
350  mutt_error(msg);
351  return 0;
352 }
353 
359 static void lua_expose_command(void *p, const struct Command *cmd)
360 {
361  lua_State *l = (lua_State *) p;
362  char buf[1024];
363  snprintf(buf, sizeof(buf), "mutt.command.%s = function (...); mutt.call('%s', ...); end",
364  cmd->name, cmd->name);
365  (void) luaL_dostring(l, buf);
366 }
367 
368 lua_State *LuaState = NULL;
369 
370 static const luaL_Reg luaMuttDecl[] = {
371  { "set", lua_mutt_set }, { "get", lua_mutt_get },
372  { "call", lua_mutt_call }, { "enter", lua_mutt_enter },
373  { "print", lua_mutt_message }, { "message", lua_mutt_message },
374  { "error", lua_mutt_error }, { NULL, NULL },
375 };
376 
377 #define lua_add_lib_member(LUA, TABLE, KEY, VALUE, DATATYPE_HANDLER) \
378  lua_pushstring(LUA, KEY); \
379  DATATYPE_HANDLER(LUA, VALUE); \
380  lua_settable(LUA, TABLE);
381 
387 static int luaopen_mutt_decl(lua_State *l)
388 {
389  mutt_debug(LL_DEBUG2, " * luaopen_mutt()\n");
390  luaL_newlib(l, luaMuttDecl);
391  int lib_idx = lua_gettop(l);
392  /* table_idx, key value, value's type */
393  lua_add_lib_member(l, lib_idx, "VERSION", mutt_make_version(), lua_pushstring);
394  lua_add_lib_member(l, lib_idx, "QUAD_YES", MUTT_YES, lua_pushinteger);
395  lua_add_lib_member(l, lib_idx, "QUAD_NO", MUTT_NO, lua_pushinteger);
396  lua_add_lib_member(l, lib_idx, "QUAD_ASKYES", MUTT_ASKYES, lua_pushinteger);
397  lua_add_lib_member(l, lib_idx, "QUAD_ASKNO", MUTT_ASKNO, lua_pushinteger);
398  return 1;
399 }
400 
405 static void luaopen_mutt(lua_State *l)
406 {
407  luaL_requiref(l, "mutt", luaopen_mutt_decl, 1);
408  (void) luaL_dostring(l, "mutt.command = {}");
410 }
411 
417 static bool lua_init(lua_State **l)
418 {
419  if (!l)
420  return false;
421  if (*l)
422  return true;
423 
424  mutt_debug(LL_DEBUG2, " * lua_init()\n");
425  *l = luaL_newstate();
426 
427  if (!*l)
428  {
429  mutt_error(_("Error: Couldn't load the lua interpreter"));
430  return false;
431  }
432 
433  lua_atpanic(*l, handle_panic);
434 
435  /* load various Lua libraries */
436  luaL_openlibs(*l);
437  luaopen_mutt(*l);
438 
439  return true;
440 }
441 
445 enum CommandResult mutt_lua_parse(struct Buffer *buf, struct Buffer *s,
446  intptr_t data, struct Buffer *err)
447 {
448  lua_init(&LuaState);
449  mutt_debug(LL_DEBUG2, " * mutt_lua_parse(%s)\n", buf->data);
450 
451  if (luaL_dostring(LuaState, s->dptr))
452  {
453  mutt_debug(LL_DEBUG2, " * %s -> failure\n", s->dptr);
454  mutt_buffer_printf(err, "%s: %s", s->dptr, lua_tostring(LuaState, -1));
455  /* pop error message from the stack */
456  lua_pop(LuaState, 1);
457  return MUTT_CMD_ERROR;
458  }
459  mutt_debug(LL_DEBUG2, " * %s -> success\n", s->dptr);
460  mutt_buffer_reset(s); // Clear the rest of the line
461  return MUTT_CMD_SUCCESS;
462 }
463 
467 enum CommandResult mutt_lua_source_file(struct Buffer *buf, struct Buffer *s,
468  intptr_t data, struct Buffer *err)
469 {
470  mutt_debug(LL_DEBUG2, " * mutt_lua_source()\n");
471 
472  lua_init(&LuaState);
473 
474  char path[PATH_MAX];
475 
476  if (mutt_extract_token(buf, s, MUTT_TOKEN_NO_FLAGS) != 0)
477  {
478  mutt_buffer_printf(err, _("source: error at %s"), s->dptr);
479  return MUTT_CMD_ERROR;
480  }
481  if (MoreArgs(s))
482  {
483  mutt_buffer_printf(err, _("%s: too many arguments"), "source");
484  return MUTT_CMD_WARNING;
485  }
486  mutt_str_copy(path, buf->data, sizeof(path));
487  mutt_expand_path(path, sizeof(path));
488 
489  if (luaL_dofile(LuaState, path))
490  {
491  mutt_error(_("Couldn't source lua source: %s"), lua_tostring(LuaState, -1));
492  lua_pop(LuaState, 1);
493  return MUTT_CMD_ERROR;
494  }
495  return MUTT_CMD_SUCCESS;
496 }
#define lua_add_lib_member(LUA, TABLE, KEY, VALUE, DATATYPE_HANDLER)
Definition: mutt_lua.c:377
void mutt_buffer_reset(struct Buffer *buf)
Reset an existing Buffer.
Definition: buffer.c:79
struct Buffer * mutt_buffer_pool_get(void)
Get a Buffer from the pool.
Definition: pool.c:101
intptr_t data
Data or flags to pass to the command.
Definition: mutt_commands.h:58
CommandResult
Error codes for command_t parse functions.
Definition: mutt_commands.h:33
#define CSR_RESULT(x)
Definition: set.h:52
Config/command parsing.
Error: Can&#39;t help the user.
Definition: mutt_commands.h:35
char * mutt_strn_cat(char *d, size_t l, const char *s, size_t sl)
Concatenate two strings.
Definition: string.c:419
#define mutt_message(...)
Definition: logging.h:83
User answered &#39;Yes&#39;, or assume &#39;Yes&#39;.
Definition: quad.h:40
#define DT_REGEX
regular expressions
Definition: types.h:38
static int handle_panic(lua_State *l)
Handle a panic in the Lua interpreter.
Definition: mutt_lua.c:60
void mutt_buffer_pool_release(struct Buffer **pbuf)
Free a Buffer from the pool.
Definition: pool.c:112
struct Buffer mutt_buffer_make(size_t size)
Make a new buffer on the stack.
Definition: buffer.c:61
String manipulation buffer.
Definition: buffer.h:33
enum CommandResult mutt_parse_rc_line(const char *line, struct Buffer *err)
Parse a line of user config.
Definition: init.c:1049
int cs_subset_he_string_get(const struct ConfigSubset *sub, struct HashElem *he, struct Buffer *result)
Get a config item as a string.
Definition: subset.c:341
char * mutt_str_dup(const char *str)
Copy a string, safely.
Definition: string.c:375
#define DT_SORT
sorting methods
Definition: types.h:40
#define _(a)
Definition: message.h:28
A user-callable command.
Definition: mutt_commands.h:44
const char * name
Name of the command.
Definition: mutt_commands.h:46
#define DT_SLIST
a list of strings
Definition: types.h:39
#define DT_MBTABLE
multibyte char table
Definition: types.h:34
static int lua_mutt_set(lua_State *l)
Set a NeoMutt variable.
Definition: mutt_lua.c:145
struct HashElem * cs_subset_lookup(const struct ConfigSubset *sub, const char *name)
Find an inherited config item.
Definition: subset.c:168
int mutt_buffer_printf(struct Buffer *buf, const char *fmt,...)
Format a string overwriting a Buffer.
Definition: buffer.c:160
Config item definition.
Definition: set.h:63
#define DT_QUAD
quad-option (no/yes/ask-no/ask-yes)
Definition: types.h:37
Container for Accounts, Notifications.
Definition: neomutt.h:36
const struct Command * mutt_command_get(const char *s)
Get a Command by its name.
Definition: init.c:391
#define DTYPE(x)
Mask for the Data Type.
Definition: types.h:44
lua_State * LuaState
Definition: mutt_lua.c:368
Integrated Lua scripting.
Convenience wrapper for the config headers.
enum CommandResult(* parse)(struct Buffer *buf, struct Buffer *s, intptr_t data, struct Buffer *err)
Function to parse a command.
Definition: mutt_commands.h:56
static int lua_mutt_enter(lua_State *l)
Execute NeoMutt config from Lua.
Definition: mutt_lua.c:300
Ask the user, defaulting to &#39;Yes&#39;.
Definition: quad.h:42
Some miscellaneous functions.
size_t dsize
Length of data.
Definition: buffer.h:37
char * mutt_expand_path(char *buf, size_t buflen)
Create the canonical path.
Definition: muttlib.c:128
#define MoreArgs(buf)
Definition: buffer.h:43
static int handle_error(lua_State *l)
Handle an error in the Lua interpreter.
Definition: mutt_lua.c:73
static bool lua_init(lua_State **l)
Initialise a Lua State.
Definition: mutt_lua.c:417
Many unsorted constants and some structs.
Log at debug level 2.
Definition: logging.h:41
Convenience wrapper for the core headers.
int cs_subset_he_string_set(const struct ConfigSubset *sub, struct HashElem *he, const char *value, struct Buffer *err)
Set a config item by string.
Definition: subset.c:373
void mutt_buffer_dealloc(struct Buffer *buf)
Release the memory allocated by a buffer.
Definition: buffer.c:294
#define CSR_SUCCESS
Action completed successfully.
Definition: set.h:35
#define DT_ADDRESS
e-mail address
Definition: types.h:29
#define mutt_b2s(buf)
Definition: buffer.h:41
#define DT_STRING
a string
Definition: types.h:41
size_t mutt_str_startswith(const char *str, const char *prefix)
Check whether a string starts with a prefix.
Definition: string.c:165
#define DT_PATH
a path to a file/directory
Definition: types.h:36
#define PATH_MAX
Definition: mutt.h:44
User answered &#39;No&#39;, or assume &#39;No&#39;.
Definition: quad.h:39
int mutt_extract_token(struct Buffer *dest, struct Buffer *tok, TokenFlags flags)
Extract one token from a string.
Definition: init.c:422
size_t mutt_buffer_strcpy_n(struct Buffer *buf, const char *s, size_t len)
Copy a string into a Buffer.
Definition: buffer.c:327
char * dptr
Current read/write position.
Definition: buffer.h:36
char * data
Pointer to data.
Definition: buffer.h:35
static int lua_mutt_message(lua_State *l)
Display a message in Neomutt.
Definition: mutt_lua.c:331
Definitions of NeoMutt commands.
enum CommandResult mutt_lua_parse(struct Buffer *buf, struct Buffer *s, intptr_t data, struct Buffer *err)
Parse the &#39;lua&#39; command - Implements Command::parse()
Definition: mutt_lua.c:445
static int lua_mutt_call(lua_State *l)
Call a NeoMutt command by name.
Definition: mutt_lua.c:87
void myvar_set(const char *var, const char *val)
Set the value of a "my_" variable.
Definition: myvar.c:91
static int luaopen_mutt_decl(lua_State *l)
Declare some NeoMutt types to the Lua interpreter.
Definition: mutt_lua.c:387
const char * myvar_get(const char *var)
Get the value of a "my_" variable.
Definition: myvar.c:73
void * data
User-supplied data.
Definition: hash.h:47
void * var
Pointer to the global variable.
Definition: set.h:67
size_t mutt_str_len(const char *a)
Calculate the length of a string, safely.
Definition: string.c:636
unsigned int type
Variable type, e.g. DT_STRING.
Definition: set.h:66
static int lua_mutt_error(lua_State *l)
Display an error in Neomutt.
Definition: mutt_lua.c:345
Success: Command worked.
Definition: mutt_commands.h:37
void mutt_buffer_expand_path(struct Buffer *buf)
Create the canonical path.
Definition: muttlib.c:323
Log at debug level 1.
Definition: logging.h:40
Warning: Help given to the user.
Definition: mutt_commands.h:36
size_t mutt_str_copy(char *dest, const char *src, size_t dsize)
Copy a string into a buffer (guaranteeing NUL-termination)
Definition: string.c:721
Ask the user, defaulting to &#39;No&#39;.
Definition: quad.h:41
#define mutt_error(...)
Definition: logging.h:84
static const luaL_Reg luaMuttDecl[]
Definition: mutt_lua.c:370
#define DT_ENUM
an enumeration
Definition: types.h:31
static void lua_expose_command(void *p, const struct Command *cmd)
Expose a NeoMutt command to the Lua interpreter.
Definition: mutt_lua.c:359
int type
Type of data stored in Hash Table, e.g. DT_STRING.
Definition: hash.h:45
#define FREE(x)
Definition: memory.h:40
static int lua_mutt_get(lua_State *l)
Get a NeoMutt variable.
Definition: mutt_lua.c:226
size_t escape_string(struct Buffer *buf, const char *src)
Write a string to a buffer, escaping special characters.
Definition: dump.c:46
The item stored in a Hash Table.
Definition: hash.h:43
#define mutt_debug(LEVEL,...)
Definition: logging.h:81
struct ConfigSubset * sub
Inherited config items.
Definition: neomutt.h:39
static void luaopen_mutt(lua_State *l)
Expose a &#39;Mutt&#39; object to the Lua interpreter.
Definition: mutt_lua.c:405
Convenience wrapper for the library headers.
int cs_subset_he_native_set(const struct ConfigSubset *sub, struct HashElem *he, intptr_t value, struct Buffer *err)
Natively set the value of a HashElem config item.
Definition: subset.c:270
Handling of personal config (&#39;my&#39; variables)
enum CommandResult mutt_lua_source_file(struct Buffer *buf, struct Buffer *s, intptr_t data, struct Buffer *err)
Parse the &#39;lua-source&#39; command - Implements Command::parse()
Definition: mutt_lua.c:467
#define DT_NUMBER
a number
Definition: types.h:35
#define DT_BOOL
boolean option
Definition: types.h:30
void mutt_commands_apply(void *data, void(*application)(void *, const struct Command *))
Run a callback function on every Command.
Definition: init.c:407
#define MUTT_TOKEN_NO_FLAGS
No flags are set.
Definition: mutt.h:70
const char * mutt_make_version(void)
Generate the NeoMutt version string.
Definition: muttlib.c:1460