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