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