]> git.lizzy.rs Git - micro.git/blob - runtime/help/plugins.md
Merge pull request #1 from msiism/msiism-patch-1
[micro.git] / runtime / help / plugins.md
1 # Plugins
2
3 Micro supports creating plugins with a simple Lua system. Every plugin has a
4 main script which is run at startup which should be placed in 
5 `~/.config/micro/plugins/pluginName/pluginName.lua`.
6
7 There are a number of callback functions which you can create in your plugin to
8 run code at times other than startup. The naming scheme is `onAction(view)`. For
9 example a function which is run every time the user saves the buffer would be:
10
11 ```lua
12 function onSave(view)
13     ...
14     return false
15 end
16 ```
17
18 The `view` variable is a reference to the view the action is being executed on.
19 This is almost always the current view, which you can get with `CurView()` as
20 well.
21
22 All available actions are listed in the keybindings section of the help.
23
24 For callbacks to mouse actions, you are also given the event info:
25
26 ```lua
27 function onMousePress(view, event)
28     local x, y = event:Position()
29
30     return false
31 end
32 ```
33
34 These functions should also return a boolean specifying whether the view should
35 be relocated to the cursor or not after the action is complete.
36
37 Note that these callbacks occur after the action has been completed. If you want
38 a callback before the action is executed, use `preAction()`. In this case the
39 boolean returned specifies whether or not the action should be executed after
40 the lua code completes.
41
42 Another useful callback to know about which is not an action is
43 `onViewOpen(view)` which is called whenever a new view is opened and the new
44 view is passed in. This is useful for setting local options based on the
45 filetype, for example turning off `tabstospaces` only for Go files when they are
46 opened.
47
48 ---
49
50 There are a number of functions and variables that are available to you in order
51 to access the inner workings of micro. Here is a list (the type signatures for
52 functions are given using Go's type system):
53
54 * `OS`: variable which gives the OS micro is currently running on (this is the
55   same as Go's GOOS variable, so `darwin`, `windows`, `linux`, `freebsd`...)
56
57 * `configDir`: contains the path to the micro configuration files
58
59 * `tabs`: a list of all the tabs currently in use
60
61 * `curTab`: the index of the current tabs in the tabs list
62
63 * `messenger`: lets you send messages to the user or create prompts
64
65 * `NewBuffer(text, path string) *Buffer`: creates a new buffer from a given
66    reader with a given path
67
68 * `NewBufferFromFile(path string) *Buffer`: creates a new buffer from a given
69    path
70
71 * `GetLeadingWhitespace() bool`: returns the leading whitespace of the given
72    string
73
74 * `IsWordChar(str string) bool`: returns whether or not the string is a 'word
75    character'
76
77 * `RuneStr(r rune) string`: returns a string containing the given rune
78
79 * `Loc(x, y int) Loc`: returns a new `Loc` struct
80
81 * `WorkingDirectory() string`: returns a rooted path name to the current working
82    directory
83
84 * `JoinPaths(dir... string) string`: combines multiple directories to a full
85    path
86
87 * `DirectoryName(path string)`: returns all but the last element of path,
88    typically the path's directory
89
90 * `GetOption(name string)`: returns the value of the requested option
91
92 * `AddOption(name string, value interface{})`: sets the given option with the
93    given value (`interface{}` means any type in Go)
94
95 * `SetOption(option, value string)`: sets the given option to the value. This
96    will set the option globally, unless it is a local only option.
97
98 * `SetLocalOption(option, value string, view *View)`: sets the given option to
99    the value locally in the given buffer
100
101 * `BindKey(key, action string)`: binds `key` to `action`
102
103 * `MakeCommand(name, function string, completions ...Completion)`: 
104    creates a command with `name` which will call `function` when executed. Use 0
105    for completions to get NoCompletion.
106
107 * `MakeCompletion(function string)`:
108    creates a `Completion` to use with `MakeCommand`
109
110 * `CurView()`: returns the current view
111
112 * `HandleCommand(cmd string)`: runs the given command
113
114 * `ExecCommand(name string, args []string) (string, error)`: exec a (shell) command with the
115    given arguments. Returns the command's output and a possible error.
116
117 * `RunShellCommand(cmd string) (string, error)`: Run a shell command. This uses `ExecCommand`
118    under the hood but also does some parsing for the arguments (i.e. quoted arguments). The
119    function returns the command's output and a possible error.
120
121 * `RunBackgroundShell(cmd string)`: Run a shell command in the background.
122
123 * `RunInteractiveShell(cmd string, wait bool, getOutput bool) (string, error)`: Run a shell command
124    by closing micro and running the command interactively. If `wait` is true, a prompt will be
125    used after the process exits to prevent the terminal from immediately returning to micro, allowing
126    the user to view the output of the process. If `getOutput` is true, the command's standard output
127    will be returned. Note that if `getOutput` is true, some interactive commands may not behave
128    normally because `isatty` will return false.
129
130 * `RunTermEmulator(cmd string, wait bool, getOutput bool, callback string) error`: Same as
131    `RunInteractiveShell` except the command is run within the current split in a terminal emulator.
132    The `callback` input is a string callback to a lua function which will be called when the process
133    exits. The output of the process will be provided as the first and only argument to the callback
134    (it will be empty if `getOutput` is false).
135    Note that this functionality is only supported on some operating systems (linux, darwin, dragonfly,
136    openbsd, freebsd). Use the `TermEmuSupported` (see below) boolean to determine if the current
137    system is supported.
138
139 * `TermEmuSupported`: Boolean specifying if the terminal emulator is supported on the version of
140    micro that is running.
141
142 * `ToCharPos(loc Loc, buf *Buffer) int`: returns the character position of a
143    given x, y location
144
145 * `Reload`: (Re)load everything
146
147 * `ByteOffset(loc Loc, buf *Buffer) int`: exactly like `ToCharPos` except it it
148    counts bytes instead of runes
149
150 * `JobSpawn(cmdName string, cmdArgs []string, onStdout, onStderr, onExit string, userargs ...string)`:
151    Starts running the given process in the background. `onStdout` `onStderr` and
152    `onExit` are callbacks to lua functions which will be called when the given
153    actions happen to the background process. `userargs` are the arguments which
154    will get passed to the callback functions
155
156 * `JobStart(cmd string, onStdout, onStderr, onExit string, userargs ...string)`:
157    Starts running the given shell command in the background. Note that the
158    command execute is first parsed by a shell when using this command. It is
159    executed with `sh -c`.
160
161 * `JobSend(cmd *exec.Cmd, data string)`: send a string into the stdin of the job
162    process
163
164 * `JobStop(cmd *exec.Cmd)`: kill a job
165
166 This may seem like a small list of available functions but some of the objects
167 returned by the functions have many methods. `CurView()` returns a view object
168 which has all the actions which you can call. For example
169 `CurView():Save(false)`. You can see the full list of possible actions in the
170 keybindings help topic. The boolean on all the actions indicates whether or not
171 the lua callbacks should be run. I would recommend generally sticking to false
172 when making a plugin to avoid recursive problems, for example if you call
173 `CurView():Save(true)` in `onSave()`. Just use `CurView():Save(false)` so that
174 it won't call `onSave()` again.
175
176 Using the view object, you can also access the buffer associated with that view
177 by using `CurView().Buf`, which lets you access the `FileType`, `Path`,
178 `Name`...
179
180 The possible methods which you can call using the `messenger` variable are:
181
182 * `messenger.Message(msg ...interface{})`
183 * `messenger.Error(msg ...interface{})`
184 * `messenger.YesNoPrompt(prompt string) (bool,bool)`
185 * `messenger.Prompt(prompt, historyType string, completionType Completion) (string, bool)`
186 * `messenger.AddLog(msg ...interface{})`
187
188 #### Note 
189
190 Go function signatures use `.` and lua uses `:` so
191
192 ```go
193 messenger.Message()
194 ```
195
196 turns to
197
198 ```lua
199 messenger:Message()
200 ```
201
202 If you want a standard prompt, just use
203
204 ```lua
205 messenger:Prompt(prompt, "", 0)
206 ```
207
208 Debug or logging your plugin can be done with below lua example code.
209
210 ```lua
211 messenger:AddLog("Message goes here ",pluginVariableToPrintHere)
212 ```
213
214 In Micro to see your plugin logging output press `CtrlE` then type `log`, a 
215 logging window will open and any logging sent from your plugin will be displayed
216 here.
217
218
219 ## Accessing the Go standard library
220
221 It is possible for your lua code to access many of the functions in the Go
222 standard library.
223
224 Simply import the package you'd like and then you can use it. For example:
225
226 ```lua
227 local ioutil = import("io/ioutil")
228 local fmt = import("fmt")
229
230 local data, err = ioutil.ReadFile("SomeFile.txt")
231
232 if err ~= nil then
233     messenger:Error("Error reading file: SomeFile.txt")
234 else
235     -- Data is returned as an array of bytes
236     -- Using Sprintf will convert it to a string
237     local str = fmt.Sprintf("%s", data)
238
239     -- Do something with the file you just read!
240     -- ...
241 end
242 ```
243
244 Here are the packages from the Go standard library that you can access.
245 Nearly all functions from these packages are supported. For an exact
246 list of which functions are supported you can look through `lua.go`
247 (which should be easy to understand).
248
249 ```
250 fmt
251 io
252 io/ioutil
253 net
254 math
255 math/rand
256 os
257 runtime
258 path
259 filepath
260 strings
261 regexp
262 errors
263 time
264 ```
265
266 For documentation for each of these functions, you can simply look
267 through the Go standard library documentation.
268
269 ## Adding help files, syntax files, or colorschemes in your plugin
270
271 You can use the `AddRuntimeFile(name, type, path string)` function to add
272 various kinds of files to your plugin. For example, if you'd like to add a help
273 topic to your plugin called `test`, you would create a `test.md` file, and call
274 the function:
275
276 ```lua
277 AddRuntimeFile("test", "help", "test.md")
278 ```
279
280 Use `AddRuntimeFilesFromDirectory(name, type, dir, pattern)` to add a number of
281 files to the runtime. To read the content of a runtime file use
282 `ReadRuntimeFile(fileType, name string)` or `ListRuntimeFiles(fileType string)`
283 for all runtime files.
284
285
286 ## Autocomplete command arguments
287
288 See this example to learn how to use `MakeCompletion` and `MakeCommand`
289
290 ```lua
291 local function StartsWith(String,Start)
292     String = String:upper()
293     Start = Start:upper() 
294     return string.sub(String,1,string.len(Start))==Start
295 end
296
297 function complete(input)
298     local allCompletions = {"Hello", "World", "Foo", "Bar"}
299     local result = {}
300
301     for i,v in pairs(allCompletions) do
302         if StartsWith(v, input) then
303             table.insert(result, v)
304         end
305     end
306     return result
307 end
308
309 function foo(arg)
310     messenger:Message(arg)
311 end
312
313 MakeCommand("foo", "example.foo", MakeCompletion("example.complete"))
314 ```
315
316
317 ## Default plugins
318
319 For examples of plugins, see the default `autoclose` and `linter` plugins
320 (stored in the normal micro core repo under `runtime/plugins`) as well as any
321 plugins that are stored in the official channel
322 [here](https://github.com/micro-editor/plugin-channel).
323
324
325 ## Plugin Manager
326
327 Micro also has a built in plugin manager which you can invoke with the
328 `> plugin ...` command.
329
330 For the valid commands you can use, see the `commands` help topic.
331
332 The manager fetches plugins from the channels (which is simply a list of plugin
333 metadata) which it knows about. By default, micro only knows about the official
334 channel which is located at github.com/micro-editor/plugin-channel but you can
335 add your own third-party channels using the `pluginchannels` option and you can
336 directly link third-party plugins to allow installation through the plugin
337 manager with the `pluginrepos` option.
338
339 If you'd like to publish a plugin you've made as an official plugin, you should
340 upload your plugin online (to Github preferably) and add a `repo.json` file.
341 This file will contain the metadata for your plugin. Here is an example:
342
343 ```json
344 [{
345   "Name": "pluginname",
346   "Description": "Here is a nice concise description of my plugin",
347   "Tags": ["python", "linting"],
348   "Versions": [
349     {
350       "Version": "1.0.0",
351       "Url": "https://github.com/user/plugin/archive/v1.0.0.zip",
352       "Require": {
353         "micro": ">=1.0.3"
354       }
355     }
356   ]
357 }]
358 ```
359
360 Then open a pull request at github.com/micro-editor/plugin-channel adding a link
361 to the raw `repo.json` that is in your plugin repository. To make updating the
362 plugin work, the first line of your plugins lua code should contain the version
363 of the plugin. (Like this: `VERSION = "1.0.0"`) Please make sure to use
364 [semver](http://semver.org/) for versioning.