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