Debian Codegraph @

runtime/help/plugins.md

raw
1 # Plugins
2
3 This help topic is about creating plugins. If you need help installing or
4 managing plugins, look for `plugin` commands in `help commands`. If you want to
5 enable or disable a plugin, look for `Plugin options` in `help options`.
6
7 Micro supports creating plugins with a simple Lua system. Plugins are
8 folders containing Lua files and possibly other source files placed
9 in `~/.config/micro/plug`. The plugin directory (within `plug`) should
10 contain at least one Lua file and a `repo.json` file. The `repo.json` file
11 provides additional information such as the name of the plugin, the
12 plugin's website, dependencies, etc.
13 [Here is an example `repo.json` file](https://github.com/micro-editor/updated-plugins/blob/master/go-plugin/repo.json)
14 from the go plugin, which has the following file structure:
15
16 ```
17 ~/.config/micro/plug/go-plugin/
18 go.lua
19 repo.json
20 help/
21 go-plugin.md
22 ```
23
24 The `go.lua` file contains the main code for the plugin, though the
25 code may be distributed across multiple Lua files. The `repo.json`
26 file contains information about the plugin, such as the website,
27 description, version, and any requirements. Plugins may also
28 have additional files that can be added to micro's runtime files,
29 of which there are 5 types:
30
31 * Colorschemes
32 * Syntax files
33 * Help files
34 * Plugin files
35 * Syntax header files
36
37 In most cases, a plugin will want to add help files, but in certain
38 cases a plugin may also want to add colorschemes or syntax files.
39 No directory structure is enforced, but keeping runtime files in their
40 own directories is good practice.
41
42 ## Lua callbacks
43
44 Plugins use Lua but also have access to many functions, both from micro
45 and from the Go standard library. Plugins can also define functions that micro
46 will call when certain events happen. Here is the list of callbacks
47 that micro defines:
48
49 * `init()`: this function should be used for your plugin initialization.
50 This function is called after buffers have been initialized.
51
52 * `preinit()`: initialization function called before buffers have been
53 initialized.
54
55 * `postinit()`: initialization function called after the `init()` function of
56 all plugins has been called.
57
58 * `deinit()`: cleanup function called when your plugin is unloaded or reloaded.
59
60 * `onBufferOpen(buf)`: runs when a buffer is opened. The input contains
61 the buffer object.
62
63 * `onBufferOptionChanged(buf, option, old, new)`: runs when an option of the
64 buffer has changed. The input contains the buffer object, the option name,
65 the old and the new value.
66
67 * `onBufPaneOpen(bufpane)`: runs when a bufpane is opened. The input
68 contains the bufpane object.
69
70 * `onSetActive(bufpane)`: runs when changing the currently active bufpane.
71
72 * `onAction(bufpane)`: runs when `Action` is triggered by the user, where
73 `Action` is a bindable action (see `> help keybindings`). A bufpane
74 is passed as input. The function should return a boolean defining
75 whether the action was successful, which is used when the action is
76 chained with other actions (see `> help keybindings`) to determine whether
77 the next actions in the chain should be executed or not.
78
79 If the action is a mouse action, e.g. `MousePress`, the mouse event info
80 is passed to the callback as an extra argument of type `*tcell.EventMouse`.
81 See https://pkg.go.dev/github.com/micro-editor/tcell/v2#EventMouse for the
82 description of this type and its methods.
83
84 * `preAction(bufpane)`: runs immediately before `Action` is triggered
85 by the user. Returns a boolean which defines whether the action should
86 be canceled.
87
88 Similarly to `onAction`, if the action is a mouse action, the mouse event
89 info is passed to the callback as an extra argument of type
90 `*tcell.EventMouse`.
91
92 * `onRune(bufpane, rune)`: runs when the composed rune has been inserted
93
94 * `preRune(bufpane, rune)`: runs before the composed rune will be inserted
95
96 * `onAnyEvent()`: runs when literally anything happens. It is useful for
97 detecting various changes of micro's state that cannot be detected
98 using other callbacks.
99
100 For example, a function that is run every time the user saves the buffer
101 would be:
102
103 ```lua
104 function onSave(bp)
105 ...
106 return false
107 end
108 ```
109
110 The `bp` variable is a reference to the bufpane the action is being executed
111 within. This is almost always the current bufpane.
112
113 All available actions are listed in the keybindings section of the help.
114
115 ## Accessing micro functions
116
117 Some of micro's internal information is exposed in the form of packages, which
118 can be imported by Lua plugins. A package can be imported in Lua, and a value
119 within it can be accessed using the following syntax:
120
121 ```lua
122 local micro = import("micro")
123 micro.Log("Hello")
124 ```
125
126 The packages and their contents are listed below (in Go type signatures):
127
128 * `micro`
129 - `TermMessage(msg any...)`: temporarily close micro and print a
130 message
131
132 - `TermError(filename string, lineNum int, err string)`: temporarily close
133 micro and print an error formatted as `filename, lineNum: err`.
134
135 - `InfoBar() *InfoPane`: return the infobar BufPane object.
136
137 - `Log(msg any...)`: write a message to `log.txt` (requires
138 `-debug` flag, or binary built with `build-dbg`).
139
140 - `SetStatusInfoFn(fn string)`: register the given lua function as
141 accessible from the statusline formatting options.
142
143 - `CurPane() *BufPane`: returns the current BufPane, or nil if the
144 current pane is not a BufPane.
145
146 - `CurTab() *Tab`: returns the current tab.
147
148 - `Tabs() *TabList`: returns the global tab list.
149
150 - `After(t time.Duration, f func())`: run function `f` in the background
151 after time `t` elapses. See https://pkg.go.dev/time#Duration for the
152 usage of `time.Duration`.
153
154 Relevant links:
155 [Time](https://pkg.go.dev/time#Duration)
156 [BufPane](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/action#BufPane)
157 [InfoPane](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/action#InfoPane)
158 [Tab](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/action#Tab)
159 [TabList](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/action#TabList)
160
161 * `micro/config`
162 - `MakeCommand(name string, action func(bp *BufPane, args[]string),
163 completer buffer.Completer)`:
164 create a command with the given name, and lua callback function when
165 the command is run. A completer may also be given to specify how
166 autocompletion should work with the custom command. Any lua function
167 that takes a Buffer argument and returns a pair of string arrays is a
168 valid completer, as are the built in completers below:
169
170 - `FileComplete`: autocomplete using files in the current directory
171 - `HelpComplete`: autocomplete using names of help documents
172 - `OptionComplete`: autocomplete using names of options
173 - `OptionValueComplete`: autocomplete using names of options, and valid
174 values afterwards
175 - `NoComplete`: no autocompletion suggestions
176
177 - `TryBindKey(k, v string, overwrite bool) (bool, error)`:
178 bind the key `k` to the string `v`. If `overwrite` is true, this will
179 overwrite any existing binding to key `k`.
180 Returns true if the binding was made, and a possible error.
181 This operation can be rejected by `lockbindings` to prevent undesired
182 actions by the user.
183
184 - `Reload()`: reload configuration files.
185
186 - `AddRuntimeFileFromMemory(filetype RTFiletype, filename, data string)`:
187 add a runtime file to the `filetype` runtime filetype, with name
188 `filename` and data `data`.
189
190 - `AddRuntimeFilesFromDirectory(plugin string, filetype RTFiletype,
191 directory, pattern string)`:
192 add runtime files for the given plugin with the given RTFiletype from
193 a directory within the plugin root. Only adds files that match the
194 pattern using Go's `filepath.Match`
195
196 - `AddRuntimeFile(plugin string, filetype RTFiletype, filepath string)`:
197 add a given file inside the plugin root directory as a runtime file
198 to the given RTFiletype category.
199
200 - `ListRuntimeFiles(fileType RTFiletype) []string`: returns a list of
201 names of runtime files of the given type.
202
203 - `ReadRuntimeFile(fileType RTFiletype, name string) string`: returns the
204 contents of a given runtime file.
205
206 - `NewRTFiletype() int`: creates a new RTFiletype, and returns its value.
207
208 - `RTColorscheme`: runtime files for colorschemes.
209 - `RTSyntax`: runtime files for syntax files.
210 - `RTHelp`: runtime files for help documents.
211 - `RTPlugin`: runtime files for plugin source code.
212
213 - `RegisterCommonOption(pl string, name string, defaultvalue any)`:
214 registers a new option for the given plugin. The name of the
215 option will be `pl.name`, and will have the given default value. Since
216 this registers a common option, the option will be modifiable on a
217 per-buffer basis, while also having a global value (in the
218 GlobalSettings map).
219
220 - `RegisterGlobalOption(pl string, name string, defaultvalue any)`:
221 same as `RegisterCommonOption`, but the option cannot be modified
222 locally to each buffer.
223
224 - `GetGlobalOption(name string) any`: returns the value of a
225 given plugin in the `GlobalSettings` map.
226
227 - `SetGlobalOption(option, value string) error`: sets an option to a
228 given value. This will try to convert the value into the proper
229 type for the option. Can return an error if the option name is not
230 valid, or the value can not be converted.
231
232 - `SetGlobalOptionNative(option string, value any) error`: sets
233 an option to a given value, where the type of value is the actual
234 type of the value internally. Can return an error if the provided value
235 is not valid for the given option.
236
237 - `ConfigDir`: the path to micro's currently active config directory.
238
239 Relevant links:
240 [Buffer](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/buffer#Buffer)
241 [buffer.Completer](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/buffer#Completer)
242 [Error](https://pkg.go.dev/builtin#error)
243 [filepath.Match](https://pkg.go.dev/path/filepath#Match)
244
245 * `micro/shell`
246 - `ExecCommand(name string, arg ...string) (string, error)`: runs an
247 executable with the given arguments, and pipes the output (stderr
248 and stdout) of the executable to an internal buffer, which is
249 returned as a string, along with a possible error.
250
251 - `RunCommand(input string) (string, error)`: same as `ExecCommand`,
252 except this uses micro's argument parser to parse the arguments from
253 the input. For example, `cat 'hello world.txt' file.txt`, will pass
254 two arguments in the `ExecCommand` argument list (quoting arguments
255 will preserve spaces).
256
257 - `RunBackgroundShell(input string) (func() string, error)`: returns a
258 function that will run the given shell command and return its output.
259
260 - `RunInteractiveShell(input string, wait bool, getOutput bool)
261 (string, error)`:
262 temporarily closes micro and runs the given command in the terminal.
263 If `wait` is true, micro will wait for the user to press enter before
264 returning to text editing. If `getOutput` is true, micro will redirect
265 stdout from the command to the returned string.
266
267 - `JobStart(cmd string, onStdout, onStderr,
268 onExit func(string, []any), userargs ...any)
269 *exec.Cmd`:
270 Starts a background job by running the shell on the given command
271 (using `sh -c`). Three callbacks can be provided which will be called
272 when the command generates stdout, stderr, or exits. The userargs will
273 be passed to the callbacks, along with the output as the first
274 argument of the callback. Returns the started command.
275
276 - `JobSpawn(cmd string, cmdArgs []string, onStdout, onStderr,
277 onExit func(string, []any), userargs ...any)
278 *exec.Cmd`:
279 same as `JobStart`, except doesn't run the command through the shell
280 and instead takes as inputs the list of arguments. Returns the started
281 command.
282
283 - `JobStop(cmd *exec.Cmd)`: kills a job.
284 - `JobSend(cmd *exec.Cmd, data string)`: sends some data to a job's stdin.
285
286 - `RunTermEmulator(h *BufPane, input string, wait bool, getOutput bool,
287 callback func(out string, userargs []any),
288 userargs []any) error`:
289 starts a terminal emulator from a given BufPane with the input command.
290 If `wait` is true, it will wait for the user to exit by pressing enter
291 once the executable has terminated, and if `getOutput` is true, it will
292 redirect the stdout of the process to a pipe, which will be passed to
293 the callback, which is a function that takes a string and a list of
294 optional user arguments. This function returns an error on systems
295 where the terminal emulator is not supported.
296
297 - `TermEmuSupported`: true on systems where the terminal emulator is
298 supported and false otherwise. Supported systems:
299 * Linux
300 * MacOS
301 * Dragonfly
302 * OpenBSD
303 * FreeBSD
304
305 Relevant links:
306 [Cmd](https://pkg.go.dev/os/exec#Cmd)
307 [BufPane](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/action#BufPane)
308 [Error](https://pkg.go.dev/builtin#error)
309
310 * `micro/buffer`
311 - `NewMessage(owner string, msg string, start, end, Loc, kind MsgType)
312 *Message`:
313 creates a new message with an owner over a range defined by the start
314 and end locations.
315
316 - `NewMessageAtLine(owner string, msg string, line int, kindMsgType)
317 *Message`:
318 creates a new message with owner, type, and text at a given line.
319
320 - `MTInfo`: info message.
321 - `MTWarning`: warning message.
322 - `MTError` error message.
323
324 - `Loc(x, y int) Loc`: creates a new location struct.
325 - `SLoc(line, row int) display.SLoc`: creates a new scrolling location struct.
326
327 - `BTDefault`: default buffer type.
328 - `BTHelp`: help buffer type.
329 - `BTLog`: log buffer type.
330 - `BTScratch`: scratch buffer type (cannot be saved).
331 - `BTRaw`: raw buffer type.
332 - `BTInfo`: info buffer type.
333
334 - `NewBuffer(text, path string) *Buffer`: creates a new buffer with the
335 given text at a certain path.
336
337 - `NewBufferFromFile(path string) (*Buffer, error)`: creates a new
338 buffer by reading the file at the given path from disk. Returns an error
339 if the read operation fails (for example, due to the file not existing).
340
341 - `ByteOffset(pos Loc, buf *Buffer) int`: returns the byte index of the
342 given position in a buffer.
343
344 - `Log(s string)`: writes a string to the log buffer.
345 - `LogBuf() *Buffer`: returns the log buffer.
346
347 Relevant links:
348 [Message](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/buffer#Message)
349 [Loc](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/buffer#Loc)
350 [display.SLoc](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/display#SLoc)
351 [Buffer](https://pkg.go.dev/github.com/zyedidia/micro/v2/internal/buffer#Buffer)
352 [Error](https://pkg.go.dev/builtin#error)
353
354 * `micro/util`
355 - `RuneAt(str string, idx int) string`: returns the utf8 rune at a
356 given index within a string.
357 - `GetLeadingWhitespace(s string) string`: returns the leading
358 whitespace of a string.
359 - `IsWordChar(s string) bool`: returns true if the first rune in a
360 string is a word character.
361 - `String(b []byte) string`: converts a byte array to a string.
362 - `Unzip(src, dest string) error`: unzips a file to given folder.
363 - `Version`: micro's version number or commit hash
364 - `SemVersion`: micro's semantic version
365 - `HttpRequest(method string, url string, headers []string)
366 (http.Response, error)`: makes a http request.
367 - `CharacterCountInString(str string) int`: returns the number of
368 characters in a string
369 - `RuneStr(r rune) string`: converts a rune to a string.
370
371 Relevant links:
372 [Rune](https://pkg.go.dev/builtin#rune)
373
374 This may seem like a small list of available functions, but some of the objects
375 returned by the functions have many methods. The Lua plugin may access any
376 public methods of an object returned by any of the functions above.
377 Unfortunately, it is not possible to list all the available functions on this
378 page. Please go to the internal documentation at
379 https://pkg.go.dev/github.com/zyedidia/micro/v2/internal to see the full list
380 of available methods. Note that only methods of types that are available to
381 plugins via the functions above can be called from a plugin. For an even more
382 detailed reference, see the source code on Github.
383
384 For example, with a BufPane object called `bp`, you could call the `Save`
385 function in Lua with `bp:Save()`.
386
387 Note that Lua uses the `:` syntax to call a function rather than Go's `.`
388 syntax.
389
390 ```go
391 micro.InfoBar().Message()
392 ```
393
394 turns to
395
396 ```lua
397 micro.InfoBar():Message()
398 ```
399
400 ## Accessing the Go standard library
401
402 It is possible for your lua code to access many of the functions in the Go
403 standard library.
404
405 Simply import the package you'd like, and then you can use it. For example:
406
407 ```lua
408 local ioutil = import("io/ioutil")
409 local fmt = import("fmt")
410 local micro = import("micro")
411
412 local data, err = ioutil.ReadFile("SomeFile.txt")
413
414 if err ~= nil then
415 micro.InfoBar():Error("Error reading file: SomeFile.txt")
416 else
417 -- Data is returned as an array of bytes
418 -- Using Sprintf will convert it to a string
419 local str = fmt.Sprintf("%s", data)
420
421 -- Do something with the file you just read!
422 -- ...
423 end
424 ```
425
426 Here are the packages from the Go standard library that you can access.
427 Nearly all functions from these packages are supported. For an exact
428 list of functions that are supported, you can look through `lua.go`
429 (which should be easy to understand).
430
431 * [fmt](https://pkg.go.dev/fmt)
432 * [io](https://pkg.go.dev/io)
433 * [io/ioutil](https://pkg.go.dev/io/ioutil)
434 * [net](https://pkg.go.dev/net)
435 * [math](https://pkg.go.dev/math)
436 * [math/rand](https://pkg.go.dev/math/rand)
437 * [os](https://pkg.go.dev/os)
438 * [runtime](https://pkg.go.dev/runtime)
439 * [path](https://pkg.go.dev/path)
440 * [filepath](https://pkg.go.dev/filepath)
441 * [strings](https://pkg.go.dev/strings)
442 * [regexp](https://pkg.go.dev/regexp)
443 * [errors](https://pkg.go.dev/errors)
444 * [time](https://pkg.go.dev/time)
445 * [unicode/utf8](https://pkg.go.dev/unicode/utf8)
446 * [archive/zip](https://pkg.go.dev/archive/zip)
447 * [net/http](https://pkg.go.dev/net/http)
448
449 The following functions from the go-humanize package are also available:
450
451 * `humanize`:
452 - `Bytes(s uint64) string`: produces a human readable representation of
453 an SI size.
454 - `Ordinal(x int) string`: gives you the input number in a rank/ordinal
455 format.
456
457 [The Lua standard library](https://www.lua.org/manual/5.1/manual.html#5) is also
458 available to plugins, though it is rather small.
459
460 ## Adding help files, syntax files, or colorschemes in your plugin
461
462 You can use the `AddRuntimeFile(name string, type config.RTFiletype,
463 path string)`
464 function to add various kinds of files to your plugin. For example, if you'd
465 like to add a help topic to your plugin called `test`, you would create a
466 `test.md` file and call the function:
467
468 ```lua
469 config = import("micro/config")
470 config.AddRuntimeFile("test", config.RTHelp, "test.md")
471 ```
472
473 Use `AddRuntimeFilesFromDirectory(name, type, dir, pattern)` to add a number of
474 files to the runtime. To read the content of a runtime file, use
475 `ReadRuntimeFile(fileType, name string)` or `ListRuntimeFiles(fileType string)`
476 for all runtime files. In addition, there is `AddRuntimeFileFromMemory` which
477 adds a runtime file based on a string that may have been constructed at
478 runtime.
479
480 ## Default plugins
481
482 The following plugins come pre-installed with micro:
483
484 * `autoclose`: automatically closes brackets, quotes, etc...
485 * `comment`: provides automatic commenting for a number of languages
486 * `ftoptions`: alters some default options (notably indentation) depending on
487 the filetype
488 * `linter`: provides extensible linting for many languages
489 * `literate`: provides advanced syntax highlighting for the Literate
490 programming tool.
491 * `status`: provides some extensions to the status line (integration with
492 Git and more).
493 * `diff`: integrates the `diffgutter` option with Git. If you are in a Git
494 directory, the diff gutter will show changes with respect to the most
495 recent Git commit rather than the diff since opening the file.
496
497 See `> help linter`, `> help comment`, and `> help status` for additional
498 documentation specific to those plugins.
499
500 These are good examples for many use-cases if you are looking to write
501 your own plugins.
502
503 ## Plugin Manager
504
505 Micro also has a built in plugin manager, which you can invoke with the
506 `> plugin ...` command, or in the shell with `micro -plugin ...`.
507
508 For the valid commands you can use, see the `commands` help topic.
509
510 The manager fetches plugins from the channels (which is simply a list of plugin
511 metadata) which it knows about. By default, micro only knows about the [official
512 channel](https://github.com/micro-editor/plugin-channel) but you can
513 add your own third-party channels using the `pluginchannels` option and you can
514 directly link third-party plugins to allow installation through the plugin
515 manager with the `pluginrepos` option.
516
517 If you'd like to publish a plugin you've made as an official plugin, you should
518 upload your plugin online (preferably to Github) and add a `repo.json` file.
519 This file will contain the metadata for your plugin. Here is an example:
520
521 ```json
522 [{
523 "Name": "pluginname",
524 "Description": "Here is a nice concise description of my plugin",
525 "Website": "https://github.com/user/plugin",
526 "Tags": ["python", "linting"],
527 "Versions": [
528 {
529 "Version": "1.0.0",
530 "Url": "https://github.com/user/plugin/archive/v1.0.0.zip",
531 "Require": {
532 "micro": ">=1.0.3"
533 }
534 }
535 ]
536 }]
537 ```
538
539 Then open a pull request at the [official plugin channel](https://github.com/micro-editor/plugin-channel),
540 adding a link to the raw `repo.json` that is in your plugin repository.
541
542 To make updating the plugin work, the first line of your plugin's lua code
543 should contain the version of the plugin. (Like this: `VERSION = "1.0.0"`)
544 Please make sure to use [semver](https://semver.org/) for versioning.