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