]> git.lizzy.rs Git - micro.git/blob - runtime/help/plugins.md
Merge pull request #704 from zyedidia/multiple-cursors
[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
8 plugin to run code at times other than startup. The naming scheme is
9 `onAction(view)`. For example a function which is run every time the user saves
10 the buffer would be:
11
12 ```lua
13 function onSave(view)
14     ...
15     return false
16 end
17 ```
18
19 The `view` variable is a reference to the view the action is being executed on.
20 This is almost always the current view, which you can get with `CurView()` as 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
35 should 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
38 want a callback before the action is executed, use `preAction()`. In this case
39 the boolean returned specifies whether or not the action should be executed
40 after the lua code completes.
41
42 Another useful callback to know about which is not a 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 filetype,
45 for example turning off `tabstospaces` only for Go files when they are opened.
46
47 ---
48
49 There are a number of functions and variables that are available to you in
50 order to access the inner workings of micro. Here is a list (the type signatures
51 for functions are given using Go's type system):
52
53 * `OS`: variable which gives the OS micro is currently running on (this is the same
54 as Go's GOOS variable, so `darwin`, `windows`, `linux`, `freebsd`...)
55
56 * `configDir`: contains the path to the micro configuration files
57
58 * `tabs`: a list of all the tabs currently in use
59
60 * `curTab`: the index of the current tabs in the tabs list
61
62 * `messenger`: lets you send messages to the user or create prompts
63
64 * `NewBuffer(text, path string) *Buffer`: creates a new buffer from a given reader with a given path
65
66 * `GetLeadingWhitespace() bool`: returns the leading whitespace of the given string
67
68 * `IsWordChar(str string) bool`: returns whether or not the string is a 'word character'
69
70 * `RuneStr(r rune) string`: returns a string containing the given rune
71
72 * `Loc(x, y int) Loc`: returns a new `Loc` struct
73
74 * `JoinPaths(dir... string) string` combines multiple directories to a full path
75
76 * `DirectoryName(path string)` returns all but the last element of path ,typically the path's directory
77
78 * `GetOption(name string)`: returns the value of the requested option
79
80 * `AddOption(name string, value interface{})`: sets the given option with the given
81    value (`interface{}` means any type in Go)
82
83 * `SetOption(option, value string)`: sets the given option to the value. This will
84    set the option globally, unless it is a local only option.
85
86 * `SetLocalOption(option, value string, view *View)`: sets the given option to
87    the value locally in the given buffer
88
89 * `BindKey(key, action string)`: binds `key` to `action`
90
91 * `MakeCommand(name, function string, completions ...Completion)`: 
92    creates a command with `name` which will call `function` when executed.
93    Use 0 for completions to get NoCompletion.
94
95 * `MakeCompletion(function string)`:
96    creates a `Completion` to use with `MakeCommand`
97
98 * `CurView()`: returns the current view
99
100 * `HandleCommand(cmd string)`: runs the given command
101
102 * `HandleShellCommand(shellCmd string, interactive bool, waitToClose bool)`: runs the given shell
103    command. The `interactive` bool specifies whether the command should run in the background. The
104    `waitToClose` bool only applies if `interactive` is true and means that it should wait before
105    returning to the editor.
106
107 * `ToCharPos(loc Loc, buf *Buffer) int`: returns the character position of a given x, y location
108
109 * `Reload`: (Re)load everything
110
111 * `ByteOffset(loc Loc, buf *Buffer) int`: exactly like `ToCharPos` except it it counts bytes instead of runes
112
113 * `JobSpawn(cmdName string, cmdArgs []string, onStdout, onStderr, onExit string, userargs ...string)`:
114    Starts running the given process in the background. `onStdout` `onStderr` and `onExit`
115    are callbacks to lua functions which will be called when the given actions happen
116    to the background process.
117    `userargs` are the arguments which will get passed to the callback functions
118
119 * `JobStart(cmd string, onStdout, onStderr, onExit string, userargs ...string)`:
120    Starts running the given shell command in the background. Note that the command execute
121    is first parsed by a shell when using this command. It is executed with `sh -c`.
122
123 * `JobSend(cmd *exec.Cmd, data string)`: send a string into the stdin of the job process
124
125 * `JobStop(cmd *exec.Cmd)`: kill a job
126
127 This may seem like a small list of available functions but some of the objects
128 returned by the functions have many methods. `CurView()` returns a view object
129 which has all the actions which you can call. For example `CurView():Save(false)`.
130 You can see the full list of possible actions in the keybindings help topic.
131 The boolean on all the actions indicates whether or not the lua callbacks should
132 be run. I would recommend generally sticking to false when making a plugin to
133 avoid recursive problems, for example if you call `CurView():Save(true)` in `onSave()`.
134 Just use `CurView():Save(false)` so that it won't call `onSave()` again.
135
136 Using the view object, you can also access the buffer associated with that view
137 by using `CurView().Buf`, which lets you access the `FileType`, `Path`, `Name`...
138
139 The possible methods which you can call using the `messenger` variable are:
140
141 * `messenger.Message(msg ...interface{})`
142 * `messenger.Error(msg ...interface{})`
143 * `messenger.YesNoPrompt(prompt string) (bool, bool)`
144 * `messenger.Prompt(prompt, historyType string, completionType Completion) (string, bool)`
145
146 If you want a standard prompt, just use `messenger.Prompt(prompt, "", 0)`
147
148 # Adding help files, syntax files, or colorschemes in your plugin
149
150 You can use the `AddRuntimeFile(name, type, path string)` function to add various kinds of
151 files to your plugin. For example, if you'd like to add a help topic to your plugin
152 called `test`, you would create a `test.md` file, and call the function:
153
154 ```lua
155 AddRuntimeFile("test", "help", "test.md")
156 ```
157
158 Use `AddRuntimeFilesFromDirectory(name, type, dir, pattern)` to add a number of files
159 to the runtime.
160 To read the content of a runtime file use `ReadRuntimeFile(fileType, name string)`
161 or `ListRuntimeFiles(fileType string)` for all runtime files.
162
163 # Autocomplete command arguments
164
165 See this example to learn how to use `MakeCompletion` and `MakeCommand`
166
167 ```lua
168 local function StartsWith(String,Start)
169     String = String:upper()
170     Start = Start:upper() 
171     return string.sub(String,1,string.len(Start))==Start
172 end
173
174 function complete(input)
175     local allCompletions = {"Hello", "World", "Foo", "Bar"}
176     local result = {}
177
178     for i,v in pairs(allCompletions) do
179         if StartsWith(v, input) then
180             table.insert(result, v)
181         end
182     end
183     return result
184 end
185
186 function foo(arg)
187     messenger:Message(arg)
188 end
189
190 MakeCommand("foo", "example.foo", MakeCompletion("example.complete"))
191 ```
192
193 # Default plugins
194
195 For examples of plugins, see the default `autoclose` and `linter` plugins
196 (stored in the normal micro core repo under `runtime/plugins`) as well as
197 any plugins that are stored in the official channel [here](https://github.com/micro-editor/plugin-channel).
198
199 # Plugin Manager
200
201 Micro also has a built in plugin manager which you can invoke with the `> plugin ...` command.
202
203 For the valid commands you can use, see the `command` help topic.
204
205 The manager fetches plugins from the channels (which is simply a list of plugin metadata)
206 which it knows about. By default, micro only knows about the official channel which is located
207 at github.com/micro-editor/plugin-channel but you can add your own third-party channels using
208 the `pluginchannels` option and you can directly link third-party plugins to allow installation
209 through the plugin manager with the `pluginrepos` option.
210
211 If you'd like to publish a plugin you've made as an official plugin, you should upload your
212 plugin online (to Github preferably) and add a `repo.json` file. This file will contain the
213 metadata for your plugin. Here is an example:
214
215 ```json
216 [{
217   "Name": "pluginname",
218   "Description": "Here is a nice concise description of my plugin",
219   "Tags": ["python", "linting"],
220   "Versions": [
221     {
222       "Version": "1.0.0",
223       "Url": "https://github.com/user/plugin/archive/v1.0.0.zip",
224       "Require": {
225         "micro": ">=1.0.3"
226       }
227     }
228   ]
229 }]
230 ```
231
232 Then open a pull request at github.com/micro-editor/plugin-channel adding a link to the
233 raw `repo.json` that is in your plugin repository.
234 To make updating the plugin work, the first line of your plugins lua code should contain the version of the plugin. (Like this: `VERSION = "1.0.0"`)
235 Please make sure to use [semver](http://semver.org/) for versioning.