Update Micro :)

Signed-off-by: The-Repo-Club <wayne6324@gmail.com>
This commit is contained in:
The-Repo-Club 2022-09-06 18:43:43 +01:00
parent b985761ecf
commit 0bfc0b623a
No known key found for this signature in database
GPG Key ID: E30EC2FBFB05C44F
86 changed files with 14237 additions and 0 deletions

View File

@ -0,0 +1,43 @@
# Minimal Mistakes Micro Theme
color-link comment "#81a1c1"
color-link identifier "#59ff59"
color-link identifier.class "#59fff9"
color-link identifier.var "#e5e9f0"
color-link constant "#9059ff"
color-link constant.number "#e5e9f0"
color-link constant.string "#ffff59"
color-link symbol "#ff59f9"
color-link symbol.brackets "#e5e9f0"
color-link symbol.tag "#AE81FF"
color-link type "italic #59fff9"
color-link type.keyword "#ff59f9"
color-link special "#ff59f9"
color-link statement "#ff59f9"
color-link preproc "#ff59f9"
color-link underlined "#ff59f9"
color-link error "bold #ff5959"
color-link todo "bold #ff59f9"
color-link diff-added "#59ff59"
color-link diff-modified "#ff59f9"
color-link diff-deleted "#ff5959"
color-link gutter-error "#ff5959"
color-link gutter-warning "#E6DB74"
color-link statusline "#e5e9f0,#434c5e"
color-link tabbar "#283036,#81a1c1"
color-link indent-char "#434c5e"
color-link line-number "#434c5e"
color-link current-line-number "#e5e9f0"
color-link cursor-line "#434c5e,#e5e9f0"
color-link color-column "#434c5e"
color-link type.extended "default"

View File

@ -0,0 +1,13 @@
{
"Alt-/": "lua:comment.comment",
"Alt-a": "lua:snippets.Accept",
"Alt-d": "command:definition",
"Alt-f": "command:format",
"Alt-k": "command:hover",
"Alt-r": "command:references",
"Alt-s": "lua:snippets.Insert",
"Alt-w": "lua:snippets.Next",
"Alt-t": "command:tree",
"CtrlSpace": "command:lspcompletion",
"CtrlUnderscore": "lua:comment.comment"
}

Binary file not shown.

View File

@ -0,0 +1,42 @@
color-link default "#F8F8F2,#282A36"
color-link comment "#6272A4"
color-link identifier "#50FA7B"
color-link identifier.class "#8BE9FD"
color-link identifier.var "#F8F8F2"
color-link constant "#BD93F9"
color-link constant.number "#F8F8F2"
color-link constant.string "#F1FA8C"
color-link symbol "#FF79C6"
color-link symbol.brackets "#F8F8F2"
color-link symbol.tag "#AE81FF"
color-link type "italic #8BE9FD"
color-link type.keyword "#FF79C6"
color-link special "#FF79C6"
color-link statement "#FF79C6"
color-link preproc "#FF79C6"
color-link underlined "#FF79C6"
color-link error "bold #FF5555"
color-link todo "bold #FF79C6"
color-link diff-added "#50FA7B"
color-link diff-modified "#FFB86C"
color-link diff-deleted "#FF5555"
color-link gutter-error "#FF5555"
color-link gutter-warning "#E6DB74"
color-link statusline "#282A36,#F8F8F2"
color-link tabbar "#282A36,#F8F8F2"
color-link indent-char "#6272A4"
color-link line-number "#6272A4"
color-link current-line-number "#F8F8F2"
color-link cursor-line "#44475A,#F8F8F2"
color-link color-column "#44475A"
color-link type.extended "default"

View File

@ -0,0 +1,43 @@
# Minimal Mistakes Micro Theme
color-link comment "#81a1c1"
color-link identifier "#59ff59"
color-link identifier.class "#59fff9"
color-link identifier.var "#e5e9f0"
color-link constant "#9059ff"
color-link constant.number "#e5e9f0"
color-link constant.string "#ffff59"
color-link symbol "#ff59f9"
color-link symbol.brackets "#e5e9f0"
color-link symbol.tag "#AE81FF"
color-link type "italic #59fff9"
color-link type.keyword "#ff59f9"
color-link special "#ff59f9"
color-link statement "#ff59f9"
color-link preproc "#ff59f9"
color-link underlined "#ff59f9"
color-link error "bold #ff5959"
color-link todo "bold #ff59f9"
color-link diff-added "#59ff59"
color-link diff-modified "#ff59f9"
color-link diff-deleted "#ff5959"
color-link gutter-error "#ff5959"
color-link gutter-warning "#E6DB74"
color-link statusline "#e5e9f0,#434c5e"
color-link tabbar "#283036,#81a1c1"
color-link indent-char "#434c5e"
color-link line-number "#434c5e"
color-link current-line-number "#e5e9f0"
color-link cursor-line "#434c5e,#e5e9f0"
color-link color-column "#434c5e"
color-link type.extended "default"

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Ján Priner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,4 @@
# Aspell plugin for Micro
This is a spellchecking plugin for [Micro](https://micro-editor.github.io/) editor.
For help see [the help file](help/aspell.md).

View File

@ -0,0 +1,658 @@
VERSION = "1.3.0"
local micro = import("micro")
local shell = import("micro/shell")
local buffer = import("micro/buffer")
local config = import("micro/config")
local util = import("micro/util")
local utf = import("unicode/utf8")
config.RegisterCommonOption("aspell", "check", "auto")
config.RegisterCommonOption("aspell", "lang", "")
config.RegisterCommonOption("aspell", "dict", "")
config.RegisterCommonOption("aspell", "sugmode", "normal")
config.RegisterCommonOption("aspell", "args", "")
function init()
config.MakeCommand("addpersonal", addpersonal, config.NoComplete)
config.MakeCommand("acceptsug", acceptsug, config.NoComplete)
config.MakeCommand("togglecheck", togglecheck, config.NoComplete)
config.AddRuntimeFile("aspell", config.RTHelp, "help/aspell.md")
end
local filterModes = {
xml = "sgml",
["c++"] = "ccpp",
c = "ccpp",
html = "html",
html4 = "html",
html5 = "html",
perl = "perl",
perl6 = "perl",
tex = "tex",
markdown = "markdown",
groff = "nroff",
man = "nroff",
["git-commit"] = "url",
mail = "email"
-- Aspell has comment mode, in which only lines starting with # are checked
-- but it doesn't work for some reason
}
local lock = false
local next = nil
function runAspell(buf, onExit, ...)
local options = {"pipe", "--encoding=utf-8"}
if filterModes[buf:FileType()] then
options[#options + 1] = "--mode=" .. filterModes[buf:FileType()]
end
if buf.Settings["aspell.lang"] ~= "" then
options[#options + 1] = "--lang=" .. buf.Settings["aspell.lang"]
end
if buf.Settings["aspell.dict"] ~= "" then
options[#options + 1] = "--master=" .. buf.Settings["aspell.dict"]
end
if buf.Settings["aspell.sugmode"] ~= "" then
options[#options + 1] = "--sug-mode=" .. buf.Settings["aspell.sugmode"]
end
for _, argument in ipairs(split(buf.Settings["aspell.args"], " ")) do
options[#options + 1] = argument
end
local job = shell.JobSpawn("aspell", options, nil,
nil, onExit, buf, unpack(arg))
-- Enable terse mode
shell.JobSend(job, "!\n")
for i=0, buf:LinesNum() - 1 do
local line = util.String(buf:LineBytes(i))
-- Escape for aspell (it interprets lines that start
-- with % @ ^ ! etc.)
line = "^" .. line .. "\n"
shell.JobSend(job, line)
end
job.Stdin:Close()
end
function spellcheck(buf)
local check = buf.Settings["aspell.check"]
local readcheck = buf.Type.Readonly
if (check == "on" or (check == "auto" and filterModes[buf:FileType()])) and (not readcheck) then
if lock then
next = buf
else
lock = true
runAspell(buf, highlight)
end
else
-- If we aren't supposed to spellcheck, clear the messages
buf:ClearMessages("aspell")
end
end
-- Parses the output of Aspell and returns the list of all misspells.
function parseOutput(out)
local patterns = {"^# (.-) (%d+)$", "^& (.-) %d+ (%d+): (.+)$"}
if out:find("command not found") then
micro.InfoBar():Error(
"Make sure that Aspell is installed and available in your PATH")
return {}
elseif not out:find("International Ispell Version") then
-- Something went wrong, we'll show what Aspell has to say
micro.InfoBar():Error("Aspell: " .. out)
return {}
end
local misspells = {}
local linenumber = 1
local lines = split(out, "\n")
for _, line in ipairs(lines) do
if line == "" then
linenumber = linenumber + 1
else
for _, pattern in ipairs(patterns) do
if string.find(line, pattern) then
local word, offset, suggestions = string.match(line, pattern)
offset = tonumber(offset)
local len = utf.RuneCountInString(word)
misspells[#misspells + 1] = {
word = word,
mstart = buffer.Loc(offset - 1, linenumber - 1),
mend = buffer.Loc(offset - 1 + len, linenumber - 1),
suggestions = suggestions and split(suggestions, ", ") or {},
}
end
end
end
end
return misspells
end
function highlight(out, args)
local buf = args[1]
buf:ClearMessages("aspell")
-- This is a hack that keeps the text shifted two columns to the right
-- even when no gutter messages are shown
local msg = "This message shouldn't be visible (Aspell plugin)"
local bmsg = buffer.NewMessageAtLine("aspell", msg, 0, buffer.MTError)
buf:AddMessage(bmsg)
for _, misspell in ipairs(parseOutput(out)) do
local msg = nil
if #(misspell.suggestions) > 0 then
msg = misspell.word .. " -> " .. table.concat(misspell.suggestions, ", ")
else
msg = misspell.word .. " ->X"
end
local bmsg = buffer.NewMessage("aspell", msg, misspell.mstart,
misspell.mend, buffer.MTWarning)
buf:AddMessage(bmsg)
end
lock = false
if next ~= nil then
spellcheck(next)
next = nil
end
end
function parseMessages(messages)
local patterns = {"^(.-) %-> (.+)$", "^(.-) %->X$"}
if messages == nil then
return {}
end
local misspells = {}
for i=1, #messages do
local message = messages[i]
if message.Owner == "aspell" then
for _, pattern in ipairs(patterns) do
if string.find(message.Msg, pattern) then
local word, suggestions = string.match(message.Msg, pattern)
misspells[#misspells + 1] = {
word = word,
mstart = -message.Start,
mend = -message.End,
suggestions = suggestions and split(suggestions, ", ") or {},
}
end
end
end
end
return misspells
end
function togglecheck(bp, args)
local buf = bp.Buf
local check = buf.Settings["aspell.check"]
if check == "on" or (check == "auto" and filterModes[buf:FileType()]) then
buf.Settings["aspell.check"] = "off"
else
buf.Settings["aspell.check"] = "on"
end
spellcheck(buf)
if args then
return
end
return true
end
function addpersonal(bp, args)
local buf = bp.Buf
local loc = buf:GetActiveCursor().Loc
for _, misspell in ipairs(parseMessages(buf.Messages)) do
local wordInBuf = util.String(buf:Substr(misspell.mstart, misspell.mend))
if loc:GreaterEqual(misspell.mstart) and loc:LessEqual(misspell.mend)
and wordInBuf == misspell.word then
local options = {"pipe", "--encoding=utf-8"}
if buf.Settings["aspell.lang"] ~= "" then
options[#options + 1] = "--lang=" .. buf.Settings["aspell.lang"]
end
if buf.Settings["aspell.dict"] ~= "" then
options[#options + 1] = "--master=" .. buf.Settings["aspell.dict"]
end
for _, argument in ipairs(split(buf.Settings["aspell.args"], " ")) do
options[#options + 1] = argument
end
local job = shell.JobSpawn("aspell", options, nil, nil, function ()
spellcheck(buf)
end)
shell.JobSend(job, "*" .. misspell.word .. "\n#\n")
job.Stdin:Close()
if args then
return
end
return true
end
end
if args then
return
end
return false
end
function acceptsug(bp, args)
local buf = bp.Buf
local n = nil
if args and #args > 0 then
n = tonumber(args[1])
end
local loc = buf:GetActiveCursor().Loc
for _, misspell in ipairs(parseMessages(buf.Messages)) do
local wordInBuf = util.String(buf:Substr(misspell.mstart, misspell.mend))
if loc:GreaterEqual(misspell.mstart) and loc:LessEqual(misspell.mend)
and wordInBuf == misspell.word then
if misspell.suggestions[n] then
-- If n is in the range we'll accept n-th suggestion
buf:GetActiveCursor():GotoLoc(misspell.mend)
buf:Replace(misspell.mstart, misspell.mend, misspell.suggestions[n])
spellcheck(buf)
if args then
return
end
return true
elseif #(misspell.suggestions) > 0 then
-- If n is 0 indicating acceptsug was called with no arguments
-- we will cycle through the suggestions autocomplete-like
buf:GetActiveCursor():GotoLoc(misspell.mend)
buf:Remove(misspell.mstart, misspell.mend)
buf:Autocomplete(function ()
return misspell.suggestions, misspell.suggestions
end)
spellcheck(buf)
if args then
return
end
return true
end
end
end
if args then
return
end
return false
end
function split(str, pat)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t, cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
-- We need to spellcheck every time, the buffer is modified. Sadly there's
-- no such thing as onBufferModified()
function onBufferOpen(buf)
spellcheck(buf)
end
-- The following callbacks are undocumented
function onRune(bp)
spellcheck(bp.Buf)
end
function onCycleAutocompleteBack(bp)
spellcheck(bp.Buf)
end
-- The following were copied from help keybindings
-- function onCursorUp(bp)
-- end
-- function onCursorDown(bp)
-- end
-- function onCursorPageUp(bp)
-- end
-- function onCursorPageDown(bp)
-- end
-- function onCursorLeft(bp)
-- end
-- function onCursorRight(bp)
-- end
-- function onCursorStart(bp)
-- end
-- function onCursorEnd(bp)
-- end
-- function onSelectToStart(bp)
-- end
-- function onSelectToEnd(bp)
-- end
-- function onSelectUp(bp)
-- end
-- function onSelectDown(bp)
-- end
-- function onSelectLeft(bp)
-- end
-- function onSelectRight(bp)
-- end
-- function onSelectToStartOfText(bp)
-- end
-- function onSelectToStartOfTextToggle(bp)
-- end
-- function onWordRight(bp)
-- end
-- function onWordLeft(bp)
-- end
-- function onSelectWordRight(bp)
-- end
-- function onSelectWordLeft(bp)
-- end
function onMoveLinesUp(bp)
spellcheck(bp.Buf)
end
function onMoveLinesDown(bp)
spellcheck(bp.Buf)
end
function onDeleteWordRight(bp)
spellcheck(bp.Buf)
end
function onDeleteWordLeft(bp)
spellcheck(bp.Buf)
end
-- function onSelectLine(bp)
-- end
-- function onSelectToStartOfLine(bp)
-- end
-- function onSelectToEndOfLine(bp)
-- end
function onInsertNewline(bp)
spellcheck(bp.Buf)
end
function onInsertSpace(bp)
spellcheck(bp.Buf)
end
function onBackspace(bp)
spellcheck(bp.Buf)
end
function onDelete(bp)
spellcheck(bp.Buf)
end
-- function onCenter(bp)
-- end
function onInsertTab(bp)
spellcheck(bp.Buf)
end
-- function onSave(bp)
-- end
-- function onSaveAll(bp)
-- end
-- function onSaveAs(bp)
-- end
-- function onFind(bp)
-- end
-- function onFindLiteral(bp)
-- end
-- function onFindNext(bp)
-- end
-- function onFindPrevious(bp)
-- end
function onUndo(bp)
spellcheck(bp.Buf)
end
function onRedo(bp)
spellcheck(bp.Buf)
end
-- function onCopy(bp)
-- end
-- function onCopyLine(bp)
-- end
function onCut(bp)
spellcheck(bp.Buf)
end
function onCutLine(bp)
spellcheck(bp.Buf)
end
function onDuplicateLine(bp)
spellcheck(bp.Buf)
end
function onDeleteLine(bp)
spellcheck(bp.Buf)
end
function onIndentSelection(bp)
spellcheck(bp.Buf)
end
function onOutdentSelection(bp)
spellcheck(bp.Buf)
end
function onOutdentLine(bp)
spellcheck(bp.Buf)
end
function onIndentLine(bp)
spellcheck(bp.Buf)
end
function onPaste(bp)
spellcheck(bp.Buf)
end
-- function onSelectAll(bp)
-- end
-- function onOpenFile(bp)
-- end
-- function onStart(bp)
-- end
-- function onEnd(bp)
-- end
-- function onPageUp(bp)
-- end
-- function onPageDown(bp)
-- end
-- function onSelectPageUp(bp)
-- end
-- function onSelectPageDown(bp)
-- end
-- function onHalfPageUp(bp)
-- end
-- function onHalfPageDown(bp)
-- end
-- function onStartOfLine(bp)
-- end
-- function onEndOfLine(bp)
-- end
-- function onStartOfText(bp)
-- end
-- function onStartOfTextToggle(bp)
-- end
-- function onParagraphPrevious(bp)
-- end
-- function onParagraphNext(bp)
-- end
-- function onToggleHelp(bp)
-- end
-- function onToggleDiffGutter(bp)
-- end
-- function onToggleRuler(bp)
-- end
-- function onJumpLine(bp)
-- end
-- function onClearStatus(bp)
-- end
-- function onShellMode(bp)
-- end
-- function onCommandMode(bp)
-- end
-- function onQuit(bp)
-- end
-- function onQuitAll(bp)
-- end
-- function onAddTab(bp)
-- end
-- function onPreviousTab(bp)
-- end
-- function onNextTab(bp)
-- end
-- function onNextSplit(bp)
-- end
-- function onUnsplit(bp)
-- end
-- function onVSplit(bp)
-- end
-- function onHSplit(bp)
-- end
-- function onPreviousSplit(bp)
-- end
-- function onToggleMacro(bp)
-- end
function onPlayMacro(bp)
spellcheck(bp.Buf)
end
-- function onSuspend(bp) -- Unix only
-- end
-- function onScrollUp(bp)
-- end
-- function onScrollDown(bp)
-- end
-- function onSpawnMultiCursor(bp)
-- end
-- function onSpawnMultiCursorUp(bp)
-- end
-- function onSpawnMultiCursorDown(bp)
-- end
-- function onSpawnMultiCursorSelect(bp)
-- end
-- function onRemoveMultiCursor(bp)
-- end
-- function onRemoveAllMultiCursors(bp)
-- end
-- function onSkipMultiCursor(bp)
-- end
-- function onNone(bp)
-- end
-- function onJumpToMatchingBrace(bp)
-- end
function onAutocomplete(bp)
spellcheck(bp.Buf)
end

View File

@ -0,0 +1,76 @@
# Aspell plugin
The text will be checked for misspells as you type. It understands the syntax
of XML, HTML, TeX and Markdown. On C++, C and Perl only comments and string
literals will be checked.
You need to have Aspell installed and available in your PATH. It does not come
with this plugin. If you are on Windows, you can install Aspell through
[MSYS2](https://www.msys2.org/).
## Options
* `aspell.check`: controls whether spellchecking is performed. Possible values
are `on`, `off` and `auto`. When set to `auto`, the file will be checked
only if it's one of these filetypes: XML, C++, C, HTML, Perl, TeX,
Markdown, Groff/Troff, Manpage, Email or Git commit. Defaults to `auto`.
* `aspell.lang`: language to use. Two letter language code, optionally followed
by an underscore or a dash and a two letter country code. It will be passed
to Aspell in the `--lang` option.
* `aspell.dict`: dictionary to use. Run `aspell dicts` in a terminal to see
available dictionaries. It will be passed to Aspell in the `--master` option.
If both `aspell.dict` and `aspell.lang` are left empty (which is the default),
Aspell will follow locale settings.
* `aspell.sugmode`: one of `ultra`, `fast`, `normal`, `slow` or `bad-spellers`.
It will be passed to Aspell in the `--sug-mode` option. Defaults to `normal`.
You may wish to change it to `fast`, if you feel that the spellchecking is
too slow. For an explanation of what each option does, see
http://aspell.net/man-html/Notes-on-the-Different-Suggestion-Modes.html
* `aspell.args`: additional command line arguments, that will be passed to
Aspell.
When you change some of these settings while in Micro using `setlocal` or
`set`, you might not see the effect until you modify a buffer.
You can also disable or enable spellchecking for specific file types in your
`settings.json`:
```json
{
"*.txt": {
"aspell.check": "on"
},
"ft:markdown": {
"aspell.check": "off"
}
}
```
## Commands
* `togglecheck`: turns the spellchecking on/off. You can bind it to a key as
`lua:aspell.addpersonal`. The effect's the same as changing `aspell.check`
using `setlocal`.
* `addpersonal`: adds the word the cursor is on to your personal dictionary, so
that it won't be highlighted as a misspell anymore. You can bind it to a key
as `lua:aspell.addpersonal`.
* `acceptsug 'n'?`: accepts the nth suggestion for the word the cursor is on.
You can bind it to a key as `lua:aspell.acceptsug`. If `n` is not provided or
this command is invoked with a keyboard shortcut, it will start to cycle
through the suggestions. Use `Tab` and `Backtab` to cycle through them.
You can also use them in chain keybindings with `,`, `&` and `|` (see
`help keybindings`). Example `bindings.json`:
```json
{
"Tab": "Autocomplete|lua:aspell.acceptsug|IndentSelection|InsertTab"
}
```

View File

@ -0,0 +1,43 @@
[{
"Name": "aspell",
"Description": "Spellchecking with Aspell",
"Tags": ["spellchecking", "spelling", "aspell", "spellchecker"],
"Website": "https://github.com/priner/micro-aspell-plugin",
"Versions": [
{
"Version": "1.3.0",
"Url": "https://github.com/priner/micro-aspell-plugin/archive/v1.3.0.zip",
"Require": {
"micro": ">=2.0.7"
}
},
{
"Version": "1.2.1",
"Url": "https://github.com/priner/micro-aspell-plugin/archive/v1.2.1.zip",
"Require": {
"micro": ">=2.0.7"
}
},
{
"Version": "1.2.0",
"Url": "https://github.com/priner/micro-aspell-plugin/archive/v1.2.0.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.1.0",
"Url": "https://github.com/priner/micro-aspell-plugin/archive/v1.1.0.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.0.0",
"Url": "https://github.com/priner/micro-aspell-plugin/archive/v1.0.0.zip",
"Require": {
"micro": ">=2.0.0"
}
}
]
}]

View File

@ -0,0 +1,33 @@
# BOUNCE
micro-bounce is a plugin for the excellent [micro editor](https://github.com/zyedidia/micro).
It provides various cursor manipulations:
- smartHome: bounce between start of text and start of line, in that order
- bounce: bounce between matching brackets
- save/recall cursor location: save your spot in a file and jump back to it
## Installation
micro-bounce is part of the official plugin channel. To install simply run the below command:
`> plugin install bounce`
## Setup / Usage
After installing, restart micro then run 'help bounce' to see how to bound the various plugin
functions to shortcuts.
`> help bounce`
## Tip / Example
Getting back to the cursor location in a file after executing a find is a good use of the cursor saving functions the bounce plugin provides.
Replace the default binding for CtrlF as shown:
`"CtrlF": "lua:bounce.keepLoc,Find"`
This will save the cursor location, then execute micro's find function. After you're done with your search you can call the bounce.gotoStoredLoc function to return to where the cursor was when the search was initiated.

View File

@ -0,0 +1,61 @@
VERSION = "2.0.0"
local micro = import("micro")
local config = import("micro/config")
local shell = import("micro/shell")
local buffer = import("micro/buffer")
-- NOTE: it's up to the user to bind the below functions to key presses.
function init()
config.AddRuntimeFile("bounce", config.RTHelp, "help/bounce.md")
end
-- bounce cursor between start of line and first non-whitespace character
-- slightly different than how micro's default home works, this is first non-whitespace
-- character, then start of line. micro works backwards, start of line, then
-- the first non-whitespace character
function smartHome(bp)
local c = bp.Buf:GetActiveCursor()
local origX = c.Loc.X
c:StartOfText()
if origX == c.Loc.X then
c:Start()
end
bp:Relocate()
end
-- bounce cursor between matching brackets
function bounce(bp)
local bracketPairs = { {123,125}, {91,93}, {40,41} }
local c = bp.Buf:GetActiveCursor()
local start = -c.Loc
for k,b in pairs(bracketPairs) do
local matchLoc, onLeft, ok = bp.Buf:FindMatchingBrace(b,-c.Loc)
if ok then
c:GotoLoc(matchLoc)
if onLeft then
local nudge = buffer.Loc(c.X-1, c.Y)
c:GotoLoc(nudge)
end
bp:Relocate()
return
end
end
end
-- keepLoc / gotoStoredLoc - easier than memorizing line numbers
local storedLoc = {}
function keepLoc(bp)
storedLoc[bp.Buf.AbsPath] = -bp.Cursor.Loc
end
function gotoStoredLoc(bp)
local name = bp.Buf.AbsPath
if storedLoc[name] ~= nil then
bp.Cursor:GotoLoc(storedLoc[name])
bp.Cursor:ResetSelection()
bp:Relocate()
end
end

View File

@ -0,0 +1,60 @@
# Bounce Plugin
The bounce plugin adds some nano-like functionality I felt was missing from micro.
It's called 'bounce' because all features involving moving (bouncing) the cursor
around.
## Smart Home
The `smartHome` function is an alternative home-button function.
Calling the smartHome function sends the cursor to the start of text (first
non-whitespace character). Pressing again sends the cursor to the start of the line.
### Using
Once the plugin is installed, to use simply bind a key to the smartHome function:
In bindings.json: `"Home":"lua:bounce.smartHome",`
Or from micro's commandline: `> bind Home "lua:bounce.smartHome"`
## Matching Bracket Bounce
Bracket bounce bounces the cursor between matching brackets, currently: {,[,(. and
their closing counterparts: },],)
### Using
To use, bind a key to the bounce function:
From micro's commandline: `> bind Alt-G "lua:bounce.bounce"`
When the cursor is overtop a bracket, press the bound button to move the cursor
to the matching bracket.
The plugin uses micro's bracket matching function, so the cursor will always move
to where micro has highlighted the matching bracket, (or fail to move,
if micro has failed to match).
## Cursor Location Saving
The below pair of functions allow you to store and jump to a cursor location. This
location is *not* persistent across multiple instance of micro nor is it saved
upon exiting. The location is unique per absolute file path (so new tabs with no
filename share the same saved cursor location). An example use-case is saving your
location before doing a search or replace command. Once done with your search, you can
jump back to where you were.
The below command bound to Ctrl-K will store the current cursor location.
`> bind CtrlK "lua:bounce.keepLoc"`
The below command bound to Ctrl-G will move the location to the saved position.
`> bind CtrlG "lua:bounce.gotoStoredLoc"`
## Bugs And Feature Requests
Please file issues and feature requests on github:
https://github.com/deusnefum/micro-bounce

View File

@ -0,0 +1,35 @@
[{
"Name": "bounce",
"Description": "plugin to add nano-style 'smart home' and bounce cursor between matching brackets",
"Tags": ["bounce", "smarthome"],
"Versions": [
{
"Version": "1.1.2",
"Url": "https://github.com/deusnefum/micro-bounce/archive/v1.1.2.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.1.1",
"Url": "https://github.com/deusnefum/micro-bounce/archive/v1.1.1.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.1.0",
"Url": "https://github.com/deusnefum/micro-bounce/archive/v1.1.0.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.0.0",
"Url": "https://github.com/deusnefum/micro-bounce/archive/v1.0.0.zip",
"Require": {
"micro": ">=2.0.0"
}
}
]
}]

View File

@ -0,0 +1,17 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
charset = utf-8
end_of_line = lf
indent_style = tab
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
# Ignore .md files, because 2 spaces at end-of-line has meaning
[*.md]
trim_trailing_whitespace = false

View File

@ -0,0 +1,109 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [3.4.0] - 2018-10-22
### Fixed
- Issues with Lua's `io.popen` on some systems by using Micro's built-in `RunShellCommand` instead, [thanks to @scottbilas](https://github.com/NicolaiSoeborg/filemanager-plugin/pull/38)
### Added
- Adds the option `filemanager-openonstart` to allow auto-opening the file tree when Micro is started (default OFF)
### Changed
- Update README's option's documentation
## [3.3.1] - 2018-10-03
### Changed
- Performance improvement by removing unnecessary refresh of the opened file, [thanks to @jackwilsdon](https://github.com/NicolaiSoeborg/filemanager-plugin/pull/37)
## [3.3.0] - 2018-09-13
### Added
- The ability to sort folders above files, [thanks to @cbrown1](https://github.com/NicolaiSoeborg/filemanager-plugin/pull/33)
### Fixed
- The displayed filenames are now correctly only showing their "basename" on Windows
## [3.2.0] - 2018-02-15
### Added
- The ability to go to parent directory with left arrow (when not minimizing). Thanks @avently
- The ability to jump to the `..` as a "parent directory". Thanks @avently
## [3.1.2] - 2018-02-07
### Fixed
- The minimum Micro version, which was incorrectly set to v1.4.0. Ref [issue #28](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/28)
## [3.1.1] - 2018-02-04
### Fixed
Ref https://github.com/zyedidia/micro/issues/992 for both of these fixes.
- The syntax parser not loading correctly (mostly block comments) on opened files. **Requires Micro >= v1.4.0**
- An errant tab being inserted into the newly opened file.
## [3.1.0] - 2018-01-30
### Added
- The ability to hide dotfiles using the `filemanager-showdotfiles` option.
- The ability to hide files ignored in your VCS (aka `.gitignore`'d) using the `filemanager-showignored` option. Only works with Git at the moment.
- This `CHANGELOG.md`
### Fixed
- A bug with the `rm` command that caused weird, undefined behaviour to contents within the same dir as the file/dir deleted.
- Issue [#24](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/24)
## [3.0.0] - 2018-01-10
### Fixed
- Issues [#13](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/13), [#14](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/14), [#15](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/15), [#19](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/19), [#20](https://github.com/NicolaiSoeborg/filemanager-plugin/issues/20)
- The broken syntax highlighting
### Added
- Directory expansion/compression below itself for viewing more akin to a file tree.
- The `rm` command, which deletes the file/directory under the cursor.
- The `touch` command, which creates a file with the passed filename.
- The `mkdir` command, which creates a directory with the passed filename.
- An API, of sorts, for the user to rebind their keys to if they dislike the defaults.
- An [editorconfig](http://editorconfig.org/) file.
### Changed
- The view that it spawns in to read-only, which requires Micro version >= 1.3.5
- The functionality of some keybindings (when in the view) so they work safetly, or at all, with the plugin.
- From the `enter` key to `tab` for opening/going into files/dirs (a side-effect of using the read-only setting)
### Removed
- The ability to use a lot of keybindings that would otherwise mess with the view, and have no benifit.
- The pointless `.gitignore` file.
[unreleased]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.4.0...HEAD
[3.4.0]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.3.1...v3.4.0
[3.3.1]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.3.0...v3.3.1
[3.3.0]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.2.0...v3.3.0
[3.2.0]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.1.2...v3.2.0
[3.1.2]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.1.1...v3.1.2
[3.1.1]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.1.0...v3.1.1
[3.1.0]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v3.0.0...v3.1.0
[3.0.0]: https://github.com/NicolaiSoeborg/filemanager-plugin/compare/v2.1.1...v3.0.0

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Nicolai Søborg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,56 @@
# Filemanager Plugin
A simple plugin that allows for easy navigation of a file tree.
![Example picture](./example.jpg?raw=true "Example")
**Installation:** run `plugin install filemanager` and restart Micro.
## Basics
The top line always has the current directory's path to show you where you are.\
The `..` near the top is used to move back a directory, from your current position.
All directories have a `/` added to the end of it, and are syntax-highlighted as a `special` character.\
If the directory is expanded, there will be a `+` to the left of it. If it is collapsed there will be a `-` instead.
**NOTE:** If you change files without using the plugin, it can't know what you did. The only fix is to close and open the tree.
### Options
| Option | Purpose | Default |
| :--------------------------- | :----------------------------------------------------------- | :------ |
| `filemanager-showdotfiles` | Show dotfiles (hidden if false) | `true` |
| `filemanager-showignored` | Show gitignore'd files (hidden if false) | `true` |
| `filemanager-compressparent` | Collapse the parent dir when left is pressed on a child file | `true` |
| `filemanager-foldersfirst` | Sorts folders above any files | `true` |
| `filemanager-openonstart` | Automatically open the file tree when starting Micro | `false` |
### Commands and Keybindings
The keybindings below are the equivalent to Micro's defaults, and not actually set by the plugin. If you've changed any of those keybindings, then that key is used instead.
If you want to [keybind](https://github.com/zyedidia/micro/blob/master/runtime/help/keybindings.md#rebinding-keys) any of the operations/commands, bind to the labeled API in the table below.
| Command | Keybinding(s) | What it does | API for `bindings.json` |
| :------- | :------------------------- | :------------------------------------------------------------------------------------------ | :------------------------------------ |
| `tree` | - | Open/close the tree | `filemanager.toggle_tree` |
| - | <kbd>Tab</kbd> & MouseLeft | Open a file, or go into the directory. Goes back a dir if on `..` | `filemanager.try_open_at_cursor` |
| - | <kbd></kbd> | Expand directory in tree listing | `filemanager.uncompress_at_cursor` |
| - | <kbd></kbd> | Collapse directory listing | `filemanager.compress_at_cursor` |
| - | <kbd>Shift ⬆</kbd> | Go to the target's parent directory | `filemanager.goto_parent_dir` |
| - | <kbd>Alt Shift {</kbd> | Jump to the previous directory in the view | `filemanager.goto_next_dir` |
| - | <kbd>Alt Shift }</kbd> | Jump to the next directory in the view | `filemanager.goto_prev_dir` |
| `rm` | - | Prompt to delete the target file/directory your cursor is on | `filemanager.prompt_delete_at_cursor` |
| `rename` | - | Rename the file/directory your cursor is on, using the passed name | `filemanager.rename_at_cursor` |
| `touch` | - | Make a new file under/into the file/directory your cursor is on, using the passed name | `filemanager.new_file` |
| `mkdir` | - | Make a new directory under/into the file/directory your cursor is on, using the passed name | `filemanager.new_dir` |
#### Notes
- `rename`, `touch`, and `mkdir` require a name to be passed when calling.\
Example: `rename newnamehere`, `touch filenamehere`, `mkdir dirnamehere`.\
If the passed name already exists in the current dir, it will cancel instead of overwriting (for safety).
- The <kbd>Ctrl w</kbd> keybinding is to switch which buffer your cursor is on.\
This isn't specific to the plugin, it's just part of Micro, but many people seem to not know this.

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,38 @@
[
{
"Name": "filemanager",
"Description": "File manager for Micro",
"Tags": ["filetree", "filemanager", "file", "manager"],
"Website": "",
"Versions": [
{
"Version": "2.1.1",
"Url": "https://github.com/NicolaiSoeborg/filemanager-plugin/archive/v2.1.1.zip",
"Require": {
"micro": ">=1.3.2"
}
},
{
"Version": "3.1.0",
"Url": "https://github.com/NicolaiSoeborg/filemanager-plugin/archive/v3.1.0.zip",
"Require": {
"micro": ">=1.3.5"
}
},
{
"Version": "3.4.0",
"Url": "https://github.com/NicolaiSoeborg/filemanager-plugin/archive/v3.4.0.zip",
"Require": {
"micro": ">=1.4.1"
}
},
{
"Version": "3.5.0",
"Url": "https://github.com/NicolaiSoeborg/filemanager-plugin/archive/v3.4.0.zip",
"Require": {
"micro": ">=2.0.0-1"
}
}
]
}
]

View File

@ -0,0 +1,9 @@
filetype: filemanager
detect:
filename: "^filemanager$"
rules:
# The "..", the separator line thing, and directories
# Optionally, add this below to highlight the ascii line: "^─*$"
- special: "^\\.\\.$|\\-\\s.*|\\+\\s.*"

View File

@ -0,0 +1,6 @@
# Fish Plugin for Micro
This repository holds the fish plugin for micro.
Install with `> plugin install fish`. This plugin will let you automatically run
`fish_indent` from within micro.

View File

@ -0,0 +1,30 @@
VERSION = "0.2.0"
local micro = import("micro")
local config = import("micro/config")
local shell = import("micro/shell")
function init()
config.RegisterCommonOption("fish", "fmt", true)
config.MakeCommand("fishfmt", fishfmt, config.NoComplete)
config.AddRuntimeFile("fish", config.RTHelp, "help/fish-plugin.md")
end
function onSave(bp)
if bp.Buf:FileType() == "fish" then
if bp.Buf.Settings["fish.fmt"] then
fishfmt(bp)
end
end
end
function fishfmt(bp)
bp:Save()
local _, err = shell.RunCommand("fish_indent -w " .. bp.Buf.Path)
if err ~= nil then
micro.InfoBar():Error(err)
return
end
bp.Buf:ReOpen()
end

View File

@ -0,0 +1,15 @@
# Fish Plugin
The fish plugin provides some extra niceties for using micro with the fish
scripting language. The main thing this plugin does is run `fish_indent` for you
automatically.
You can run
```
> fishfmt
```
To automatically run it when you save the file, use the following option:
* `fishfmt`: run fish_indent on file saved. Default value: `on`

View File

@ -0,0 +1,22 @@
[{
"Name": "fish",
"Description": "plugin to make scripting in fish more pleasant",
"Tags": ["fish"],
"Website": "https://github.com/onodera-punpun/micro-fish-plugin",
"Versions": [
{
"Version": "0.2.0",
"Url": "https://github.com/onodera-punpun/micro-fish-plugin/archive/0.2.0.zip",
"Require": {
"micro": ">=2.0.0-1"
}
},
{
"Version": "0.1.1",
"Url": "https://github.com/onodera-punpun/micro-fish-plugin/archive/0.1.1.zip",
"Require": {
"micro": ">=1.0.3"
}
}
]
}]

View File

@ -0,0 +1 @@
Provides a `fzf` command in micro to open a file in the current pane using fzf.

View File

@ -0,0 +1,38 @@
VERSION = "1.1.1"
local micro = import("micro")
local shell = import("micro/shell")
local config = import("micro/config")
local buffer = import("micro/buffer")
function fzf(bp)
if shell.TermEmuSupported then
local err = shell.RunTermEmulator(bp, "fzf", false, true, fzfOutput, {bp})
if err ~= nil then
micro.InfoBar():Error(err)
end
else
local output, err = shell.RunInteractiveShell("fzf", false, true)
if err ~= nil then
micro.InfoBar():Error(err)
else
fzfOutput(output, {bp})
end
end
end
function fzfOutput(output, args)
local bp = args[1]
local strings = import("strings")
output = strings.TrimSpace(output)
if output ~= "" then
local buf, err = buffer.NewBufferFromFile(output)
if err == nil then
bp:OpenBuffer(buf)
end
end
end
function init()
config.MakeCommand("fzf", fzf, config.NoComplete)
end

View File

@ -0,0 +1,32 @@
[
{
"Name": "fzf",
"Description": "adds support to opening files via fzf",
"Website": "https://github.com/samdmarshall/micro-fzf-plugin",
"Tags": ["fzf"],
"Versions": [
{
"Version": "1.1.1",
"Url": "https://github.com/micro-editor/updated-plugins/releases/download/v1.0.0/fzf-1.1.1.zip",
"Require": {
"micro": ">=2.0.0-1"
}
},
{
"Version": "1.1.0",
"Url": "https://github.com/micro-editor/updated-plugins/releases/download/v1.0.0/fzf-1.1.0.zip",
"Require": {
"micro": ">=2.0.0-1"
}
},
{
"Version": "1.0.5",
"Url": "https://github.com/samdmarshall/micro-fzf-plugin/archive/v1.0.5.zip",
"Require": {
"micro": ">=1.1.2"
}
}
]
}
]

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Robert Kunze
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,93 @@
# Micro Plugin LSP Client
**Please note:** This software is very much not finished. It is more like a
proof of concept and might break if you call it names.
Provides LSP methods as actions to Micro that can subsequently be mapped to key
bindings.
Currently implemented methods:
- textDocument/hover
- textDocument/definition
- textDocument/completion
- textDocument/formatting
- textDocument/references
If possible, this plugin will register the following shortcuts:
- Alt-k for hover
- Alt-d for definition lookup
- Alt-f for formatting
- Alt-r for looking up references
- Ctrl-space for completion
## Installation
Clone this repo into micro's plug folder:
```
$ git clone https://github.com/AndCake/micro-plugin-lsp ~/.config/micro/plug/lsp
```
## Configuration
In your `settings.json`, you add the `lsp.server` option in order to enable
using it for your languages' server.
Example:
```
{
"lsp.server": "python=pyls,go=gopls,typescript=deno lsp,rust=rls",
"lsp.formatOnSave": true,
"lsp.ignoreMessages": "LS message1 to ignore|LS message 2 to ignore|...",
"lsp.tabcompletion": true,
"lsp.ignoreTriggerCharacters", "completion,signature",
"lsp.autocompleteDetails": false
}
```
The format for the `lsp.server` value is a comma-separated list for each file
type you want to boot up a language server:
```
<file type>=<executable with arguments where necessary>[=<initialization options passed to language server>][,...]
```
You can also use an environment variable called `MICRO_LSP` to define the same
information. If set, it will override the `lsp.server` from the `settings.json`.
You can add a line such as the following to your shell profile (e.g. .bashrc):
```
export MICRO_LSP='python=pyls,go=gopls,typescript=deno lsp={"importMap":"import_map.json"},rust=rls'
```
If neither the MICRO_LSP nor the lsp.server is set, then the plugin falls back
to the following settings:
```
python=pylsp,go=gopls,typescript=deno lsp,javascript=deno lsp,markdown=deno lsp,json=deno lsp,jsonc=deno lsp,rust=rls,lua=lua-lsp,c++=clangd
```
The option `lsp.autocompleteDetails` allows for showing all auto-completions in
a horizontally split buffer view (true) instead of the status line (false).
## Testing
This plugin has been tested briefly with the following language servers:
- C++ [clangd](https://clangd.llvm.org) /
[ccls](https://github.com/MaskRay/ccls)
- go: [gopls](https://pkg.go.dev/golang.org/x/tools/gopls#section-readme)
- markdown, JSON, typescript, javascript (including JSX/TSX):
[deno](https://deno.land/)
- python: pyls, [pylsp](https://github.com/python-lsp/python-lsp-server)
- rust: [rls](https://github.com/rust-lang/rls)
- lua: [lua-lsp](https://github.com/Alloyed/lua-lsp)
- zig: [zls](https://github.com/zigtools/zls)
## Known issues
Not all possible types of modification events to the file are currently being
sent to the language server. Saving the file will re-synchronize it, though.

View File

@ -0,0 +1,315 @@
# Micro Plugin LSP Client
LSP is a Language Server Protocol client. Features include function signatures
and jump to definition.
This help page can be viewed in Micro editor with Ctrl-E 'help lsp'
## Features and Shortcuts
- Show function signature on status bar (alt-K) (textDocument/hover)
- Open function definition in a new tab (alt-D) (textDocument/definition)
- Format document (alt-F) (textDocument/formatting)
- Show references to the current symbol in a buffer (alt-R)
(textDocument/references), pressing return on the reference line, the
reference's location is opened in a new tab
There is initial support for completion (ctrl-space) (textDocument/completion).
## Supported languages
Installation instructions for Go and Python are provided below. LSP Plugin has
been briefly tested with
- C++: [clangd](https://clangd.llvm.org) /
[ccls](https://github.com/MaskRay/ccls)
- go: [gopls](https://pkg.go.dev/golang.org/x/tools/gopls#section-readme)
- markdown, JSON, typescript, javascript (including JSX/TSX):
[deno](https://deno.land/)
- python: pyls and [pylsp](https://github.com/python-lsp/python-lsp-server)
- rust: [rls](https://github.com/rust-lang/rls)
- lua: [lua-lsp](https://github.com/Alloyed/lua-lsp)
## Install LSP plugin
$ micro --plugin install lsp
To configure the LSP Plugin, you can add two lines to settings.json
$ micro settings.json
Add lines
```json
{
"lsp.server": "python=pylsp,go=gopls,typescript=deno lsp={\"importMap\": \"./import_map.json\"}",
"lsp.formatOnSave": true
}
```
Remember to add comma to previous line. Depending on the language server,
automatic code formating can be quite opinionated. In that case, you can simply
set lsp.formatOnSave to false.
For Python language server, the currently maintained fork is 'pylsp'. If you
wish to use the Palantir version (last updated in 2020) instead, set
"python=pyls" in lsp.server.
If your lsp.server settings are autoremoved, you can
$ export MICRO_LSP='python=pylsp,go=gopls,typescript=deno lsp={"importMap":"import_map.json"},rust=rls'
The lsp.server default settings (if no others are defined) are:
```
python=pylsp,go=gopls,typescript=deno lsp,javascript=deno lsp,markdown=deno lsp,json=deno lsp,jsonc=deno lsp,rust=rls,lua=lua-lsp,c++=clangd
```
## Install Language Server
To support each language, LSP plugin uses language servers. To use LSP plugin,
you must install at least one language server.
If you want to quickly test LSP plugin, Go language server gopls is simple to
install.
### gopls, Go language server
You will need command 'gopls'
$ gopls version
golang.org/x/tools/gopls v0.7.3
In Debian, this is installed with
$ sudo apt-get update
$ sudo apt-get -y install golang-go gopls
To test it, write a short go program
$ micro hello.go
```go
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
```
Move cursor over Println and press alt-k. The function signature is shown on the
bottom of the screen, in Micro status bar. It shows you what parameters the
function can take. The signature should look similar to this: "func
fmt.Println(a ...interface{}) (n int, err error)Println formats using the
default formats..."
Can you see the function signature with alt-k? If you can, you have succesfully
installed Micro LSP plugin and GoPLS language server.
Keep your cursor over Println, and press alt-d. The file defining Println opens.
In this case, it's fmt/print.go. As Go reference documentation is in code
comments, this is very convenient. You can navigate between tabs with atl-,
(alt-comma) and alt-. (alt - full stop). To close the tab, press Ctrl-Q.
### Markdown, JSON/JSONC, Typescript, Javascript
The Deno LSP server will provide full support for Typescript and Javascript.
Additionally, it supports formatting for Markdown and JSON files. The
installation of this is fairly straight forward:
On Mac/Linux:
$ curl -fsSL https://deno.land/install.sh | sh
On Powershell:
$ iwr https://deno.land/install.ps1 -useb | iex
### typescript-language-server
This LSP server will allow for Javascript as well as Typescript support. For
using it, you first need to install it using NPM:
$ npm install -g typescript-language-server typescript
Once it has been installed, you can use it like so:
$ micro hello.js
Press ctrl-e and type in:
set lsp.server "typescript=typescript-language-server --stdio,javascript=typescript-language-server --stdio"
After you restarted micro, you can use the features for typescript and
javascript accordingly.
### pylsp, Python language server
Installing Python language server PyLSP is a bit more involved.
You will need 'virtualenv' command to create virtual environments and 'pip' to
install Python packages. You can also use one of the many other commands for
keeping your 'pip' packages in order.
In Debian, these are installed with
$ sudo apt-get update
$ sudo apt-get install python-pip virtualenv
Create a new virtual environment
$ mkdir somePythonProject; cd somePythonProject
$ virtualenv -p python3 env/
$ source env/bin/activate
Your prompt likely shows "(env)" to confirm you're inside your virtual
environment.
List the packages you want installed.
$ micro requirements.txt
This list is to provide the most useful suggestions. If you would like to get a
lot more opinionated advice, such as adding two empty lines between functions,
you could use "python-lsp-server[all]". The mypy package provides optional
static type checking. requirements.txt:
```
python-lsp-server[rope,pyflakes,mccabe,pylsp-mypy]
pylsp-mypy
```
And actually install
$ pip install -r requirements.txt
No you can test your Python environment
$ micro hello.py
```python
def helloWorld():
return a
```
Save with Ctrl-S. A red warning sign ">>" lists up in the gutter, on the left
side of Micro. Move cursor to the line "return a". The status bar shows the
warning: "undefined name 'a'". Well done, you have now installed Python LSP
support for Micro.
MyPy provides optional static type setting. You can write normally, and type
checking is ignored. You can define types for some functions, and you get
automatic warnings for incorrect use of types. This is how types are marked:
```python
def square(x: int) -> int:
return x*x
```
Depending on your project, taste and installed linters, pylsp sometimes shows
warnings you would like to hide. Hiding messages is possible using
lsp.ignoreMessages, explained in later in this help document.
### lua-lsp, Lua language server
These are the initial installation instructions. This installation will support
linter messages in the gutter (on the left of editing area) and jump to
definition inside the same file (alt-D). All LSP features are not yet supported
with Lua.
Install 'luarocks' command using your package manager. For example, on Debian
$ sudo apt-get update
$ sudo apt-get -y install luarocks
Use luarocks to install helper packages used by lua-lsp
$ sudo luarocks install luacheck
$ sudo luarocks install Formatter
$ sudo luarocks install lcf
Install lua-lsp, the Lua language server
$ sudo luarocks install --server=ssh://luarocks.org/dev lua-lsp
This command uses different URL from official lua-lsp instructions due to
[a change in how packages are downloaded](https://github.com/Alloyed/lua-lsp/issues/45).
This command uses ssh instead of http.
To test it, open a Lua file
$ micro $HOME/.config/micro/plug/lsp/main.lua
Can you see some linter warnings ">>" in the gutter? Can you jump to functions
inside the same file with Alt-D? Well done, you've installed Lua LSP support for
micro.
All features don't work yet with Lua LSP.
### zls, ZIG language server
The ZIG language server provides formatting, goto definition, auto-completion as
well as hover and references. It can be installed by following
[these instruction](https://github.com/zigtools/zls).
Once installed, open micro, press ctrl+e and type the following command:
set lsp.server zig=zls
Close micro again and open a zig file.
## Ignoring unhelpful messages
In addition to providing assistance while coding, some language servers can show
spurious, unnecessary or too oppinionated messages. Sometimes, it's not obvious
how these messages are disable using language server settings.
This plugin allows you to selectively ignore unwanted warnings while keeping
others. This is done my matching the start of the message. By default, nothing
is ignored.
Consider a case where you're working with an external Python project that
indents with tabs. When joining an existing project, you might not want to
impose your own conventions to every code file. On the other hand, LSP support
is not useful if nearly every line is marked with a warning.
Moving the cursor to a line with the warning, you see that the line starts with
"W191 indentation contains tabs". This, and similar unhelpful messages (in the
context of your current project) can be ignored by editing
~/.config/micro/settings.json
```json
{
"lsp.ignoreMessages": "Skipping analyzing |W191 indentation contains tabs|E101 indentation contains mixed spaces and tabs|See https://mypy.readthedocs.io/en"
}
```
As you now open the same file, you can see that warning "W191 indentation
contains tabs" is no longer shown. Also the warning mark ">>" in the gutter is
gone. Try referring to a variable that does not exist, and you can see a helpful
warning appear. You have now disabled the warnings you don't need, while keeping
the useful ones.
## See also
[Official repostory](https://github.com/AndCake/micro-plugin-lsp)
[Usage examples with screenshots](https://terokarvinen.com/2022/micro-editor-lsp-support-python-and-go-jump-to-definition-show-function-signature/)
[Language Server Protocol](https://microsoft.github.io/language-server-protocol/)
[gopls - the Go language server](https://pkg.go.dev/golang.org/x/tools/gopls)
[pylsp - Python LSP Server](https://github.com/python-lsp/python-lsp-server)
[mypy - Optional Static Typing for Python](http://mypy-lang.org/)
[rls - Rust Language Server](https://github.com/rust-lang/rls)
[deno](https://deno.land/)
[typescript-language-server](https://www.npmjs.com/package/typescript-language-server)
[lua-lsp - A Lua language server](https://github.com/Alloyed/lua-lsp)

View File

@ -0,0 +1,923 @@
VERSION = "0.6.1"
local micro = import("micro")
local config = import("micro/config")
local shell = import("micro/shell")
local util = import("micro/util")
local buffer = import("micro/buffer")
local fmt = import("fmt")
local go_os = import("os")
local path = import("path")
local filepath = import("path/filepath")
local cmd = {}
local id = {}
local version = {}
local currentAction = {}
local capabilities = {}
local filetype = ''
local rootUri = ''
local message = ''
local completionCursor = 0
local lastCompletion = {}
local splitBP = nil
local tabCount = 0
local json = {}
function toBytes(str)
local result = {}
for i=1,#str do
local b = str:byte(i)
if b < 32 then
table.insert(result, b)
end
end
return result
end
function getUriFromBuf(buf)
if buf == nil then return; end
local file = buf.AbsPath
local uri = fmt.Sprintf("file://%s", file)
return uri
end
function mysplit (inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
function parseOptions(inputstr)
local t = {}
inputstr = inputstr:gsub("[%w+_-]+=[^=,]+={.-}", function (str)
table.insert(t, str)
return '';
end)
inputstr = inputstr:gsub("[%w+_-]+=[^=,]+", function (str)
table.insert(t, str)
return '';
end)
return t
end
function startServer(filetype, callback)
local wd, _ = go_os.Getwd()
rootUri = fmt.Sprintf("file://%s", wd)
local envSettings, _ = go_os.Getenv("MICRO_LSP")
local settings = config.GetGlobalOption("lsp.server")
local fallback = "python=pylsp,go=gopls,typescript=deno lsp,javascript=deno lsp,markdown=deno lsp,json=deno lsp,jsonc=deno lsp,rust=rls,lua=lua-lsp,c++=clangd"
if envSettings ~= nil and #envSettings > 0 then
settings = envSettings
end
if settings ~= nil and #settings > 0 then
settings = settings .. "," .. fallback
else
settings = fallback
end
local server = parseOptions(settings)
micro.Log("Server Options", server)
for i in pairs(server) do
local part = mysplit(server[i], "=")
local run = mysplit(part[2], "%s")
local initOptions = part[3] or '{}'
local runCmd = table.remove(run, 1)
local args = run
if filetype == part[1] then
local send = withSend(part[1])
if cmd[part[1]] ~= nil then return; end
id[part[1]] = 0
micro.Log("Starting server", part[1])
cmd[part[1]] = shell.JobSpawn(runCmd, args, onStdout(part[1]), onStderr, onExit(part[1]), {})
currentAction[part[1]] = { method = "initialize", response = function (bp, data)
send("initialized", "{}", true)
capabilities[filetype] = data.result and data.result.capabilities or {}
callback(bp.Buf, filetype)
end }
send(currentAction[part[1]].method, fmt.Sprintf('{"processId": %.0f, "rootUri": "%s", "workspaceFolders": [{"name": "root", "uri": "%s"}], "initializationOptions": %s, "capabilities": {"textDocument": {"hover": {"contentFormat": ["plaintext", "markdown"]}, "publishDiagnostics": {"relatedInformation": false, "versionSupport": false, "codeDescriptionSupport": true, "dataSupport": true}, "signatureHelp": {"signatureInformation": {"documentationFormat": ["plaintext", "markdown"]}}}}}', go_os.Getpid(), rootUri, rootUri, initOptions))
return
end
end
end
function init()
config.RegisterCommonOption("lsp", "server", "python=pylsp,go=gopls,typescript=deno lsp,javascript=deno lsp,markdown=deno lsp,json=deno lsp,jsonc=deno lsp,rust=rls,lua=lua-lsp,c++=clangd")
config.RegisterCommonOption("lsp", "formatOnSave", true)
config.RegisterCommonOption("lsp", "autocompleteDetails", false)
config.RegisterCommonOption("lsp", "ignoreMessages", "")
config.RegisterCommonOption("lsp", "tabcompletion", true)
config.RegisterCommonOption("lsp", "ignoreTriggerCharacters", "completion")
-- example to ignore all LSP server message starting with these strings:
-- "lsp.ignoreMessages": "Skipping analyzing |See https://"
config.MakeCommand("hover", hoverAction, config.NoComplete)
config.MakeCommand("definition", definitionAction, config.NoComplete)
config.MakeCommand("lspcompletion", completionAction, config.NoComplete)
config.MakeCommand("format", formatAction, config.NoComplete)
config.MakeCommand("references", referencesAction, config.NoComplete)
config.TryBindKey("Alt-k", "command:hover", false)
config.TryBindKey("Alt-d", "command:definition", false)
config.TryBindKey("Alt-f", "command:format", false)
config.TryBindKey("Alt-r", "command:references", false)
config.TryBindKey("CtrlSpace", "command:lspcompletion", false)
config.AddRuntimeFile("lsp", config.RTHelp, "help/lsp.md")
-- @TODO register additional actions here
end
function withSend(filetype)
return function (method, params, isNotification)
if cmd[filetype] == nil then
return
end
local msg = fmt.Sprintf('{"jsonrpc": "2.0", %s"method": "%s", "params": %s}', not isNotification and fmt.Sprintf('"id": %.0f, ', id[filetype]) or "", method, params)
id[filetype] = id[filetype] + 1
msg = fmt.Sprintf("Content-Length: %.0f\r\n\r\n%s", #msg, msg)
--micro.Log("send", filetype, "sending", method or msg, msg)
shell.JobSend(cmd[filetype], msg)
end
end
function preRune(bp, r)
if splitBP ~= nil then
pcall(function () splitBP:Unsplit(); end)
splitBP = nil
local cur = bp.Buf:GetActiveCursor()
cur:Deselect(false);
cur:GotoLoc(buffer.Loc(cur.X + 1, cur.Y))
end
end
-- when a new character is types, the document changes
function onRune(bp, r)
local filetype = bp.Buf:FileType()
if cmd[filetype] == nil then
return
end
if splitBP ~= nil then
pcall(function () splitBP:Unsplit(); end)
splitBP = nil
end
local send = withSend(filetype)
local uri = getUriFromBuf(bp.Buf)
if r ~= nil then
lastCompletion = {}
end
-- allow the document contents to be escaped properly for the JSON string
local content = util.String(bp.Buf:Bytes()):gsub("\\", "\\\\"):gsub("\n", "\\n"):gsub("\r", "\\r"):gsub('"', '\\"'):gsub("\t", "\\t")
-- increase change version
version[uri] = (version[uri] or 0) + 1
send("textDocument/didChange", fmt.Sprintf('{"textDocument": {"version": %.0f, "uri": "%s"}, "contentChanges": [{"text": "%s"}]}', version[uri], uri, content), true)
local ignored = mysplit(config.GetGlobalOption("lsp.ignoreTriggerCharacters") or '', ",")
if r and capabilities[filetype] then
if not contains(ignored, "completion") and capabilities[filetype].completionProvider and capabilities[filetype].completionProvider.triggerCharacters and contains(capabilities[filetype].completionProvider.triggerCharacters, r) then
completionAction(bp)
elseif not contains(ignored, "signature") and capabilities[filetype].signatureHelpProvider and capabilities[filetype].signatureHelpProvider.triggerCharacters and contains(capabilities[filetype].signatureHelpProvider.triggerCharacters, r) then
hoverAction(bp)
end
end
end
-- alias functions for any kind of change to the document
-- @TODO: add missing ones
function onBackspace(bp) onRune(bp); end
function onCut(bp) onRune(bp); end
function onCutLine(bp) onRune(bp); end
function onDuplicateLine(bp) onRune(bp); end
function onDeleteLine(bp) onRune(bp); end
function onDelete(bp) onRune(bp); end
function onUndo(bp) onRune(bp); end
function onRedo(bp) onRune(bp); end
function onIndent(bp) onRune(bp); end
function onIndentSelection(bp) onRune(bp); end
function onPaste(bp) onRune(bp); end
function onSave(bp) onRune(bp); end
function onEscape(bp)
if splitBP ~= nil then
pcall(function () splitBP:Unsplit(); end)
splitBP = nil
end
end
function preInsertNewline(bp)
if bp.Buf.Path == "References found" then
local cur = bp.Buf:GetActiveCursor()
cur:SelectLine()
local data = util.String(cur:GetSelection())
local file, line, character = data:match("(./[^:]+):([^:]+):([^:]+)")
local doc, _ = file:gsub("^file://", "")
buf, _ = buffer.NewBufferFromFile(doc)
bp:AddTab()
micro.CurPane():OpenBuffer(buf)
buf:GetActiveCursor():GotoLoc(buffer.Loc(character * 1, line * 1))
micro.CurPane():Center()
return false
end
end
function preSave(bp)
if config.GetGlobalOption("lsp.formatOnSave") then
onRune(bp)
formatAction(bp, function ()
bp:Save()
end)
end
end
function handleInitialized(buf, filetype)
if cmd[filetype] == nil then return; end
micro.Log("Found running lsp server for ", filetype, "firing textDocument/didOpen...")
local send = withSend(filetype)
local uri = getUriFromBuf(buf)
local content = util.String(buf:Bytes()):gsub("\\", "\\\\"):gsub("\n", "\\n"):gsub("\r", "\\r"):gsub('"', '\\"'):gsub("\t", "\\t")
send("textDocument/didOpen", fmt.Sprintf('{"textDocument": {"uri": "%s", "languageId": "%s", "version": 1, "text": "%s"}}', uri, filetype, content), true)
end
function onBufferOpen(buf)
local filetype = buf:FileType()
micro.Log("ONBUFFEROPEN", filetype)
if filetype ~= "unknown" and rootUri == "" and not cmd[filetype] then return startServer(filetype, handleInitialized); end
if cmd[filetype] then
handleInitialized(buf, filetype)
end
end
function contains(list, x)
for _, v in pairs(list) do
if v == x then return true; end
end
return false
end
function string.starts(String, Start)
return string.sub(String, 1, #Start) == Start
end
function string.ends(String, End)
return string.sub(String, #String - (#End - 1), #String) == End
end
function string.random(CharSet, Length, prefix)
local _CharSet = CharSet or '.'
if _CharSet == '' then
return ''
else
local Result = prefix or ""
math.randomseed(os.time())
for Loop = 1,Length do
local char = math.random(1, #CharSet)
Result = Result .. CharSet:sub(char,char)
end
return Result
end
end
function string.parse(text)
if not text:find('"jsonrpc":') then return {}; end
local start,fin = text:find("\n%s*\n")
local cleanedText = text
if fin ~= nil then
cleanedText = text:sub(fin)
end
local status, res = pcall(json.parse, cleanedText)
if status then
return res
end
return false
end
function isIgnoredMessage(msg)
-- Return true if msg matches one of the ignored starts of messages
-- Useful for linters that show spurious, hard to disable warnings
local ignoreList = mysplit(config.GetGlobalOption("lsp.ignoreMessages"), "|")
for i, ignore in pairs(ignoreList) do
if string.match(msg, ignore) then -- match from start of string
micro.Log("Ignore message: '", msg, "', because it matched: '", ignore, "'.")
return true -- ignore this message, dont show to user
end
end
return false -- show this message to user
end
function onStdout(filetype)
return function (text)
if text:starts("Content-Length:") then
message = text
else
message = message .. text
end
if not text:ends("}") then
return
end
local data = message:parse()
if data == false then
return
end
if data.method == "workspace/configuration" then
-- actually needs to respond with the same ID as the received JSON
local message = fmt.Sprintf('{"jsonrpc": "2.0", "id": %.0f, "result": [{"enable": true}]}', data.id)
shell.JobSend(cmd[filetype], fmt.Sprintf('Content-Length: %.0f\n\n%s', #message, message))
elseif data.method == "textDocument/publishDiagnostics" or data.method == "textDocument\\/publishDiagnostics" then
-- react to server-published event
local bp = micro.CurPane().Buf
bp:ClearMessages("lsp")
bp:AddMessage(buffer.NewMessage("lsp", "", buffer.Loc(0, 10000000), buffer.Loc(0, 10000000), buffer.MTInfo))
local uri = getUriFromBuf(bp)
if data.params.uri == uri then
for _, diagnostic in ipairs(data.params.diagnostics) do
local type = buffer.MTInfo
if diagnostic.severity == 1 then
type = buffer.MTError
elseif diagnostic.severity == 2 then
type = buffer.MTWarning
end
local mstart = buffer.Loc(diagnostic.range.start.character, diagnostic.range.start.line)
local mend = buffer.Loc(diagnostic.range["end"].character, diagnostic.range["end"].line)
if not isIgnoredMessage(diagnostic.message) then
msg = buffer.NewMessage("lsp", diagnostic.message, mstart, mend, type)
bp:AddMessage(msg)
end
end
end
elseif currentAction[filetype] and currentAction[filetype].method and not data.method and currentAction[filetype].response and data.jsonrpc then -- react to custom action event
local bp = micro.CurPane()
micro.Log("Received message for ", filetype, data)
currentAction[filetype].response(bp, data)
currentAction[filetype] = {}
elseif data.method == "window/showMessage" or data.method == "window\\/showMessage" then
if filetype == micro.CurPane().Buf:FileType() then
micro.InfoBar():Message(data.params.message)
else
micro.Log(filetype .. " message " .. data.params.message)
end
elseif data.method == "window/logMessage" or data.method == "window\\/logMessage" then
micro.Log(data.params.message)
elseif message:starts("Content-Length:") then
if message:find('"') and not message:find('"result":null') then
micro.Log("Unhandled message 1", filetype, message)
end
else
-- enable for debugging purposes
micro.Log("Unhandled message 2", filetype, message)
end
end
end
function onStderr(text)
micro.Log("ONSTDERR", text)
--micro.InfoBar():Message(text)
end
function onExit(filetype)
return function (str)
currentAction[filetype] = nil
cmd[filetype] = nil
micro.Log("ONEXIT", filetype, str)
end
end
-- the actual hover action request and response
-- the hoverActionResponse is hooked up in
function hoverAction(bp)
local filetype = bp.Buf:FileType()
if cmd[filetype] ~= nil then
local send = withSend(filetype)
local file = bp.Buf.AbsPath
local line = bp.Buf:GetActiveCursor().Y
local char = bp.Buf:GetActiveCursor().X
currentAction[filetype] = { method = "textDocument/hover", response = hoverActionResponse }
send(currentAction[filetype].method, fmt.Sprintf('{"textDocument": {"uri": "file://%s"}, "position": {"line": %.0f, "character": %.0f}}', file, line, char))
end
end
function hoverActionResponse(buf, data)
if data.result and data.result.contents ~= nil and data.result.contents ~= "" then
if data.result.contents.value then
micro.InfoBar():Message(data.result.contents.value)
elseif #data.result.contents > 0 then
micro.InfoBar():Message(data.result.contents[1].value)
end
end
end
-- the definition action request and response
function definitionAction(bp)
local filetype = bp.Buf:FileType()
if cmd[filetype] == nil then return; end
local send = withSend(filetype)
local file = bp.Buf.AbsPath
local line = bp.Buf:GetActiveCursor().Y
local char = bp.Buf:GetActiveCursor().X
currentAction[filetype] = { method = "textDocument/definition", response = definitionActionResponse }
send(currentAction[filetype].method, fmt.Sprintf('{"textDocument": {"uri": "file://%s"}, "position": {"line": %.0f, "character": %.0f}}', file, line, char))
end
function definitionActionResponse(bp, data)
local results = data.result or data.partialResult
if results == nil then return; end
local file = bp.Buf.AbsPath
if results.uri ~= nil then
-- single result
results = { results }
end
if #results <= 0 then return; end
local uri = (results[1].uri or results[1].targetUri)
local doc = uri:gsub("^file://", "")
local buf = bp.Buf
if file ~= doc then
-- it's from a different file, so open it as a new tab
buf, _ = buffer.NewBufferFromFile("." .. uri:sub(#rootUri + 1, #uri))
bp:AddTab()
micro.CurPane():OpenBuffer(buf)
end
local range = results[1].range or results[1].targetSelectionRange
buf:GetActiveCursor():GotoLoc(buffer.Loc(range.start.character, range.start.line))
bp:Center()
end
function completionAction(bp)
local filetype = bp.Buf:FileType()
local send = withSend(filetype)
local file = bp.Buf.AbsPath
local line = bp.Buf:GetActiveCursor().Y
local char = bp.Buf:GetActiveCursor().X
if lastCompletion[1] == file and lastCompletion[2] == line and lastCompletion[3] == char then
completionCursor = completionCursor + 1
else
completionCursor = 0
if bp.Cursor:HasSelection() then
-- we have a selection
-- assume we want to indent the selection
bp:IndentSelection()
return
end
if char == 0 then
-- we are at the very first character of a line
-- assume we want to indent
bp:IndentLine()
return
end
local cur = bp.Buf:GetActiveCursor()
cur:SelectLine()
local lineContent = util.String(cur:GetSelection())
cur:ResetSelection()
cur:GotoLoc(buffer.Loc(char, line))
local startOfLine = "" .. lineContent:sub(1, char)
if startOfLine:match("^%s+$") then
-- we are at the beginning of a line
-- assume we want to indent the line
bp:IndentLine()
return
end
end
if cmd[filetype] == nil then return; end
lastCompletion = {file, line, char}
currentAction[filetype] = { method = "textDocument/completion", response = completionActionResponse }
send(currentAction[filetype].method, fmt.Sprintf('{"textDocument": {"uri": "file://%s"}, "position": {"line": %.0f, "character": %.0f}}', file, line, char))
end
table.filter = function(t, filterIter)
local out = {}
for k, v in pairs(t) do
if filterIter(v, k, t) then table.insert(out, v) end
end
return out
end
function findCommon(input, list)
local commonLen = 0
local prefixList = {}
local str = input.textEdit and input.textEdit.newText or input.label
for i = 1,#str,1 do
local prefix = str:sub(1, i)
prefixList[prefix] = 0
for idx, entry in ipairs(list) do
local currentEntry = entry.textEdit and entry.textEdit.newText or entry.label
if currentEntry:starts(prefix) then
prefixList[prefix] = prefixList[prefix] + 1
end
end
end
local longest = ""
for idx, entry in pairs(prefixList) do
if entry >= #list then
if #longest < #idx then
longest = idx
end
end
end
if #list == 1 then
return list[1].textEdit and list[1].textEdit.newText or list[1].label
end
return longest
end
function completionActionResponse(bp, data)
local results = data.result
if results == nil then
return
end
if results.items then
results = results.items
end
local xy = buffer.Loc(bp.Cursor.X, bp.Cursor.Y)
local start = xy
if bp.Cursor:HasSelection() then
bp.Cursor:DeleteSelection()
end
local found = false
local prefix = ""
local reversed = ""
-- if we have no defined ranges in the result
-- try to find out what our prefix is we want to filter against
if not results[1] or not results[1].textEdit or not results[1].textEdit.range then
if capabilities[bp.Buf:FileType()] and capabilities[bp.Buf:FileType()].completionProvider and capabilities[bp.Buf:FileType()].completionProvider.triggerCharacters then
local cur = bp.Buf:GetActiveCursor()
cur:SelectLine()
local lineContent = util.String(cur:GetSelection())
reversed = string.reverse(lineContent:gsub("\r?\n$", ""):sub(1, xy.X))
local triggerChars = capabilities[bp.Buf:FileType()].completionProvider.triggerCharacters
for i = 1,#reversed,1 do
local char = reversed:sub(i,i)
-- try to find a trigger character or any other non-word character
if contains(triggerChars, char) or contains({" ", ":", "/", "-", "\t", ";"}, char) then
found = true
start = buffer.Loc(#reversed - (i - 1), bp.Cursor.Y)
bp.Cursor:SetSelectionStart(start)
bp.Cursor:SetSelectionEnd(xy)
prefix = util.String(cur:GetSelection())
bp.Cursor:DeleteSelection()
bp.Cursor:ResetSelection()
break
end
end
if not found then
prefix = lineContent:gsub("\r?\n$", '')
end
end
-- if we have found a prefix
if prefix ~= "" then
-- filter it down to what is suggested by the prefix
results = table.filter(results, function (entry)
return entry.label:starts(prefix)
end)
end
end
table.sort(results, function (left, right)
return (left.sortText or left.label) < (right.sortText or right.label)
end)
entry = results[(completionCursor % #results) + 1]
-- if no matching results are found
if entry == nil then
-- reposition cursor and stop
bp.Cursor:GotoLoc(xy)
return
end
local commonStart = ''
local toInsert = entry.textEdit and entry.textEdit.newText or entry.label
local isTabCompletion = config.GetGlobalOption("lsp.tabcompletion")
if isTabCompletion and not entry.textEdit then
commonStart = findCommon(entry, results)
bp.Buf:Insert(start, commonStart)
if prefix ~= commonStart then
return
end
start = buffer.Loc(start.X + #prefix, start.Y)
else
prefix = ''
end
if entry.textEdit and entry.textEdit.range then
start = buffer.Loc(entry.textEdit.range.start.character, entry.textEdit.range.start.line)
bp.Cursor:SetSelectionStart(start)
bp.Cursor:SetSelectionEnd(xy)
bp.Cursor:DeleteSelection()
bp.Cursor:ResetSelection()
elseif capabilities[bp.Buf:FileType()] and capabilities[bp.Buf:FileType()].completionProvider and capabilities[bp.Buf:FileType()].completionProvider.triggerCharacters then
if not found then
-- we found nothing - so assume we need the beginning of the line
if reversed:starts(" ") or reversed:starts("\t") then
-- if we end with some indentation, keep it
start = buffer.Loc(#reversed, bp.Cursor.Y)
else
start = buffer.Loc(0, bp.Cursor.Y)
end
bp.Cursor:SetSelectionStart(start)
bp.Cursor:SetSelectionEnd(xy)
bp.Cursor:DeleteSelection()
bp.Cursor:ResetSelection()
end
end
local inserting = "" .. toInsert:gsub(prefix, "")
bp.Buf:Insert(start, inserting)
if #results > 1 then
if entry.textEdit then
bp.Cursor:GotoLoc(start)
bp.Cursor:SetSelectionStart(start)
else
-- if we had to calculate everything outselves
-- go back to the original location
bp.Cursor:GotoLoc(xy)
bp.Cursor:SetSelectionStart(xy)
end
bp.Cursor:SetSelectionEnd(buffer.Loc(start.X + #toInsert, start.Y))
else
bp.Cursor:GotoLoc(buffer.Loc(start.X + #inserting, start.Y))
end
local startLoc = buffer.Loc(0, 0)
local endLoc = buffer.Loc(0, 0)
local msg = ''
local insertion = ''
if entry.detail or entry.documentation then
insertion = fmt.Sprintf("%s", entry.detail or entry.documentation or '')
for idx, result in ipairs(results) do
if #msg > 0 then
msg = msg .. "\n"
end
local insertion = fmt.Sprintf("%s %s", result.detail or '', result.documentation or '')
if idx == (completionCursor % #results) + 1 then
local msglines = mysplit(msg, "\n")
startLoc = buffer.Loc(0, #msglines)
endLoc = buffer.Loc(#insertion - 1, #msglines)
end
msg = msg .. insertion
end
else
insertion = entry.label
for idx, result in ipairs(results) do
if #msg > 0 then
local msglines = mysplit(msg, "\n")
local lastLine = msglines[#msglines]
local len = #result.label + 4
if #lastLine + len >= bp:GetView().Width then
msg = msg .. "\n "
else
msg = msg .. ' '
end
else
msg = " "
end
if idx == (completionCursor % #results) + 1 then
local msglines = mysplit(msg, "\n")
local prefixLen = 0
if #msglines > 0 then
prefixLen = #msglines[#msglines]
else
prefixLen = #msg
end
startLoc = buffer.Loc(prefixLen or 0, #msglines - 1)
endLoc = buffer.Loc(prefixLen + #result.label, #msglines - 1)
end
msg = msg .. result.label
end
end
if config.GetGlobalOption("lsp.autocompleteDetails") then
if not splitBP then
local tmpName = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):random(32)
local logBuf = buffer.NewBuffer(msg, tmpName)
splitBP = bp:HSplitBuf(logBuf)
bp:NextSplit()
else
splitBP:SelectAll()
splitBP.Cursor:DeleteSelection()
splitBP.Cursor:ResetSelection()
splitBP.Buf:insert(buffer.Loc(1, 1), msg)
end
splitBP.Cursor:ResetSelection()
splitBP.Cursor:SetSelectionStart(startLoc)
splitBP.Cursor:SetSelectionEnd(endLoc)
else
if entry.detail or entry.documentation then
micro.InfoBar():Message(insertion)
else
local cleaned = " " .. msg:gsub("%s+", " ")
local replaced, _ = cleaned:gsub(".*%s" .. insertion .. "%s?", " [" .. insertion .. "] ")
micro.InfoBar():Message(replaced)
end
end
end
function formatAction(bp, callback)
local filetype = bp.Buf:FileType()
if cmd[filetype] == nil then return; end
local send = withSend(filetype)
local file = bp.Buf.AbsPath
currentAction[filetype] = { method = "textDocument/formatting", response = formatActionResponse(callback) }
send(currentAction[filetype].method, fmt.Sprintf('{"textDocument": {"uri": "file://%s"}, "options": {"tabSize": 4, "insertSpaces": true}}', file))
end
function formatActionResponse(callback)
return function (bp, data)
if data.result == nil then return; end
local edits = data.result
-- make sure we apply the changes from back to front
-- this allows for changes to not need position updates
table.sort(edits, function (left, right)
-- go by lines first
return left.range['end'].line > right.range['end'].line or
-- if lines match, go by end character
left.range['end'].line == right.range['end'].line and left.range['end'].character > right.range['end'].character or
-- if they match too, go by start character
left.range['end'].line == right.range['end'].line and left.range['end'].character == right.range['end'].character and left.range.start.line == left.range['end'].line and left.range.start.character > right.range.start.character
end)
-- save original cursor position
local xy = buffer.Loc(bp.Cursor.X, bp.Cursor.Y)
for _idx, edit in ipairs(edits) do
rangeStart = buffer.Loc(edit.range.start.character, edit.range.start.line)
rangeEnd = buffer.Loc(edit.range['end'].character, edit.range['end'].line)
-- apply each change
bp.Cursor:GotoLoc(rangeStart)
bp.Cursor:SetSelectionStart(rangeStart)
bp.Cursor:SetSelectionEnd(rangeEnd)
bp.Cursor:DeleteSelection()
bp.Cursor:ResetSelection()
if edit.newText ~= "" then
bp.Buf:insert(rangeStart, edit.newText)
end
end
-- put the cursor back where it was
bp.Cursor:GotoLoc(xy)
-- if any changes were applied
if #edits > 0 then
-- tell the server about the changed document
onRune(bp)
end
if callback ~= nil then
callback(bp)
end
end
end
-- the references action request and response
function referencesAction(bp)
local filetype = bp.Buf:FileType()
if cmd[filetype] == nil then return; end
local send = withSend(filetype)
local file = bp.Buf.AbsPath
local line = bp.Buf:GetActiveCursor().Y
local char = bp.Buf:GetActiveCursor().X
currentAction[filetype] = { method = "textDocument/references", response = referencesActionResponse }
send(currentAction[filetype].method, fmt.Sprintf('{"textDocument": {"uri": "file://%s"}, "position": {"line": %.0f, "character": %.0f}, "context": {"includeDeclaration":true}}', file, line, char))
end
function referencesActionResponse(bp, data)
if data.result == nil then return; end
local results = data.result or data.partialResult
if results == nil or #results <= 0 then return; end
local file = bp.Buf.AbsPath
local msg = ''
for _idx, ref in ipairs(results) do
if msg ~= '' then msg = msg .. '\n'; end
local doc = (ref.uri or ref.targetUri)
msg = msg .. "." .. doc:sub(#rootUri + 1, #doc) .. ":" .. ref.range.start.line .. ":" .. ref.range.start.character
end
local logBuf = buffer.NewBuffer(msg, "References found")
local splitBP = bp:HSplitBuf(logBuf)
end
--
-- @TODO implement additional functions here...
--
--
-- JSON
--
-- Internal functions.
local function kind_of(obj)
if type(obj) ~= 'table' then return type(obj) end
local i = 1
for _ in pairs(obj) do
if obj[i] ~= nil then i = i + 1 else return 'table' end
end
if i == 1 then return 'table' else return 'array' end
end
local function escape_str(s)
local in_char = {'\\', '"', '/', '\b', '\f', '\n', '\r', '\t'}
local out_char = {'\\', '"', '/', 'b', 'f', 'n', 'r', 't'}
for i, c in ipairs(in_char) do
s = s:gsub(c, '\\' .. out_char[i])
end
return s
end
-- Returns pos, did_find; there are two cases:
-- 1. Delimiter found: pos = pos after leading space + delim; did_find = true.
-- 2. Delimiter not found: pos = pos after leading space; did_find = false.
-- This throws an error if err_if_missing is true and the delim is not found.
local function skip_delim(str, pos, delim, err_if_missing)
pos = pos + #str:match('^%s*', pos)
if str:sub(pos, pos) ~= delim then
if err_if_missing then
error('Expected ' .. delim .. ' near position ' .. pos)
end
return pos, false
end
return pos + 1, true
end
-- Expects the given pos to be the first character after the opening quote.
-- Returns val, pos; the returned pos is after the closing quote character.
local function parse_str_val(str, pos, val)
val = val or ''
local early_end_error = 'End of input found while parsing string.'
if pos > #str then error(early_end_error) end
local c = str:sub(pos, pos)
if c == '"' then return val, pos + 1 end
if c ~= '\\' then return parse_str_val(str, pos + 1, val .. c) end
-- We must have a \ character.
local esc_map = {b = '\b', f = '\f', n = '\n', r = '\r', t = '\t'}
local nextc = str:sub(pos + 1, pos + 1)
if not nextc then error(early_end_error) end
return parse_str_val(str, pos + 2, val .. (esc_map[nextc] or nextc))
end
-- Returns val, pos; the returned pos is after the number's final character.
local function parse_num_val(str, pos)
local num_str = str:match('^-?%d+%.?%d*[eE]?[+-]?%d*', pos)
local val = tonumber(num_str)
if not val then error('Error parsing number at position ' .. pos .. '.') end
return val, pos + #num_str
end
json.null = {} -- This is a one-off table to represent the null value.
function json.parse(str, pos, end_delim)
pos = pos or 1
if pos > #str then error('Reached unexpected end of input.' .. str) end
local pos = pos + #str:match('^%s*', pos) -- Skip whitespace.
local first = str:sub(pos, pos)
if first == '{' then -- Parse an object.
local obj, key, delim_found = {}, true, true
pos = pos + 1
while true do
key, pos = json.parse(str, pos, '}')
if key == nil then return obj, pos end
if not delim_found then error('Comma missing between object items.') end
pos = skip_delim(str, pos, ':', true) -- true -> error if missing.
obj[key], pos = json.parse(str, pos)
pos, delim_found = skip_delim(str, pos, ',')
end
elseif first == '[' then -- Parse an array.
local arr, val, delim_found = {}, true, true
pos = pos + 1
while true do
val, pos = json.parse(str, pos, ']')
if val == nil then return arr, pos end
if not delim_found then error('Comma missing between array items.') end
arr[#arr + 1] = val
pos, delim_found = skip_delim(str, pos, ',')
end
elseif first == '"' then -- Parse a string.
return parse_str_val(str, pos + 1)
elseif first == '-' or first:match('%d') then -- Parse a number.
return parse_num_val(str, pos)
elseif first == end_delim then -- End of an object or array.
return nil, pos + 1
else -- Parse true, false, or null.
local literals = {['true'] = true, ['false'] = false, ['null'] = json.null}
for lit_str, lit_val in pairs(literals) do
local lit_end = pos + #lit_str - 1
if str:sub(pos, lit_end) == lit_str then return lit_val, lit_end + 1 end
end
local pos_info_str = 'position ' .. pos .. ': ' .. str:sub(pos, pos + 10)
error('Invalid json syntax starting at ' .. pos_info_str .. ': ' .. str)
end
end

View File

@ -0,0 +1,71 @@
[{
"Name": "lsp",
"Description": "Generic LSP Client for Micro",
"Website": "https://github.com/AndCake/micro-plugin-lsp",
"Tags": ["lsp"],
"Versions": [
{
"Version": "0.4.1",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.4.1.zip",
"Require": {
"micro": ">=2.0.10"
}
},
{
"Version": "0.4.2",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.4.2.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.4.3",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.4.3.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.5.0",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.5.0.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.5.1",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.5.1.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.5.2",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.5.2.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.5.3",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.5.3.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.6.0",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.6.0.zip",
"Require": {
"micro": ">=2.0.8"
}
},
{
"Version": "0.6.1",
"Url": "https://github.com/AndCake/micro-plugin-lsp/archive/v0.6.1.zip",
"Require": {
"micro": ">=2.0.8"
}
}
]
}]

View File

@ -0,0 +1,20 @@
Copyright (c) 2016: Florian Sundermann.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,26 @@
This project was originally created by [boombuler](https://github.com/boombuler)
## Introduction
This is a simple snippet plugin for the [Micro](https://github.com/zyedidia/micro) editor.
The plugin comes with some snippet files which are taken from [vim-snippets](https://github.com/honza/vim-snippets)
Have a look at those repositories for their license and additional information!
Other [plugins](https://github.com/micro-editor/plugin-channel) for Micro editor
## Install Snippet Plugin
### From Micro Version 1
'ctrl-e'
'plugin install snippets'
### From Micro Version 2
```bash
cd ~/.config/micro/plug
git clone https://github.com/tommyshem/micro-snippets-plugin.git snippets
```

View File

@ -0,0 +1,82 @@
# About the snippet plugin
This plugin is designed to work with simple VIM snippets like the once from
[here](https://github.com/honza/vim-snippets/tree/master/snippets)
The plugin itself doesn't provide any snippets. To add snippets for a language
place a file containing the snippets at `~/.config/micro/plugins/snippets/[filetype].snippets`
## Commands
The plugin provides the following commands:
| Command | Description of function | Key |
| ------------- | :--------------------------------------------------- | :---: |
| snippetinsert | with an optional parameter to specify which snippet | Alt+S |
| ' | should be inserted. |
| ' | If the parameter is absent, the word right |
| ' | before the cursor will be used for this. |
| snippetnext | proceeds to the next placeholder | Alt+W |
| snippetcancel | removes all the current snippet | Alt+D |
| snippetaccept | finishes the snippet editing for the current snippet | Alt+A |
## Snippet Files
The snippet files have a very simple syntax:
* lines starting with `#` are ignored
* a line starts with `snippet` starts a new snippet.
* after `snippet` you can add one or more shortcuts for the snippets,
like `snippet aFunc bFunc` (at least one shortcut is required)
* every line of code within the snippet must start with a tab (`\t`)
* a snippet can have multiple placeholders which are indicated by `
${num[:name]}` where num is a numeric value. Placeholders with the
same number share the same value. You also have the option to give
a placeholder a name / description / default value.
Plugins can provide snippet files they just need to publish them as a runtime file with type `snippets`.
See the plugins help for additional details.
Sample for go:
```go
# creates a function that prints a value
snippet fmtfunc
func ${0:name}() {
fmt.Println("${0} prints:", ${1:value})
}
```
## Custom Key Bindings
Add a file, if not already created in `~/.config/micro/bindings.json`
Change the default keys you want to use.
Micro editor as a help file here https://github.com/zyedidia/micro/blob/master/runtime/help/keybindings.md
```json
{
"Alt-w": "snippets.Next",
"Alt-a": "snippets.Accept",
"Alt-s": "snippets.Insert",
"Alt-d": "snippets.Cancel"
}
```
## Raw key codes
Micro has a command `raw`
Micro will open a new tab and show the escape sequence for every event it receives from the terminal.
This shows you what micro actually sees from the terminal and helps you see which bindings aren't possible and why.
This is most useful for debugging keybindings.
Example
\x1b turns into \u001 then the same as the raw output.
`"\u001bctrlback": "DeleteWordLeft"`
Micro editor help file https://github.com/zyedidia/micro/blob/master/runtime/help/keybindings.md

View File

@ -0,0 +1,10 @@
{
"name": "snippets",
"description": "Snippets plugin",
"website": "",
"install": "",
"version": "1.0.0",
"require": [
"micro >= 2.0.0"
]
}

View File

@ -0,0 +1,29 @@
[{
"Name": "snippets",
"Description": "plugin to insert language specific code snippets.",
"Website": "https://github.com/tommyshem/micro-snippets-plugin",
"Tags": ["snippet"],
"Versions": [
{
"Version": "0.2.0",
"Url": "https://github.com/tommyshem/micro-snippets-plugin/archive/v0.2.0.zip",
"Require": {
"micro": ">=2.0.0-1"
}
},
{
"Version": "0.1.4",
"Url": "https://github.com/tommyshem/micro-snippets-plugin/archive/v0.1.4.zip",
"Require": {
"micro": ">=1.3.4"
}
},
{
"Version": "0.1.2",
"Url": "https://github.com/tommyshem/micro-snippets-plugin/archive/v0.1.2.zip",
"Require": {
"micro": ">1.0.3 <1.3.4"
}
}
]
}]

View File

@ -0,0 +1,586 @@
VERSION = "0.2.0"
local micro = import("micro")
local buffer = import("micro/buffer")
local config = import("micro/config")
local util = import("micro/util")
local debugflag = true
local curFileType = ""
local snippets = {}
local currentSnippet = nil
local RTSnippets = config.NewRTFiletype()
local Location = {}
Location.__index = Location
local Snippet = {}
Snippet.__index = Snippet
-- Snippets
-- --> Snippet
-- --> Location
function Location.new(idx, ph, snippet)
debug1("Location.new(idx, ph, snip) idx = " , idx)
--debugt("Location.new(idx, ph, snip) ph = ", ph)
--debugt("Location.new(idx, ph, snippet) snippet = ", snippet)
local self = setmetatable({}, Location)
self.idx = idx
self.ph = ph
self.snippet = snippet
return self
end
-- offset of the location relative to the snippet start
function Location.offset(self)
debug("Location.offset(self)")
local add = 0
for i = 1, #self.snippet.locations do
local loc = self.snippet.locations[i]
debug1("loc = ",loc)
if loc == self then
break
end
local val = loc.ph.value
micro.Log("VAL", val)
if val then
add = add + val:len()
end
end
return self.idx+add
end
function Location.startPos(self)
--debugt("Location.startPos(self) = ",self)
local loc = self.snippet.startPos
return loc:Move(self:offset(), self.snippet.view.buf)
end
-- returns the length of the location (but at least 1)
function Location.len(self)
debug("Location.len(self)")
local len = 0
if self.ph.value then
len = self.ph.value:len()
end
if len <= 0 then
len = 1
end
return len
end
function Location.endPos(self)
debug("Location.endPos(self)")
local start = self:startPos()
micro.Log("ENDPOS", self.ph.value)
return start:Move(self:len(), self.snippet.view.buf)
end
-- check if the given loc is within the location
function Location.isWithin(self, loc)
debug("Location.isWithin(self, loc)")
return loc:GreaterEqual(self:startPos()) and loc:LessEqual(self:endPos())
end
function Location.focus(self)
debug("Location.focus(self)")
local view = self.snippet.view
local startP = self:startPos():Move(-1, view.Buf)
local endP = self:endPos():Move(-1, view.Buf)
micro.Log(startP, endP)
if view.Cursor:LessThan(startP) then
while view.Cursor:LessThan(startP) do
view.Cursor:Right()
end
elseif view.Cursor:GreaterEqual(endP) then
while view.Cursor:GreaterEqual(endP) do
view.Cursor:Left()
end
end
if self.ph.value:len() > 0 then
view.Cursor:SetSelectionStart(startP)
view.Cursor:SetSelectionEnd(endP)
else
view.Cursor:ResetSelection()
end
end
function Location.handleInput(self, ev)
debug("Location.handleInput(self, ev)")
if ev.EventType == 1 then
-- TextInput
if util.String(ev.Deltas[1].Text) == "\n" then
Accept()
return false
else
local offset = 1
local sp = self:startPos()
while sp:LessEqual(-ev.Deltas[1].Start) do
sp = sp:Move(1, self.snippet.view.Buf)
offset = offset + 1
end
self.snippet:remove()
local v = self.ph.value
if v == nil then
v = ""
end
self.ph.value = v:sub(0, offset-1) .. util.String(ev.Deltas[1].Text) .. v:sub(offset)
self.snippet:insert()
return true
end
elseif ev.EventType == -1 then
-- TextRemove
local offset = 1
local sp = self:startPos()
while sp:LessEqual(-ev.Deltas[1].Start) do
sp = sp:Move(1, self.snippet.view.Buf)
offset = offset + 1
end
if ev.Deltas[1].Start.Y ~= ev.Deltas[1].End.Y then
return false
end
self.snippet:remove()
local v = self.ph.value
if v == nil then
v = ""
end
local len = ev.Deltas[1].End.X - ev.Deltas[1].Start.X
self.ph.value = v:sub(0, offset-1) .. v:sub(offset+len)
self.snippet:insert()
return true
end
return false
end
-- new snippet
function Snippet.new()
debug("Snippet.new()")
local self = setmetatable({}, Snippet)
self.code = ""
return self
end
-- add line of code to snippet
function Snippet.AddCodeLine(self, line)
--debugt("Snippet.AddCodeLine(self,line) self = " , self)
debug1("Snippet.AddCodeLine(self, line) line = " , line)
if self.code ~= "" then
self.code = self.code .. "\n"
end
self.code = self.code .. line
end
function Snippet.Prepare(self)
debug("Snippet.Prepare(self)")
if not self.placeholders then
self.placeholders = {}
self.locations = {}
local count = 0
local pattern = "${(%d+):?([^}]*)}"
while true do
local num, value = self.code:match(pattern)
if not num then
break
end
count = count+1
num = tonumber(num)
local idx = self.code:find(pattern)
self.code = self.code:gsub(pattern, "", 1)
micro.Log("IDX", idx, self.code)
local placeHolders = self.placeholders[num]
if not placeHolders then
placeHolders = {num = num}
self.placeholders[#self.placeholders+1] = placeHolders
end
self.locations[#self.locations+1] = Location.new(idx, placeHolders, self)
debug1("location total = ",#self.locations)
if value then
placeHolders.value = value
end
end
end
end
function Snippet.clone(self)
debug("Snippet.clone(self)")
local result = Snippet.new()
result:AddCodeLine(self.code)
result:Prepare()
return result
end
function Snippet.str(self)
debug("Snippet.str(self)")
local res = self.code
for i = #self.locations, 1, -1 do
local loc = self.locations[i]
res = res:sub(0, loc.idx-1) .. loc.ph.value .. res:sub(loc.idx)
end
return res
end
function Snippet.findLocation(self, loc)
debug1("Snippet.findLocation(self, loc) loc = ",loc)
for i = 1, #self.locations do
if self.locations[i]:isWithin(loc) then
return self.locations[i]
end
end
return nil
end
function Snippet.remove(self)
debug("Snippet.remove(self)")
local endPos = self.startPos:Move(self:str():len(), self.view.Buf)
self.modText = true
self.view.Cursor:SetSelectionStart(self.startPos)
self.view.Cursor:SetSelectionEnd(endPos)
self.view.Cursor:DeleteSelection()
self.view.Cursor:ResetSelection()
self.modText = false
end
function Snippet.insert(self)
debug("Snippet.insert(self)")
self.modText = true
self.view.Buf:insert(self.startPos, self:str())
self.modText = false
end
function Snippet.focusNext(self)
debug("Snippet.focusNext(self)")
if self.focused == nil then
self.focused = 0
else
self.focused = (self.focused + 1) % #self.placeholders
end
local ph = self.placeholders[self.focused+1]
for i = 1, #self.locations do
if self.locations[i].ph == ph then
self.locations[i]:focus()
return
end
end
end
local function CursorWord(bp)
debug1("CursorWord(bp)",bp)
local c = bp.Cursor
local x = c.X-1 -- start one rune before the cursor
local result = ""
while x >= 0 do
local r = util.RuneStr(c:RuneUnder(x))
if (r == " ") then -- IsWordChar(r) then
break
else
result = r .. result
end
x = x-1
end
return result
end
local function ReadSnippets(filetype)
debug1("ReadSnippets(filetype)",filetype)
local snippets = {}
local allSnippetFiles = config.ListRuntimeFiles(RTSnippets)
local exists = false
for i = 1, #allSnippetFiles do
if allSnippetFiles[i] == filetype then
exists = true
break
end
end
if not exists then
micro.InfoBar():Error("No snippets file for \""..filetype.."\"")
return snippets
end
local snippetFile = config.ReadRuntimeFile(RTSnippets, filetype)
local curSnip = nil
local lineNo = 0
for line in string.gmatch(snippetFile, "(.-)\r?\n") do
lineNo = lineNo + 1
if string.match(line,"^#") then
-- comment
elseif line:match("^snippet") then
curSnip = Snippet.new()
for snipName in line:gmatch("%s(.+)") do -- %s space .+ one or more non-empty sequence
snippets[snipName] = curSnip
end
else
local codeLine = line:match("^\t(.*)$")
if codeLine ~= nil then
curSnip:AddCodeLine(codeLine)
elseif line ~= "" then
micro.InfoBar():Error("Invalid snippets file (Line #"..tostring(lineNo)..")")
end
end
end
debugt("ReadSnippets(filetype) snippets = ",snippets)
return snippets
end
-- Check filetype and load snippets
-- Return true is snippets loaded for filetype
-- Return false if no snippets loaded
local function EnsureSnippets(bp)
debug("EnsureSnippets()")
local filetype = bp.Buf.Settings["filetype"]
if curFileType ~= filetype then
snippets = ReadSnippets(filetype)
curFileType = filetype
end
if next(snippets) == nil then
return false
end
return true
end
function onBeforeTextEvent(sb, ev)
debug1("onBeforeTextEvent(ev)",ev)
if currentSnippet ~= nil and currentSnippet.view.Buf.SharedBuffer == sb then
if currentSnippet.modText then
-- text event from the snippet. simply ignore it...
return true
end
local locStart = nil
local locEnd = nil
if ev.Deltas[1].Start ~= nil and currentSnippet ~= nil then
locStart = currentSnippet:findLocation(ev.Deltas[1].Start:Move(1, currentSnippet.view.Buf))
locEnd = currentSnippet:findLocation(ev.Deltas[1].End)
end
if locStart ~= nil and ((locStart == locEnd) or (ev.Deltas[1].End.Y==0 and ev.Deltas[1].End.X==0)) then
if locStart:handleInput(ev) then
currentSnippet.view.Cursor:Goto(-ev.C)
return false
end
end
Accept()
end
return true
end
-- Insert snippet if found.
-- Pass in the name of the snippet to be inserted by command mode
-- No name passed in then it will check the text left of the cursor
function Insert(bp, args)
local snippetName = nil
if args ~= nil and #args > 0 then
snippetName = args[1]
end
debug1("Insert(snippetName)",snippetName)
local c = bp.Cursor
local buf = bp.Buf
local xy = buffer.Loc(c.X, c.Y)
-- check if a snippet name was passed in
local noArg = false
if not snippetName then
snippetName = CursorWord(bp)
noArg = true
end
-- check filetype and load snippets
local result = EnsureSnippets(bp)
-- if no snippets return early
if (result == false) then return end
-- curSn cloned into currentSnippet if snippet found
local curSn = snippets[snippetName]
if curSn then
currentSnippet = curSn:clone()
currentSnippet.view = bp
-- remove snippet keyword from micro buffer before inserting snippet
if noArg then
currentSnippet.startPos = xy:Move(-snippetName:len(), buf)
currentSnippet.modText = true
c:SetSelectionStart(currentSnippet.startPos)
c:SetSelectionEnd(xy)
c:DeleteSelection()
c:ResetSelection()
currentSnippet.modText = false
else
-- no need to remove snippet keyword from buffer as run from command mode
currentSnippet.startPos = xy
end
-- insert snippet to micro buffer
currentSnippet:insert()
micro.InfoBar():Message("Snippet Inserted \""..snippetName.."\"")
-- Placeholders
if #currentSnippet.placeholders == 0 then
local pos = currentSnippet.startPos:Move(currentSnippet:str():len(), bp.Buf)
while bp.Cursor:LessThan(pos) do
bp.Cursor:Right()
end
while bp.Cursor:GreaterThan(pos) do
bp.Cursor:Left()
end
else
currentSnippet:focusNext()
end
else
-- Snippet not found
micro.InfoBar():Message("Unknown snippet \""..snippetName.."\"")
end
end
function Next()
debug("Next()")
if currentSnippet then
currentSnippet:focusNext()
end
end
function Accept()
debug("Accept()")
currentSnippet = nil
end
function Cancel()
debug("Cancel()")
if currentSnippet then
currentSnippet:remove()
Accept()
end
end
local function StartsWith(String,Start)
debug1("StartsWith(String,Start) String ",String)
debug1("StartsWith(String,Start) start ",start)
String = String:upper()
Start = Start:upper()
return string.sub(String,1,string.len(Start))==Start
end
-- Used for auto complete in the command prompt
function findSnippet(input)
debug1("findSnippet(input)",input)
local result = {}
-- TODO: pass bp
EnsureSnippets()
for name,v in pairs(snippets) do
if StartsWith(name, input) then
table.insert(result, name)
end
end
return result
end
-- Debug functions below
-- debug1 is for logging functionName and 1 argument passed
function debug1(functionName, argument)
if debugflag == false then return end
if argument == nil then
micro.Log("snippets-plugin -> function " .. functionName .. " = nil")
elseif argument == "" then
micro.Log("snippets-plugin -> function " .. functionName .. " = empty string")
else micro.Log("snippets-plugin -> function " .. functionName .. " = " .. tostring(argument))
end
end
-- debug is for logging functionName only
function debug(functionName)
if debugflag == false then return end
micro.Log("snippets-plugin -> function " .. functionName)
end
-- debug is for logging functionName and table
function debugt(functionName,tablepassed)
if debugflag == false then return end
micro.Log("snippets-plugin -> function " .. functionName )
tprint(tablepassed)
-- if (tablepassed == nil) then return end
-- for key,value in pairs(tablepassed) do
-- micro.Log("key - " .. tostring(key) .. "value = " .. tostring(value[1]) )
-- end
end
-- dump table
function dump(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
function tprint (tbl, indent)
if not indent then indent = 0 end
for k, v in pairs(tbl) do
formatting = string.rep(" ", indent) .. k .. ": "
if type(v) == "table" then
micro.Log(formatting .. "Table ->")
tprint(v, indent+1)
elseif type(v) == nil then
micro.Log(formatting .. " nil")
else
micro.Log(formatting .. tostring(v))
end
end
end
function checkTableisEmpty(myTable)
if next(myTable) == nil then
-- myTable is empty
end
end
function tablePrint(tbl)
for index = 1, #tbl do
micro.Log(tostring(index) .. " = " .. tostring(tbl[index]))
end
end
function init()
-- Insert a snippet
config.MakeCommand("snippetinsert", Insert, config.NoComplete)
-- Mark next placeholder
config.MakeCommand("snippetnext", Next, config.NoComplete)
-- Cancel current snippet (removes the text)
config.MakeCommand("snippetcancel", Cancel, config.NoComplete)
-- Acceptes snipped editing
config.MakeCommand("snippetaccept", Accept, config.NoComplete)
config.AddRuntimeFile("snippets", config.RTHelp, "help/snippets.md")
config.AddRuntimeFilesFromDirectory("snippets", RTSnippets, "snippets", "*.snippets")
config.TryBindKey("Alt-w", "lua:snippets.Next", false)
config.TryBindKey("Alt-a", "lua:snippets.Accept", false)
config.TryBindKey("Alt-s", "lua:snippets.Insert", false)
config.TryBindKey("Alt-d", "lua:snippets.Cancel", false)
end

View File

@ -0,0 +1,35 @@
# Snippets for code blocks used oftenly in Apache files.
# <Directory>
snippet dir
<Directory ${1:/}>
DirectoryIndex ${0:index.html}
Order Deny,Allow
Deny from All
</Directory>
# <FilesMatch>
snippet filesmatch
<FilesMatch "${1:regex}">
${0}
</FilesMatch>
# <IfModule>
snippet ifmodule
<IfModule ${1:mod_example.c}>
${0}
</IfModule>
# <LimitExcept>
snippet limitexcept
<LimitExcept ${1:POST GET}>
${0}
</LimitExcept>
# <Proxy>
snippet proxy
<Proxy ${1:*}>
${0}
</Proxy>
# <VirtualHost>
snippet virtualhost
<VirtualHost ${1:*}:${2:80}>
ServerAdmin ${3:webmaster@example.com}
DocumentRoot ${4:/www/example.com}
ServerName ${0:www.example.com}
</VirtualHost>

View File

@ -0,0 +1,102 @@
# cannot use /usr/bin/env because it does not support parameters (as -f)
snippet #! #!/usr/bin/awk -f
#!/usr/bin/awk -f
# @include is a gawk extension
snippet inc @include
@include "${1}"${0}
# @load is a gawk extension
snippet loa @load
@load "${1}"${0}
snippet beg BEGIN { ... }
BEGIN {
${0}
}
# BEGINFILE is a gawk extension
snippet begf BEGINFILE { ... }
BEGINFILE {
${0}
}
snippet end END { ... }
END {
${0}
}
# ENDFILE is a gawk extension
snippet endf ENDFILE { ... }
ENDFILE {
${0}
}
snippet pri print
print ${1:"${2}"}${0}
snippet printf printf
printf("${1:%s}\n", ${2})${0}
snippet ign IGNORECASE
IGNORECASE = ${1:1}
snippet if if {...}
if (${1}) {
${0}
}
snippet ife if ... else ...
if (${1}) {
${2}
} else {
${0}
}
snippet eif else if ...
else if (${1}) {
${0}
}
snippet el else {...}
else {
${0}
}
snippet wh while
while (${1}) {
${2}
}
snippet do do ... while
do {
${0}
} while (${1})
snippet for for
for (${2:i} = 0; i < ${1:n}; ${3:++i}) {
${0}
}
snippet fore for each
for (${1:i} in ${2:array}) {
${0}
}
# the switch is a gawk extension
snippet sw switch
switch (${1}) {
case ${2}:
${3}
break
default:
${0}
break
}
# the switch is a gawk extension
snippet case case
case ${1}:
${0}
break

View File

@ -0,0 +1,470 @@
# cs.snippets
# ===========
#
# Standard C-Sharp snippets for snipmate.
#
# Largely ported over from Visual Studio 2010 snippets plus
# a few snippets from Resharper plus a few widely known snippets.
#
# Most snippets on elements (i.e. classes, properties)
# follow suffix conventions. The order of suffixes to a snippet
# is fixed.
#
# Snippet Suffix Order
# --------------------
# 1. Access Modifiers
# 2. Class Modifiers
#
# Access Modifier Suffix Table
# ----------------------------
# + = public
# & = internal
# | = protected
# - = private
#
# Example: `cls&` expands to `internal class $1`.
# Access modifiers might be doubled to indicate
# different modifiers for get/set on properties.
# Example: `pb+-` expands to `public bool $1 { get; private set; }`
#
# Class Modifier Table
# --------------------
# ^ = static
# % = abstract
#
# Example: `cls|%` expands to `protected abstract class $1`
#
# On method and property snippets, you can directly set
# one of the common types int, string and bool, if desired,
# just by appending the type modifier.
#
# Type Modifier Table
# -------------------
# i = integer
# s = string
# b = bool
#
# Example: `pi+&` expands to `public int $1 { get; internal set; }`
#
# I'll most propably add more stuff in here like
# * List/Array constructio
# * Mostly used generics
# * Linq
# * Funcs, Actions, Predicates
# * Lambda
# * Events
#
# Feedback is welcome!
#
# Main
snippet sim
${1:public }static int Main(string[] args) {
${0}
return 0;
}
snippet simc
public class Application {
${1:public }static int Main(string[] args) {
${0}
return 0;
}
}
snippet svm
${1:public }static void Main(string[] args) {
${0}
}
# if condition
snippet if
if (${1:true}) {
${0}
}
snippet el
else {
${0}
}
snippet ifs
if (${1})
${0}
# ternary conditional
snippet t
${1} ? ${2} : ${0}
snippet ?
${1} ? ${2} : ${0}
# do while loop
snippet do
do {
${0}
} while (${1:true});
# while loop
snippet wh
while (${1:true}) {
${0}
}
# for loop
snippet for
for (int ${1:i} = 0; $1 < ${2:count}; $1${3:++}) {
${0}
}
snippet forr
for (int ${1:i} = ${2:length}; $1 >= 0; $1--) {
${0}
}
# foreach
snippet fore
foreach (${1:var} ${2:entry} in ${3}) {
${0}
}
snippet foreach
foreach (${1:var} ${2:entry} in ${3}) {
${0}
}
snippet each
foreach (${1:var} ${2:entry} in ${3}) {
${0}
}
# interfaces
snippet interface
public interface ${1:`vim_snippets#Filename()`} {
${0}
}
snippet if+
public interface ${1:`vim_snippets#Filename()`} {
${0}
}
# class bodies
snippet class
public class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls
${2:public} class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls+
public class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls+^
public static class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls&
internal class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls&^
internal static class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls|
protected class ${1:`vim_snippets#Filename()`} {
${0}
}
snippet cls|%
protected abstract class ${1:`vim_snippets#Filename()`} {
${0}
}
# constructor
snippet ctor
public ${1:`vim_snippets#Filename()`}() {
${0}
}
# properties - auto properties by default.
# default type is int with layout get / set.
snippet prop
${1:public} ${2:int} ${3} { get; set; }
snippet p
${1:public} ${2:int} ${3} { get; set; }
snippet p+
public ${1:int} ${2} { get; set; }
snippet p+&
public ${1:int} ${2} { get; internal set; }
snippet p+|
public ${1:int} ${2} { get; protected set; }
snippet p+-
public ${1:int} ${2} { get; private set; }
snippet p&
internal ${1:int} ${2} { get; set; }
snippet p&|
internal ${1:int} ${2} { get; protected set; }
snippet p&-
internal ${1:int} ${2} { get; private set; }
snippet p|
protected ${1:int} ${2} { get; set; }
snippet p|-
protected ${1:int} ${2} { get; private set; }
snippet p-
private ${1:int} ${2} { get; set; }
# property - bool
snippet pi
${1:public} int ${2} { get; set; }
snippet pi+
public int ${1} { get; set; }
snippet pi+&
public int ${1} { get; internal set; }
snippet pi+|
public int ${1} { get; protected set; }
snippet pi+-
public int ${1} { get; private set; }
snippet pi&
internal int ${1} { get; set; }
snippet pi&|
internal int ${1} { get; protected set; }
snippet pi&-
internal int ${1} { get; private set; }
snippet pi|
protected int ${1} { get; set; }
snippet pi|-
protected int ${1} { get; private set; }
snippet pi-
private int ${1} { get; set; }
# property - bool
snippet pb
${1:public} bool ${2} { get; set; }
snippet pb+
public bool ${1} { get; set; }
snippet pb+&
public bool ${1} { get; internal set; }
snippet pb+|
public bool ${1} { get; protected set; }
snippet pb+-
public bool ${1} { get; private set; }
snippet pb&
internal bool ${1} { get; set; }
snippet pb&|
internal bool ${1} { get; protected set; }
snippet pb&-
internal bool ${1} { get; private set; }
snippet pb|
protected bool ${1} { get; set; }
snippet pb|-
protected bool ${1} { get; private set; }
snippet pb-
private bool ${1} { get; set; }
# property - string
snippet ps
${1:public} string ${2} { get; set; }
snippet ps+
public string ${1} { get; set; }
snippet ps+&
public string ${1} { get; internal set; }
snippet ps+|
public string ${1} { get; protected set; }
snippet ps+-
public string ${1} { get; private set; }
snippet ps&
internal string ${1} { get; set; }
snippet ps&|
internal string ${1} { get; protected set; }
snippet ps&-
internal string ${1} { get; private set; }
snippet ps|
protected string ${1} { get; set; }
snippet ps|-
protected string ${1} { get; private set; }
snippet ps-
private string ${1} { get; set; }
# members - void
snippet m
${1:public} ${2:void} ${3}(${4}) {
${0}
}
snippet m+
public ${1:void} ${2}(${3}) {
${0}
}
snippet m&
internal ${1:void} ${2}(${3}) {
${0}
}
snippet m|
protected ${1:void} ${2}(${3}) {
${0}
}
snippet m-
private ${1:void} ${2}(${3}) {
${0}
}
# members - int
snippet mi
${1:public} int ${2}(${3}) {
${0:return 0;}
}
snippet mi+
public int ${1}(${2}) {
${0:return 0;}
}
snippet mi&
internal int ${1}(${2}) {
${0:return 0;}
}
snippet mi|
protected int ${1}(${2}) {
${0:return 0;}
}
snippet mi-
private int ${1}(${2}) {
${0:return 0;}
}
# members - bool
snippet mb
${1:public} bool ${2}(${3}) {
${0:return false;}
}
snippet mb+
public bool ${1}(${2}) {
${0:return false;}
}
snippet mb&
internal bool ${1}(${2}) {
${0:return false;}
}
snippet mb|
protected bool ${1}(${2}) {
${0:return false;}
}
snippet mb-
private bool ${1}(${2}) {
${0:return false;}
}
# members - string
snippet ms
${1:public} string ${2}(${3}) {
${0:return "";}
}
snippet ms+
public string ${1}(${2}) {
${0:return "";}
}
snippet ms&
internal string ${1}(${2}) {
${0:return "";}
}
snippet ms|
protected string ${1:}(${2:}) {
${0:return "";}
}
snippet ms-
private string ${1}(${2}) {
${0:return "";}
}
# structure
snippet struct
public struct ${1:`vim_snippets#Filename()`} {
${0}
}
# enumeration
snippet enum
enum ${1} {
${0}
}
snippet enum+
public enum ${1} {
${0}
}
# preprocessor directives
snippet #if
#if
${0}
#endif
# inline xml documentation
snippet ///
/// <summary>
/// ${0}
/// </summary>
snippet <p
<param name="${1}">${2:$1}</param>
snippet <ex
<exception cref="${1:System.Exception}">${2}</exception>
snippet <r
<returns>${1}</returns>{
snippet <s
<see cref="${1}"/>
snippet <rem
<remarks>${1}</remarks>
snippet <c
<code>${1}</code>
snippet cw
Console.WriteLine(${1});
# equals override
snippet eq
public override bool Equals(object obj) {
if (obj == null || GetType() != obj.GetType()) {
return false;
}
${0:throw new NotImplementedException();}
return base.Equals(obj);
}
# exception
snippet exc
public class ${1:MyException} : ${2:Exception} {
public $1() { }
public $1(string message) : base(message) { }
public $1(string message, Exception inner) : base(message, inner) { }
protected $1(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
# indexer
snippet index
public ${1:object} this[${2:int} index] {
get { ${0} }
set { ${0} }
}
# eventhandler
snippet inv
EventHandler temp = ${1:MyEvent};
if (${2:temp} != null) {
$2();
}
# lock
snippet lock
lock (${1:this}) {
${0}
}
# namespace
snippet namespace
namespace ${1:MyNamespace} {
${0}
}
# property
snippet prop
public ${1:int} ${2:MyProperty} { get; set; }
snippet propf
private ${1:int} ${2:myVar};
public $1 ${3:MyProperty} {
get { return $2; }
set { $2 = value; }
}
snippet propg
public ${1:int} ${2:MyProperty} { get; private set; }
# switch
snippet switch
switch (${1:switch_on}) {
${0}
default:
}
# try
snippet try
try {
${0}
}
catch (${1:System.Exception}) {
throw;
}
snippet tryf
try {
${0}
}
finally {
${1}
}
# using
snippet usi
using(${1:resource}) {
${0}
}

View File

@ -0,0 +1,228 @@
## Main
# main
snippet main
int main(int argc, const char *argv[])
{
${0}
return 0;
}
# main(void)
snippet mainn
int main(void)
{
${0}
return 0;
}
##
## Preprocessor
# #include <...>
snippet inc
#include <${1:stdio}.h>
# #include "..."
snippet Inc
#include "${1:`vim_snippets#Filename("$1.h")`}"
# ifndef...define...endif
snippet ndef
#ifndef $1
#define ${1:SYMBOL} ${2:value}
#endif /* ifndef $1 */
# define
snippet def
#define
# ifdef...endif
snippet ifdef
#ifdef ${1:FOO}
${2:#define }
#endif
# if
snippet #if
#if ${1:FOO}
${0}
#endif
# header include guard
snippet once
#ifndef ${1:`toupper(vim_snippets#Filename('$1_H', 'UNTITLED_H'))`}
#define $1
${0}
#endif /* end of include guard: $1 */
##
## Control Statements
# if
snippet if
if (${1:true}) {
${0}
}
snippet ife
if (${1:true}) {
${2}
} else {
${0}
}
# else
snippet el
else {
${0}
}
# else if
snippet elif
else if (${1:true}) {
${0}
}
# ifi
snippet ifi
if (${1:true}) ${0};
# ternary
snippet t
${1:/* condition */} ? ${2:a} : ${3:b}
# switch
snippet switch
switch (${1:/* variable */}) {
case ${2:/* variable case */}:
${3}
${4:break;}${5}
default:
${6}
}
# switch without default
snippet switchndef
switch (${1:/* variable */}) {
case ${2:/* variable case */}:
${3}
${4:break;}${5}
}
# case
snippet case
case ${1:/* variable case */}:
${2}
${3:break;}
snippet ret
return ${0};
##
## Loops
# for
snippet for
for (${2:i} = 0; $2 < ${1:count}; $2${3:++}) {
${4}
}
# for (custom)
snippet forr
for (${1:i} = ${2:0}; ${3:$1 < 10}; $1${4:++}) {
${5}
}
# while
snippet wh
while (${1:/* condition */}) {
${2}
}
# do... while
snippet do
do {
${2}
} while (${1:/* condition */});
##
## Functions
# function definition
snippet fun
${1:void} ${2:function_name}(${3})
{
${4}
}
# function declaration
snippet fund
${1:void} ${2:function_name}(${3});
##
## Types
# typedef
snippet td
typedef ${1:int} ${2:MyCustomType};
# struct
snippet st
struct ${1:`vim_snippets#Filename('$1_t', 'name')`} {
${2:/* data */}
}${3: /* optional variable list */};
# typedef struct
snippet tds
typedef struct ${2:_$1 }{
${3:/* data */}
} ${1:`vim_snippets#Filename('$1_t', 'name')`};
snippet enum
enum ${1:name} { ${0} };
# typedef enum
snippet tde
typedef enum {
${1:/* data */}
} ${2:foo};
##
## Input/Output
# printf
snippet pr
printf("${1:%s}\n"${2});
# fprintf (again, this isn't as nice as TextMate's version, but it works)
snippet fpr
fprintf(${1:stderr}, "${2:%s}\n"${3});
# getopt
snippet getopt
int choice;
while (1)
{
static struct option long_options[] =
{
/* Use flags like so:
{"verbose", no_argument, &verbose_flag, 'V'}*/
/* Argument styles: no_argument, required_argument, optional_argument */
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
${1}
{0,0,0,0}
};
int option_index = 0;
/* Argument parameters:
no_argument: " "
required_argument: ":"
optional_argument: "::" */
choice = getopt_long( argc, argv, "vh",
long_options, &option_index);
if (choice == -1)
break;
switch( choice )
{
case 'v':
${2}
break;
case 'h':
${3}
break;
case '?':
/* getopt_long will have already printed an error */
break;
default:
/* Not sure how to get here... */
return EXIT_FAILURE;
}
}
/* Deal with non-option arguments here */
if ( optind < argc )
{
while ( optind < argc )
{
${0}
}
}
##
## Miscellaneous
# This is kind of convenient
snippet .
[${1}]

View File

@ -0,0 +1,83 @@
snippet init
cmake_minimum_required(version ${1:2.8.2})
project(${2:ProjectName})
find_package(${3:library})
include_directories(${$3_INCLUDE_DIRS})
add_subdirectory(${0:src})
add_executable($2)
target_link_libraries($2 ${$3_LIBRARIES})
snippet proj
project(${0:Name})
snippet min
cmake_minimum_required(version ${0:2.8.2})
snippet include
include_directories(${${0:include_dir}})
snippet find
find_package(${1:library} ${0:REQUIRED})
snippet glob
file(glob ${1:srcs} *.${0:cpp})
snippet subdir
add_subdirectory(${0:src})
snippet lib
add_library(${1:lib} ${${0:srcs}})
snippet link
target_link_libraries(${1:bin} ${0:somelib})
snippet bin
add_executable(${1:bin})
snippet set
set(${1:var} ${0:val})
snippet dep
add_dependencies(${1:target}
${0:dep}
)
snippet Ext_url
include(ExternalProject)
ExternalProject_Add(${1:googletest}
URL ${2:http://googletest.googlecode.com/files/gtest-1.7.0.zip}
URL_HASH SHA1=${3:f85f6d2481e2c6c4a18539e391aa4ea8ab0394af}
SOURCE_DIR "${4:${CMAKE_BINARY_DIR}/gtest-src}"
BINARY_DIR "${0:${CMAKE_BINARY_DIR}/gtest-build}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
snippet Ext_git
include(ExternalProject)
ExternalProject_Add(${1:googletest}
GIT_REPOSITORY ${2:https://github.com/google/googletest.git}
GIT_TAG ${3:master}
SOURCE_DIR "${4:${CMAKE_BINARY_DIR}/googletest-src}"
BINARY_DIR "${0:${CMAKE_BINARY_DIR}/googletest-build}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
snippet props
set_target_properties(${1:target}
${2:properties} ${3:compile_flags}
${0:"-O3 -Wall -pedantic"}
)
snippet test
add_test(${1:ATestName} ${0:testCommand --options})

View File

@ -0,0 +1,987 @@
snippet .
${1} {
${0}
}
snippet !
!important
snippet bdi:m+
-moz-border-image: url(${1}) ${2:0} ${3:0} ${4:0} ${5:0} ${6:stretch} ${0:stretch};
snippet bdi:m
-moz-border-image: ${0};
snippet bdrz:m
-moz-border-radius: ${0};
snippet bxsh:m+
-moz-box-shadow: ${1:0} ${2:0} ${3:0} #${0:000};
snippet bxsh:m
-moz-box-shadow: ${0};
snippet bdi:w+
-webkit-border-image: url(${1}) ${2:0} ${3:0} ${4:0} ${5:0} ${6:stretch} ${0:stretch};
snippet bdi:w
-webkit-border-image: ${0};
snippet bdrz:w
-webkit-border-radius: ${0};
snippet bxsh:w+
-webkit-box-shadow: ${1:0} ${2:0} ${3:0} #${0:000};
snippet bxsh:w
-webkit-box-shadow: ${0};
snippet @f
@font-face {
font-family: ${1};
src: url(${0});
}
snippet @i
@import url(${0});
snippet @m
@media ${1:print} {
${0}
}
snippet bg+
background: #${1:FFF} url(${2}) ${3:0} ${4:0} ${0:no-repeat};
snippet bga
background-attachment: ${0};
snippet bga:f
background-attachment: fixed;
snippet bga:s
background-attachment: scroll;
snippet bgbk
background-break: ${0};
snippet bgbk:bb
background-break: bounding-box;
snippet bgbk:c
background-break: continuous;
snippet bgbk:eb
background-break: each-box;
snippet bgcp
background-clip: ${0};
snippet bgcp:bb
background-clip: border-box;
snippet bgcp:cb
background-clip: content-box;
snippet bgcp:nc
background-clip: no-clip;
snippet bgcp:pb
background-clip: padding-box;
snippet bgc
background-color: #${0:FFF};
snippet bgc:t
background-color: transparent;
snippet bgi
background-image: url(${0});
snippet bgi:n
background-image: none;
snippet bgo
background-origin: ${0};
snippet bgo:bb
background-origin: border-box;
snippet bgo:cb
background-origin: content-box;
snippet bgo:pb
background-origin: padding-box;
snippet bgpx
background-position-x: ${0};
snippet bgpy
background-position-y: ${0};
snippet bgp
background-position: ${1:0} ${0:0};
snippet bgr
background-repeat: ${0};
snippet bgr:n
background-repeat: no-repeat;
snippet bgr:x
background-repeat: repeat-x;
snippet bgr:y
background-repeat: repeat-y;
snippet bgr:r
background-repeat: repeat;
snippet bgz
background-size: ${0};
snippet bgz:a
background-size: auto;
snippet bgz:ct
background-size: contain;
snippet bgz:cv
background-size: cover;
snippet bg
background: ${0};
snippet bg:ie
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='${1}',sizingMethod='${0:crop}');
snippet bg:n
background: none;
snippet bd+
border: ${1:1px} ${2:solid} #${0:000};
snippet bdb+
border-bottom: ${1:1px} ${2:solid} #${0:000};
snippet bdbc
border-bottom-color: #${0:000};
snippet bdbi
border-bottom-image: url(${0});
snippet bdbi:n
border-bottom-image: none;
snippet bdbli
border-bottom-left-image: url(${0});
snippet bdbli:c
border-bottom-left-image: continue;
snippet bdbli:n
border-bottom-left-image: none;
snippet bdblrz
border-bottom-left-radius: ${0};
snippet bdbri
border-bottom-right-image: url(${0});
snippet bdbri:c
border-bottom-right-image: continue;
snippet bdbri:n
border-bottom-right-image: none;
snippet bdbrrz
border-bottom-right-radius: ${0};
snippet bdbs
border-bottom-style: ${0};
snippet bdbs:n
border-bottom-style: none;
snippet bdbw
border-bottom-width: ${0};
snippet bdb
border-bottom: ${0};
snippet bdb:n
border-bottom: none;
snippet bdbk
border-break: ${0};
snippet bdbk:c
border-break: close;
snippet bdcl
border-collapse: ${0};
snippet bdcl:c
border-collapse: collapse;
snippet bdcl:s
border-collapse: separate;
snippet bdc
border-color: #${0:000};
snippet bdci
border-corner-image: url(${0});
snippet bdci:c
border-corner-image: continue;
snippet bdci:n
border-corner-image: none;
snippet bdf
border-fit: ${0};
snippet bdf:c
border-fit: clip;
snippet bdf:of
border-fit: overwrite;
snippet bdf:ow
border-fit: overwrite;
snippet bdf:r
border-fit: repeat;
snippet bdf:sc
border-fit: scale;
snippet bdf:sp
border-fit: space;
snippet bdf:st
border-fit: stretch;
snippet bdi
border-image: url(${1}) ${2:0} ${3:0} ${4:0} ${5:0} ${6:stretch} ${0:stretch};
snippet bdi:n
border-image: none;
snippet bdl+
border-left: ${1:1px} ${2:solid} #${0:000};
snippet bdlc
border-left-color: #${0:000};
snippet bdli
border-left-image: url(${0});
snippet bdli:n
border-left-image: none;
snippet bdls
border-left-style: ${0};
snippet bdls:n
border-left-style: none;
snippet bdlw
border-left-width: ${0};
snippet bdl
border-left: ${0};
snippet bdl:n
border-left: none;
snippet bdlt
border-length: ${0};
snippet bdlt:a
border-length: auto;
snippet bdrz
border-radius: ${0};
snippet bdr+
border-right: ${1:1px} ${2:solid} #${0:000};
snippet bdrc
border-right-color: #${0:000};
snippet bdri
border-right-image: url(${0});
snippet bdri:n
border-right-image: none;
snippet bdrs
border-right-style: ${0};
snippet bdrs:n
border-right-style: none;
snippet bdrw
border-right-width: ${0};
snippet bdr
border-right: ${0};
snippet bdr:n
border-right: none;
snippet bdsp
border-spacing: ${0};
snippet bds
border-style: ${0};
snippet bds:ds
border-style: dashed;
snippet bds:dtds
border-style: dot-dash;
snippet bds:dtdtds
border-style: dot-dot-dash;
snippet bds:dt
border-style: dotted;
snippet bds:db
border-style: double;
snippet bds:g
border-style: groove;
snippet bds:h
border-style: hidden;
snippet bds:i
border-style: inset;
snippet bds:n
border-style: none;
snippet bds:o
border-style: outset;
snippet bds:r
border-style: ridge;
snippet bds:s
border-style: solid;
snippet bds:w
border-style: wave;
snippet bdt+
border-top: ${1:1px} ${2:solid} #${0:000};
snippet bdtc
border-top-color: #${0:000};
snippet bdti
border-top-image: url(${0});
snippet bdti:n
border-top-image: none;
snippet bdtli
border-top-left-image: url(${0});
snippet bdtli:c
border-corner-image: continue;
snippet bdtli:n
border-corner-image: none;
snippet bdtlrz
border-top-left-radius: ${0};
snippet bdtri
border-top-right-image: url(${0});
snippet bdtri:c
border-top-right-image: continue;
snippet bdtri:n
border-top-right-image: none;
snippet bdtrrz
border-top-right-radius: ${0};
snippet bdts
border-top-style: ${0};
snippet bdts:n
border-top-style: none;
snippet bdtw
border-top-width: ${0};
snippet bdt
border-top: ${0};
snippet bdt:n
border-top: none;
snippet bdw
border-width: ${0};
snippet bd
border: ${0};
snippet bd:n
border: none;
snippet b
bottom: ${0};
snippet b:a
bottom: auto;
snippet bxsh+
box-shadow: ${1:0} ${2:0} ${3:0} #${0:000};
snippet bxsh
box-shadow: ${0};
snippet bxsh:n
box-shadow: none;
snippet bxz
box-sizing: ${0};
snippet bxz:bb
box-sizing: border-box;
snippet bxz:cb
box-sizing: content-box;
snippet cps
caption-side: ${0};
snippet cps:b
caption-side: bottom;
snippet cps:t
caption-side: top;
snippet cl
clear: ${0};
snippet cl:b
clear: both;
snippet cl:l
clear: left;
snippet cl:n
clear: none;
snippet cl:r
clear: right;
snippet cp
clip: ${0};
snippet cp:a
clip: auto;
snippet cp:r
clip: rect(${1:0} ${2:0} ${3:0} ${0:0});
snippet c
color: #${0:000};
snippet ct
content: ${0};
snippet ct:a
content: attr(${0});
snippet ct:cq
content: close-quote;
snippet ct:c
content: counter(${0});
snippet ct:cs
content: counters(${0});
snippet ct:ncq
content: no-close-quote;
snippet ct:noq
content: no-open-quote;
snippet ct:n
content: normal;
snippet ct:oq
content: open-quote;
snippet coi
counter-increment: ${0};
snippet cor
counter-reset: ${0};
snippet cur
cursor: ${0};
snippet cur:a
cursor: auto;
snippet cur:c
cursor: crosshair;
snippet cur:d
cursor: default;
snippet cur:ha
cursor: hand;
snippet cur:he
cursor: help;
snippet cur:m
cursor: move;
snippet cur:p
cursor: pointer;
snippet cur:t
cursor: text;
snippet d
display: ${0};
snippet d:mib
display: -moz-inline-box;
snippet d:mis
display: -moz-inline-stack;
snippet d:b
display: block;
snippet d:cp
display: compact;
snippet d:ib
display: inline-block;
snippet d:itb
display: inline-table;
snippet d:i
display: inline;
snippet d:li
display: list-item;
snippet d:n
display: none;
snippet d:ri
display: run-in;
snippet d:tbcp
display: table-caption;
snippet d:tbc
display: table-cell;
snippet d:tbclg
display: table-column-group;
snippet d:tbcl
display: table-column;
snippet d:tbfg
display: table-footer-group;
snippet d:tbhg
display: table-header-group;
snippet d:tbrg
display: table-row-group;
snippet d:tbr
display: table-row;
snippet d:tb
display: table;
snippet ec
empty-cells: ${0};
snippet ec:h
empty-cells: hide;
snippet ec:s
empty-cells: show;
snippet exp
expression()
snippet fl
float: ${0};
snippet fl:l
float: left;
snippet fl:n
float: none;
snippet fl:r
float: right;
snippet f+
font: ${1:1em} ${2:Arial},${0:sans-serif};
snippet fef
font-effect: ${0};
snippet fef:eb
font-effect: emboss;
snippet fef:eg
font-effect: engrave;
snippet fef:n
font-effect: none;
snippet fef:o
font-effect: outline;
snippet femp
font-emphasize-position: ${0};
snippet femp:a
font-emphasize-position: after;
snippet femp:b
font-emphasize-position: before;
snippet fems
font-emphasize-style: ${0};
snippet fems:ac
font-emphasize-style: accent;
snippet fems:c
font-emphasize-style: circle;
snippet fems:ds
font-emphasize-style: disc;
snippet fems:dt
font-emphasize-style: dot;
snippet fems:n
font-emphasize-style: none;
snippet fem
font-emphasize: ${0};
snippet ff
font-family: ${0};
snippet ff:c
font-family: ${0:'Monotype Corsiva','Comic Sans MS'},cursive;
snippet ff:f
font-family: ${0:Capitals,Impact},fantasy;
snippet ff:m
font-family: ${0:Monaco,'Courier New'},monospace;
snippet ff:ss
font-family: ${0:Helvetica,Arial},sans-serif;
snippet ff:s
font-family: ${0:Georgia,'Times New Roman'},serif;
snippet fza
font-size-adjust: ${0};
snippet fza:n
font-size-adjust: none;
snippet fz
font-size: ${0};
snippet fsm
font-smooth: ${0};
snippet fsm:aw
font-smooth: always;
snippet fsm:a
font-smooth: auto;
snippet fsm:n
font-smooth: never;
snippet fst
font-stretch: ${0};
snippet fst:c
font-stretch: condensed;
snippet fst:e
font-stretch: expanded;
snippet fst:ec
font-stretch: extra-condensed;
snippet fst:ee
font-stretch: extra-expanded;
snippet fst:n
font-stretch: normal;
snippet fst:sc
font-stretch: semi-condensed;
snippet fst:se
font-stretch: semi-expanded;
snippet fst:uc
font-stretch: ultra-condensed;
snippet fst:ue
font-stretch: ultra-expanded;
snippet fs
font-style: ${0};
snippet fs:i
font-style: italic;
snippet fs:n
font-style: normal;
snippet fs:o
font-style: oblique;
snippet fv
font-variant: ${0};
snippet fv:n
font-variant: normal;
snippet fv:sc
font-variant: small-caps;
snippet fw
font-weight: ${0};
snippet fw:b
font-weight: bold;
snippet fw:br
font-weight: bolder;
snippet fw:lr
font-weight: lighter;
snippet fw:n
font-weight: normal;
snippet f
font: ${0};
snippet h
height: ${0};
snippet h:a
height: auto;
snippet l
left: ${0};
snippet l:a
left: auto;
snippet lts
letter-spacing: ${0};
snippet lh
line-height: ${0};
snippet lisi
list-style-image: url(${0});
snippet lisi:n
list-style-image: none;
snippet lisp
list-style-position: ${0};
snippet lisp:i
list-style-position: inside;
snippet lisp:o
list-style-position: outside;
snippet list
list-style-type: ${0};
snippet list:c
list-style-type: circle;
snippet list:dclz
list-style-type: decimal-leading-zero;
snippet list:dc
list-style-type: decimal;
snippet list:d
list-style-type: disc;
snippet list:lr
list-style-type: lower-roman;
snippet list:n
list-style-type: none;
snippet list:s
list-style-type: square;
snippet list:ur
list-style-type: upper-roman;
snippet lis
list-style: ${0};
snippet lis:n
list-style: none;
snippet mb
margin-bottom: ${0};
snippet mb:a
margin-bottom: auto;
snippet ml
margin-left: ${0};
snippet ml:a
margin-left: auto;
snippet mr
margin-right: ${0};
snippet mr:a
margin-right: auto;
snippet mt
margin-top: ${0};
snippet mt:a
margin-top: auto;
snippet m
margin: ${0};
snippet m:4
margin: ${1:0} ${2:0} ${3:0} ${0:0};
snippet m:3
margin: ${1:0} ${2:0} ${0:0};
snippet m:2
margin: ${1:0} ${0:0};
snippet m:0
margin: 0;
snippet m:a
margin: auto;
snippet mah
max-height: ${0};
snippet mah:n
max-height: none;
snippet maw
max-width: ${0};
snippet maw:n
max-width: none;
snippet mih
min-height: ${0};
snippet miw
min-width: ${0};
snippet op
opacity: ${0};
snippet op:ie
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=${0:100});
snippet op:ms
-ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=${0:100})';
snippet orp
orphans: ${0};
snippet o+
outline: ${1:1px} ${2:solid} #${0:000};
snippet oc
outline-color: ${0:#000};
snippet oc:i
outline-color: invert;
snippet oo
outline-offset: ${0};
snippet os
outline-style: ${0};
snippet ow
outline-width: ${0};
snippet o
outline: ${0};
snippet o:n
outline: none;
snippet ovs
overflow-style: ${0};
snippet ovs:a
overflow-style: auto;
snippet ovs:mq
overflow-style: marquee;
snippet ovs:mv
overflow-style: move;
snippet ovs:p
overflow-style: panner;
snippet ovs:s
overflow-style: scrollbar;
snippet ovx
overflow-x: ${0};
snippet ovx:a
overflow-x: auto;
snippet ovx:h
overflow-x: hidden;
snippet ovx:s
overflow-x: scroll;
snippet ovx:v
overflow-x: visible;
snippet ovy
overflow-y: ${0};
snippet ovy:a
overflow-y: auto;
snippet ovy:h
overflow-y: hidden;
snippet ovy:s
overflow-y: scroll;
snippet ovy:v
overflow-y: visible;
snippet ov
overflow: ${0};
snippet ov:a
overflow: auto;
snippet ov:h
overflow: hidden;
snippet ov:s
overflow: scroll;
snippet ov:v
overflow: visible;
snippet pb
padding-bottom: ${0};
snippet pl
padding-left: ${0};
snippet pr
padding-right: ${0};
snippet pt
padding-top: ${0};
snippet p
padding: ${0};
snippet p:4
padding: ${1:0} ${2:0} ${3:0} ${0:0};
snippet p:3
padding: ${1:0} ${2:0} ${0:0};
snippet p:2
padding: ${1:0} ${0:0};
snippet p:0
padding: 0;
snippet pgba
page-break-after: ${0};
snippet pgba:aw
page-break-after: always;
snippet pgba:a
page-break-after: auto;
snippet pgba:l
page-break-after: left;
snippet pgba:r
page-break-after: right;
snippet pgbb
page-break-before: ${0};
snippet pgbb:aw
page-break-before: always;
snippet pgbb:a
page-break-before: auto;
snippet pgbb:l
page-break-before: left;
snippet pgbb:r
page-break-before: right;
snippet pgbi
page-break-inside: ${0};
snippet pgbi:a
page-break-inside: auto;
snippet pgbi:av
page-break-inside: avoid;
snippet pos
position: ${0};
snippet pos:a
position: absolute;
snippet pos:f
position: fixed;
snippet pos:r
position: relative;
snippet pos:s
position: static;
snippet q
quotes: ${0};
snippet q:en
quotes: '\201C' '\201D' '\2018' '\2019';
snippet q:n
quotes: none;
snippet q:ru
quotes: '\00AB' '\00BB' '\201E' '\201C';
snippet rz
resize: ${0};
snippet rz:b
resize: both;
snippet rz:h
resize: horizontal;
snippet rz:n
resize: none;
snippet rz:v
resize: vertical;
snippet r
right: ${0};
snippet r:a
right: auto;
snippet tbl
table-layout: ${0};
snippet tbl:a
table-layout: auto;
snippet tbl:f
table-layout: fixed;
snippet tal
text-align-last: ${0};
snippet tal:a
text-align-last: auto;
snippet tal:c
text-align-last: center;
snippet tal:l
text-align-last: left;
snippet tal:r
text-align-last: right;
snippet ta
text-align: ${0};
snippet ta:c
text-align: center;
snippet ta:l
text-align: left;
snippet ta:r
text-align: right;
snippet td
text-decoration: ${0};
snippet td:l
text-decoration: line-through;
snippet td:n
text-decoration: none;
snippet td:o
text-decoration: overline;
snippet td:u
text-decoration: underline;
snippet te
text-emphasis: ${0};
snippet te:ac
text-emphasis: accent;
snippet te:a
text-emphasis: after;
snippet te:b
text-emphasis: before;
snippet te:c
text-emphasis: circle;
snippet te:ds
text-emphasis: disc;
snippet te:dt
text-emphasis: dot;
snippet te:n
text-emphasis: none;
snippet th
text-height: ${0};
snippet th:a
text-height: auto;
snippet th:f
text-height: font-size;
snippet th:m
text-height: max-size;
snippet th:t
text-height: text-size;
snippet ti
text-indent: ${0};
snippet ti:-
text-indent: -9999px;
snippet tj
text-justify: ${0};
snippet tj:a
text-justify: auto;
snippet tj:d
text-justify: distribute;
snippet tj:ic
text-justify: inter-cluster;
snippet tj:ii
text-justify: inter-ideograph;
snippet tj:iw
text-justify: inter-word;
snippet tj:k
text-justify: kashida;
snippet tj:t
text-justify: tibetan;
snippet to+
text-outline: ${1:0} ${2:0} #${0:000};
snippet to
text-outline: ${0};
snippet to:n
text-outline: none;
snippet tr
text-replace: ${0};
snippet tr:n
text-replace: none;
snippet tsh+
text-shadow: ${1:0} ${2:0} ${3:0} #${0:000};
snippet tsh
text-shadow: ${0};
snippet tsh:n
text-shadow: none;
snippet tt
text-transform: ${0};
snippet tt:c
text-transform: capitalize;
snippet tt:l
text-transform: lowercase;
snippet tt:n
text-transform: none;
snippet tt:u
text-transform: uppercase;
snippet tw
text-wrap: ${0};
snippet tw:no
text-wrap: none;
snippet tw:n
text-wrap: normal;
snippet tw:s
text-wrap: suppress;
snippet tw:u
text-wrap: unrestricted;
snippet t
top: ${0};
snippet t:a
top: auto;
snippet va
vertical-align: ${0};
snippet va:bl
vertical-align: baseline;
snippet va:b
vertical-align: bottom;
snippet va:m
vertical-align: middle;
snippet va:sub
vertical-align: sub;
snippet va:sup
vertical-align: super;
snippet va:tb
vertical-align: text-bottom;
snippet va:tt
vertical-align: text-top;
snippet va:t
vertical-align: top;
snippet v
visibility: ${0};
snippet v:c
visibility: collapse;
snippet v:h
visibility: hidden;
snippet v:v
visibility: visible;
snippet whsc
white-space-collapse: ${0};
snippet whsc:ba
white-space-collapse: break-all;
snippet whsc:bs
white-space-collapse: break-strict;
snippet whsc:k
white-space-collapse: keep-all;
snippet whsc:l
white-space-collapse: loose;
snippet whsc:n
white-space-collapse: normal;
snippet whs
white-space: ${0};
snippet whs:n
white-space: normal;
snippet whs:nw
white-space: nowrap;
snippet whs:pl
white-space: pre-line;
snippet whs:pw
white-space: pre-wrap;
snippet whs:p
white-space: pre;
snippet wid
widows: ${0};
snippet w
width: ${0};
snippet w:a
width: auto;
snippet wob
word-break: ${0};
snippet wob:ba
word-break: break-all;
snippet wob:bs
word-break: break-strict;
snippet wob:k
word-break: keep-all;
snippet wob:l
word-break: loose;
snippet wob:n
word-break: normal;
snippet wos
word-spacing: ${0};
snippet wow
word-wrap: ${0};
snippet wow:no
word-wrap: none;
snippet wow:n
word-wrap: normal;
snippet wow:s
word-wrap: suppress;
snippet wow:u
word-wrap: unrestricted;
snippet z
z-index: ${0};
snippet z:a
z-index: auto;
snippet zoo
zoom: 1;
snippet :h
:hover
snippet :fc
:first-child
snippet :lc
:last-child
snippet :nc
:nth-child(${0})
snippet :nlc
:nth-last-child(${0})
snippet :oc
:only-child
snippet :a
:after
snippet :b
:before
snippet ::a
::after
snippet ::b
::before

View File

@ -0,0 +1,338 @@
### Import
snippet imp
import
snippet pimp
public import
### My favorite modules
snippet io
std.stdio
snippet traits
std.traits
snippet conv
std.conv
snippet arr
std.array
snippet algo
std.algorithm
snippet theusual
import std.stdio, std.string, std.array;
import std.traits, std.conv, std.algorithm;
import std.math, std.regex;
### Control Structures
snippet for
for(int ${1:i} = 0; $1 < ${2:count}; $1++) {
${0}
}
snippet fe
foreach(${1:elem}; ${2:range}) {
${0}
}
snippet fei
foreach(${1:i}, ${2:elem}; ${3:range}) {
${0}
}
snippet fer
foreach_reverse(${1:elem}; ${2:range}) {
${0}
}
snippet feri
foreach_reverse(${1:i}, ${2:elem}; ${3:range}) {
${0}
}
snippet sce
scope(exit) ${1:f.close();}
snippet scs
scope(success) ${1}
snippet scf
scope(failure) ${1}
snippet el
else {
${1}
}
snippet eif
else if(${1}) {
${0}
}
snippet if
if(${1}) {
${0}
}
snippet ife
if(${1}) {
${2}
} else {
${3}
}
snippet ifee
if(${1}) {
${2}
} else if(${3}) {
${4}
} else {
${5}
}
snippet sw
switch(${1}) {
${0}
}
snippet cs
case ${1:0}:
${2}
break;
snippet def
default:
${0}
snippet fsw
final switch(${1}) {
${0}
}
snippet try
try {
${1}
} catch(${2:Exception} ${3:e}) {
${4}
}
snippet tcf
try {
${0}
} catch(${1:Exception} ${2:e}) {
${3}
} finally {
${4}
}
snippet wh
while(${1:cond}) {
${0}
}
snippet dowh
do {
${1}
} while(${2});
snippet sif
static if(${1:cond}) {
${2}
}
snippet sife
static if(${1}) {
${2}
} else {
${3}
}
snippet sifee
static if(${1}) {
${2}
} else static if(${3}) {
${4}
} else {
${5}
}
snippet seif
else static if(${1}) {
${2}
}
snippet ?
(${1: a > b}) ? ${2:a} : ${3:b};
snippet with
with(${1:exp}) {
${2}
} ${0}
### Functions
snippet fun
${1:auto} ${2:func}(${3:params}) {
${0}
}
snippet contr
in {
${1}
} out {
${2}
} body {
${0}
}
snippet l
(${1:x}) => ${2:x}${0:;}
snippet funl
function (${1:int x}) => ${2}${3:;}
snippet del
delegate (${1:int x}) => ${2}${3:;}
### Templates
snippet temp
template ${1:`vim_snippets#Filename("$2", "untitled")`}(${2:T}) {
${0}
}
snippet tempif
template ${1:`vim_snippets#Filename("$2", "untitled")`}(${2:T}) if(${3:isSomeString!}$2) {
${0}
}
snippet opApply
int opApply(Dg)(Dg dg) if(ParameterTypeTuble!Dg.length == 2) {
${0}
}
snippet psn
pure @safe nothrow
snippet safe
@safe
snippet trusted
@trusted
snippet system
@system
### OOPs
snippet cl
class${1:(T)} ${2:`vim_snippets#Filename("$3", "untitled")`} {
${0}
}
snippet str
struct${1:(T)} ${2:`vim_snippets#Filename("$3", "untitled")`} {
${0}
}
snippet uni
union${1:(T)} ${2:`vim_snippets#Filename("$3", "untitled")`} {
${0}
}
snippet inter
interface I${1:`vim_snippets#Filename("$2", "untitled")`} {
${0}
}
snippet enum
enum ${1} {
${0}
}
snippet pu
public
snippet pr
private
snippet po
protected
snippet ctor
this(${1}) {
${0}
}
snippet dtor
~this(${1}) {
${0}
}
### Type Witchery
snippet al
alias ${1:b} = ${2:a};
${0}
snippet alth
alias ${1:value} this;
${0}
### The Commonplace
snippet main
void main() {
${0}
}
snippet maina
void main(string[] args) {
${0}
}
snippet mod
module ${1:main};${0}
snippet var
${1:auto} ${2:var} = ${0:1};
snippet new
${1:auto} ${2:var} = new ${3:Object}(${4});
${0}
snippet file
auto ${1:f} = File(${2:"useful_info.xml"}, ${3:"rw"});
${0}
snippet map
map!(${1:f})(${2:xs});
${0}
snippet filter
filter!(${1:p})(${2:xs});
${0}
snippet reduce
reduce!(${1:f})(${2:xs});
${0}
snippet find
find!(${1:p})($2:xs);
${0}
snippet aa
${1:int}[${2:string}] ${3:dict} = ${0};
### Misc
snippet #!
#!/usr/bin/env rdmd
snippet bang
#!/usr/bin/env rdmd
snippet rdmd
#!/usr/bin/env rdmd
snippet isstr
isSomeString!${1:S}
snippet isnum
isNumeric!${1:N}
snippet tos
to!string(${1:x});
${0}
snippet toi
to!int(${1:str});
${0}
snippet tod
to!double(${1:str});
${0}
snippet un
unittest {
${0}
}
snippet ver
version(${1:Posix}) {
${0}
}
snippet de
debug {
${0}
}
snippet sst
shared static this(${1}) {
${0}
}
snippet td
// Typedef is deprecated. Use alias instead.
typedef
snippet ino
inout
snippet imm
immutable
snippet fin
final
snippet con
const
snippet psi
private static immutable ${1:int} ${2:Constant} = ${3:1};
${0}
snippet prag
pragma(${1})
snippet pms
pragma(msg, ${1:Warning});
snippet asm
asm {
${1}
}
snippet mixin
mixin(${1:`writeln("Hello, World!");`});
snippet over
override
snippet ret
return ${1};
snippet FILE
__FILE__
snippet MOD
__MODULE__
snippet LINE
__LINE__
snippet FUN
__FUNCTION__
snippet PF
__PRETTY_FUNCTION__
snippet cast
cast(${1:T})(${2:val});
snippet /*
/*
* ${1}
*/
### Fun stuff
snippet idk
// I don't know how this works. Don't touch it.
snippet idfk
// Don't FUCKING touch this.

View File

@ -0,0 +1,82 @@
snippet lib
#library('${1}');
${0}
snippet im
#import('${1}');
${0}
snippet so
#source('${1}');
${0}
snippet main
static void main() {
${0}
}
snippet st
static ${0}
snippet fi
final ${0}
snippet re
return ${0}
snippet br
break;
snippet th
throw ${0}
snippet cl
class ${1:`vim_snippets#Filename("", "untitled")`} ${0}
snippet in
interface ${1:`vim_snippets#Filename("", "untitled")`} ${0}
snippet imp
implements ${0}
snippet ext
extends ${0}
snippet if
if (${1:true}) {
${0}
}
snippet ife
if (${1:true}) {
${2}
} else {
${0}
}
snippet el
else
snippet sw
switch (${1}) {
${0}
}
snippet cs
case ${1}:
${0}
snippet de
default:
${0}
snippet for
for (var ${2:i} = 0, len = ${1:things}.length; $2 < len; ${3:++}$2) {
${0:$1[$2]}
}
snippet fore
for (final ${2:item} in ${1:itemList}) {
${0}
}
snippet wh
while (${1:/* condition */}) {
${0}
}
snippet dowh
do {
${0}
} while (${0:/* condition */});
snippet as
assert(${0:/* condition */});
snippet try
try {
${0}
} catch (${1:Exception e}) {
}
snippet tryf
try {
${0}
} catch (${1:Exception e}) {
} finally {
}

View File

@ -0,0 +1,29 @@
# Shebang. Executing bash via /usr/bin/env makes scripts more portable.
snippet #!
#!/usr/bin/env fish
snippet if
if ${1:condition}
${0:#statements}
end
snippet for
for ${1:needle} in ${1:haystack}
${0:#statements}
end
snippet while
while ${1:condition}
${0:#statements}
end
snippet switch
switch ${1:word}
case ${2:pattern}
${0:#statements}
end
snippet function
function ${1:name}
${0:#body}
end

View File

@ -0,0 +1,93 @@
snippet impl
implicit none
$0
snippet prog
program ${1:main}
$0
end program $1
snippet mod
module ${1:modulename}
$0
end module $1
snippet proc
procedure ${1:name}
${0}
end procedure $1
snippet iface
interface ${1:name}
${0}
end interface $1
snippet doc
! """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
! File: ${2:`vim_snippets#Filename('$1')`}
! Author: `g:snips_author`
! Email: `g:snips_email`
! Github: `g:snips_github`
! Description: $1
! """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
$0
# Variables definitions
# Boolean
snippet bool
logical :: $0
# Integer
snippet int
integer :: $0
snippet real
real :: $0
# Double Precision
snippet double
double precision :: $0
# Char
snippet str
character(len=${1:*}) :: ${0:}
# Types
snippet type
type(${1:name})
$0
end type
snippet const
${1:type}, parameter :: $2 = $0
snippet arr
${1:type}, allocatable, dimension(${2::}) :: $0
snippet intent
${1:type}, intent(inout) :: $0
# Array
snippet /
(/ $1 /) ${2:,&} $0
snippet if
if (${1:condition}) then
$2
end if
snippet case
select case (${1:expr})
case ($2)
case default
$3
end select $0
snippet do
do ${1:i} = ${2:start},${3:end}, ${4:incr}
$4
end do
snippet dow
do while (${1:condition})
$2
end do
snippet sub
subroutine ${1:name}($2)
$0
end subroutine $1
snippet func
function ${1:name}($2) result($3)
$0
end function $1
snippet pr
write(*,*) $0
snippet read
read( unit = ${1:fp}, file = ${2:filename}${3:, iostat = IERR }) $0
snippet write
write( unit = ${1:fp}, file = ${2:filename}${3:, iostat = IERR }) $0
snippet open
open (unit = ${1:fp}, file = ${2:filename}, status = unknown${3:, iostat = IERR }) $0
snippet close
close ( unit = ${1:fp} ) $0

View File

@ -0,0 +1,237 @@
# shorthand variable declaration
snippet v
${1} := ${2}
# variable initialization
snippet vr
var ${1:t} ${0:string}
# variable declaration
snippet var
var ${1} ${2} = ${3}
# variables declaration
snippet vars
var (
${1} ${2} = ${3}
)
# append
snippet ap
append(${1:slice}, ${0:value})
# bool
snippet bl
bool
# byte
snippet bt
byte
# break
snippet br
break
# channel
snippet ch
chan ${0:int}
# case
snippet cs
case ${1:value}:
${0}
# const
snippet c
const ${1:NAME} = ${0:0}
# constants with iota
snippet co
const (
${1:NAME1} = iota
${0:NAME2}
)
# continue
snippet cn
continue
# defer
snippet df
defer ${0:func}()
# defer recover
snippet dfr
defer func() {
if err := recover(); err != nil {
${0}
}
}()
# int
snippet i
int
# import
snippet im
import (
"${1:package}"
)
# interface
snippet in
interface{}
# full interface snippet
snippet inf
interface ${1:name} {
${2:/* methods */}
}
# if condition
snippet if
if ${1:/* condition */} {
${2}
}
snippet ife
if ${1:/* condition */} {
${2}
} else {
${0}
}
# else snippet
snippet el
else {
${1}
}
# error snippet
snippet ir
if err != nil {
return err
}
${0}
# false
snippet f
false
# fallthrough
snippet ft
fallthrough
# float
snippet fl
float32
# float32
snippet f3
float32
# float64
snippet f6
float64
# if else
snippet ie
if ${1:/* condition */} {
${2}
} else {
${3}
}
${0}
# for int loop
snippet for
for ${1}{
${0}
}
# for int loop
snippet fori
for ${2:i} := 0; $2 < ${1:count}; $2${3:++} {
${0}
}
# for range loop
snippet forr
for ${1:e} := range ${2:collection} {
${0}
}
# function simple
snippet fun
func ${1:funcName}(${2}) ${3:error} {
${4}
}
${0}
# function on receiver
snippet fum
func (${1:receiver} ${2:type}) ${3:funcName}(${4}) ${5:error} {
${6}
}
${0}
# log printf
snippet lf
log.Printf("%${1:s}", ${2:var})
# log printf
snippet lp
log.Println("${1}")
# make
snippet mk
make(${1:[]string}, ${0:0})
# map
snippet mp
map[${1:string}]${0:int}
# main()
snippet main
func main() {
${1}
}
${0}
# new
snippet nw
new(${0:type})
# package
snippet pa
package ${1:main}
# panic
snippet pn
panic("${0:msg}")
# print
snippet pr
fmt.Printf("%${1:s}\n", ${2:var})
# println
snippet pl
fmt.Println("${1:s}")
# range
snippet rn
range ${0}
# return
snippet rt
return ${0}
# result
snippet rs
result
# select
snippet sl
select {
case ${1:v1} := <-${2:chan1}
${3}
default:
${0}
}
# string
snippet sr
string
# struct
snippet st
struct ${1:name} {
${2:/* data */}
}
${0}
# switch
snippet sw
switch ${1:var} {
case ${2:value1}:
${3}
case ${4:value2}:
${5}
default:
${0}
}
snippet sp
fmt.Sprintf("%${1:s}", ${2:var})
# true
snippet t
true
# goroutine named function
snippet g
go ${1:funcName}(${0})
# goroutine anonymous function
snippet ga
go func(${1} ${2:type}) {
${3:/* code */}
}(${0})
snippet test test function
func Test${1:name}(t *testing.T) {
${2}
}
${0}
snippet bench benchmark function
func Benchmark${1:name}(b *testing.B) {
for i := 0; i < b.N; i++ {
${2}
}
}
${0}

View File

@ -0,0 +1,37 @@
snippet t
%table
%tr
%th
${1:headers}
%tr
%td
${0:headers}
snippet ul
%ul
%li
${0:item}
%li
snippet rp
= render :partial => "${0:item}"
snippet rpc
= render :partial => "${1:item}", :collection => ${0:@$1s}
snippet rpl
= render :partial => "${1:item}", :locals => { :${2:$1} => ${0:@$1}
snippet rpo
= render :partial => "${1:item}", :object => ${0:@$1}
snippet lt
= link_to ${1:name}, ${2:dest}
snippet mt
= mail_to ${1:email_address}, ${2:name}
snippet mts
= mail_to ${1:email_address}, ${2:name}, :subject => ${3}, :body => ${4}
snippet ife
- if ${1:condition}
${2}
- else
${0}
snippet ifp
- if ${1:condition}.presence?
${0}
snippet ntc
= number_to_currency(${1})

View File

@ -0,0 +1,115 @@
snippet lang
{-# LANGUAGE ${0:OverloadedStrings} #-}
snippet haddock
{-# OPTIONS_HADDOCK ${0:hide} #-}
snippet ghc
{-# OPTIONS_GHC ${0:-fno-warn-unused-imports} #-}
snippet inline
{-# INLINE ${0:name} #-}
snippet info
-- |
-- Module : ${1:`substitute(substitute(expand('%:r'), '[/\\]','.','g'),'^\%(\l*\.\)\?','','')`}
-- Copyright : ${2:Author} ${3:2011-2012}
-- License : ${4:BSD3}
--
-- Maintainer : ${5:email@something.com}
-- Stability : ${6:experimental}
-- Portability : ${7:unknown}
--
-- ${0:Description}
--
snippet imp
import ${0:Data.Text}
snippet import
import ${0:Data.Text}
snippet import2
import ${1:Data.Text} (${0:head})
snippet impq
import qualified ${1:Data.Text} as ${0:T}
snippet importq
import qualified ${1:Data.Text} as ${0:T}
snippet inst
instance ${1:Monoid} ${2:Type} where
${0}
snippet type
type ${1:Type} = ${0:Type}
snippet data
data ${1:Type} = ${2:$1} ${0:Int}
snippet newtype
newtype ${1:Type} = ${2:$1} ${0:Int}
snippet class
class ${1:Class} a where
${0}
snippet module
module `substitute(substitute(expand('%:r'), '[/\\]','.','g'),'^\%(\l*\.\)\?','','')` (
) where
`expand('%') =~ 'Main' ? "\nmain :: IO ()\nmain = undefined" : ""`
snippet main
main :: IO ()
main = ${0:undefined}
snippet const
${1:name} :: ${2:a}
$1 = ${0:undefined}
snippet fn
${1:fn} :: ${2:a} -> ${3:a}
$1 ${4} = ${0:undefined}
snippet fn2
${1:fn} :: ${2:a} -> ${3:a} -> ${4:a}
$1 ${5} = ${0:undefined}
snippet fn3
${1:fn} :: ${2:a} -> ${3:a} -> ${4:a} -> ${5:a}
$1 ${6} = ${0:undefined}
snippet => "Type constraint"
(${1:Class} ${2:a}) => $2
snippet ap
${1:map} ${2:fn} ${0:list}
snippet \
\\${1:x} -> ${0:expression}
snippet (\
(\\${1:x} -> ${0:expression})
snippet <-
${1:a} <- ${0:m a}
snippet ->
${1:m a} -> ${0:a}
snippet tup
(${1:a}, ${0:b})
snippet tup2
(${1:a}, ${2:b}, ${0:c})
snippet tup3
(${1:a}, ${2:b}, ${3:c}, ${0:d})
snippet rec
${1:Record} { ${2:recFieldA} = ${3:undefined}
, ${4:recFieldB} = ${0:undefined}
}
snippet case
case ${1:something} of
${2} -> ${0}
snippet let
let ${1} = ${2}
in ${3}
snippet where
where
${1:fn} = ${0:undefined}
snippet spec
module `substitute(substitute(expand('%:r'), '[/\\]','.','g'),'^\%(\l*\.\)\?','','')` (main, spec) where
import Test.Hspec
import Test.QuickCheck
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "${1}" $ do
$0
snippet desc
describe "${1}" $ do
$0
snippet it
it "${1}" $
$0
snippet itp
it "${1}" $ property $
$0

View File

@ -0,0 +1,877 @@
# Some useful Unicode entities
# Non-Breaking Space
snippet nbs
&nbsp;
# ←
snippet left
&#x2190;
# →
snippet right
&#x2192;
# ↑
snippet up
&#x2191;
# ↓
snippet down
&#x2193;
# ↩
snippet return
&#x21A9;
# ⇤
snippet backtab
&#x21E4;
# ⇥
snippet tab
&#x21E5;
# ⇧
snippet shift
&#x21E7;
# ⌃
snippet ctrl
&#x2303;
# ⌅
snippet enter
&#x2305;
# ⌘
snippet cmd
&#x2318;
# ⌥
snippet option
&#x2325;
# ⌦
snippet delete
&#x2326;
# ⌫
snippet backspace
&#x232B;
# ⎋
snippet esc
&#x238B;
# comment
snippet //
<!-- ${1} -->${0}
# Generic Doctype
snippet doctype HTML 4.01 Strict
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
snippet doctype HTML 4.01 Transitional
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
snippet doctype HTML 5
<!DOCTYPE HTML>
snippet doctype XHTML 1.0 Frameset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
snippet doctype XHTML 1.0 Strict
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
snippet doctype XHTML 1.0 Transitional
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
snippet doctype XHTML 1.1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
# HTML Doctype 4.01 Strict
snippet docts
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
# HTML Doctype 4.01 Transitional
snippet doct
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
# HTML Doctype 5
snippet doct5
<!DOCTYPE HTML>
# XHTML Doctype 1.0 Frameset
snippet docxf
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
# XHTML Doctype 1.0 Strict
snippet docxs
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
# XHTML Doctype 1.0 Transitional
snippet docxt
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
# XHTML Doctype 1.1
snippet docx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
# Attributes
snippet attr
${1:attribute}="${0:property}"
snippet attr+
${1:attribute}="${2:property}" attr+
snippet .
class="${1}"
snippet #
id="${1}"
snippet alt
alt="${1}"
snippet charset
charset="${1:utf-8}"
snippet data
data-${1}="${2:$1}"
snippet for
for="${1}"
snippet height
height="${1}"
snippet href
href="${1:#}"
snippet lang
lang="${1:en}"
snippet media
media="${1}"
snippet name
name="${1}"
snippet rel
rel="${1}"
snippet scope
scope="${1:row}"
snippet src
src="${1}"
snippet title=
title="${1}"
snippet type
type="${1}"
snippet value
value="${1}"
snippet width
width="${1}"
# Elements
snippet a
<a href="${1:#}">${0:$1}</a>
snippet a.
<a class="${1}" href="${2:#}">${0:$1}</a>
snippet a#
<a id="${1}" href="${2:#}">${0:$1}</a>
snippet a:ext
<a href="http://${1:example.com}">${0:$1}</a>
snippet a:mail
<a href="mailto:${1:joe@example.com}?subject=${2:feedback}">${0:email me}</a>
snippet ac
<a href="`@+`">${0:`@+`}</a>
snippet abbr
<abbr title="${1}">${0}</abbr>
snippet address
<address>
${0}
</address>
snippet area
<area shape="${1:rect}" coords="${2}" href="${3}" alt="${0}" />
snippet area+
<area shape="${1:rect}" coords="${2}" href="${3}" alt="${4}" />
area+
snippet area:c
<area shape="circle" coords="${1}" href="${2}" alt="${0}" />
snippet area:d
<area shape="default" coords="${1}" href="${2}" alt="${0}" />
snippet area:p
<area shape="poly" coords="${1}" href="${2}" alt="${0}" />
snippet area:r
<area shape="rect" coords="${1}" href="${2}" alt="${0}" />
snippet article
<article>
${0}
</article>
snippet article.
<article class="${1}">
${0}
</article>
snippet article#
<article id="${1}">
${0}
</article>
snippet aside
<aside>
${0}
</aside>
snippet aside.
<aside class="${1}">
${0}
</aside>
snippet aside#
<aside id="${1}">
${0}
</aside>
snippet audio
<audio src="${1}>${0}</audio>
snippet b
<b>${0}</b>
snippet base
<base href="${1}" target="${0}" />
snippet bdi
<bdi>${0}</bdo>
snippet bdo
<bdo dir="${1}">${0}</bdo>
snippet bdo:l
<bdo dir="ltr">${0}</bdo>
snippet bdo:r
<bdo dir="rtl">${0}</bdo>
snippet blockquote
<blockquote>
${0}
</blockquote>
snippet body
<body>
${0}
</body>
snippet br
<br />
snippet button
<button type="${1:submit}">${0}</button>
snippet button.
<button class="${1:button}" type="${2:submit}">${0}</button>
snippet button#
<button id="${1}" type="${2:submit}">${0}</button>
snippet button:s
<button type="submit">${0}</button>
snippet button:r
<button type="reset">${0}</button>
snippet canvas
<canvas>
${0}
</canvas>
snippet caption
<caption>${0}</caption>
snippet cite
<cite>${0}</cite>
snippet code
<code>${0}</code>
snippet col
<col />
snippet col+
<col />
col+
snippet colgroup
<colgroup>
${0}
</colgroup>
snippet colgroup+
<colgroup>
<col />
col+${0}
</colgroup>
snippet command
<command type="command" label="${1}" icon="${0}">
snippet command:c
<command type="checkbox" label="${1}" icon="${0}">
snippet command:r
<command type="radio" radiogroup="${1}" label="${2}" icon="${0}">
snippet datagrid
<datagrid>
${0}
</datagrid>
snippet datalist
<datalist>
${0}
</datalist>
snippet datatemplate
<datatemplate>
${0}
</datatemplate>
snippet dd
<dd>${0}</dd>
snippet dd.
<dd class="${1}">${0}</dd>
snippet dd#
<dd id="${1}">${0}</dd>
snippet del
<del>${0}</del>
snippet details
<details>${0}</details>
snippet dfn
<dfn>${0}</dfn>
snippet dialog
<dialog>
${0}
</dialog>
snippet div
<div>
${0}
</div>
snippet div.
<div class="${1}">
${0}
</div>
snippet div#
<div id="${1}">
${0}
</div>
snippet dl
<dl>
${0}
</dl>
snippet dl.
<dl class="${1}">
${0}
</dl>
snippet dl#
<dl id="${1}">
${0}
</dl>
snippet dl+
<dl>
<dt>${1}</dt>
<dd>${2}</dd>
dt+${0}
</dl>
snippet dt
<dt>${0}</dt>
snippet dt.
<dt class="${1}">${0}</dt>
snippet dt#
<dt id="${1}">${0}</dt>
snippet dt+
<dt>${1}</dt>
<dd>${2}</dd>
dt+${0}
snippet em
<em>${0}</em>
snippet embed
<embed src="${1}" type="${0}" />
snippet fieldset
<fieldset>
${0}
</fieldset>
snippet fieldset.
<fieldset class="${1}">
${0}
</fieldset>
snippet fieldset#
<fieldset id="${1}">
${0}
</fieldset>
snippet fieldset+
<fieldset>
<legend><span>${1}</span></legend>
${2}
</fieldset>
fieldset+${0}
snippet figcaption
<figcaption>${0}</figcaption>
snippet figure
<figure>${0}</figure>
snippet figure#
<figure id="${1}">
${0}
</figure>
snippet figure.
<figure class="${1}">
${0}
</figure>
snippet footer
<footer>
${0}
</footer>
snippet footer.
<footer class="${1}">
${0}
</footer>
snippet footer#
<footer id="${1}">
${0}
</footer>
snippet form
<form action="${1}" method="${2:post}">
${0}
</form>
snippet form.
<form class="${1}" action="${2}" method="${3:post}">
${0}
</form>
snippet form#
<form id="${1}" action="${2}" method="${3:post}">
${0}
</form>
snippet h1
<h1>${0}</h1>
snippet h1.
<h1 class="${1}">${0}</h1>
snippet h1#
<h1 id="${1}">${0}</h1>
snippet h2
<h2>${0}</h2>
snippet h2.
<h2 class="${1}">${0}</h2>
snippet h2#
<h2 id="${1}">${0}</h2>
snippet h3
<h3>${0}</h3>
snippet h3.
<h3 class="${1}">${0}</h3>
snippet h3#
<h3 id="${1}">${0}</h3>
snippet h4
<h4>${0}</h4>
snippet h4.
<h4 class="${1}">${0}</h4>
snippet h4#
<h4 id="${1}">${0}</h4>
snippet h5
<h5>${0}</h5>
snippet h5.
<h5 class="${1}">${0}</h5>
snippet h5#
<h5 id="${1}">${0}</h5>
snippet h6
<h6>${0}</h6>
snippet h6.
<h6 class="${1}">${0}</h6>
snippet h6#
<h6 id="${1}">${0}</h6>
snippet head
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>${1:`substitute(vim_snippets#Filename('', 'Page Title'), '^.', '\u&', '')`}</title>
${0}
</head>
snippet header
<header>
${0}
</header>
snippet header.
<header class="${1}">
${0}
</header>
snippet header#
<header id="${1}">
${0}
</header>
snippet hgroup
<hgroup>
${0}
</hgroup>
snippet hgroup.
<hgroup class="${1}>
${0}
</hgroup>
snippet hr
<hr />
snippet html
<html>
${0}
</html>
snippet xhtml
<html xmlns="http://www.w3.org/1999/xhtml">
${0}
</html>
snippet html5
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>${1:`substitute(vim_snippets#Filename('', 'Page Title'), '^.', '\u&', '')`}</title>
${2:link}
</head>
<body>
${0:body}
</body>
</html>
snippet html5l
<!DOCTYPE html>
<html lang="${1:es}">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>${2:`substitute(vim_snippets#Filename('', 'Page Title'), '^.', '\u&', '')`}</title>
${3:link}
</head>
<body>
${0:body}
</body>
</html>
snippet i
<i>${0}</i>
snippet iframe
<iframe src="${1}" frameborder="0"></iframe>
snippet iframe.
<iframe class="${1}" src="${2}" frameborder="0"></iframe>
snippet iframe#
<iframe id="${1}" src="${2}" frameborder="0"></iframe>
snippet img
<img src="${1}" alt="${2}" />
snippet img.
<img class="${1}" src="${2}" alt="${3}" />
snippet img#
<img id="${1}" src="${2}" alt="${3}" />
snippet input
<input type="${1:text/submit/hidden/button/image}" name="${2}" id="${3:$2}" value="${4}" />
snippet input.
<input class="${1}" type="${2:text/submit/hidden/button/image}" name="${3}" id="${4:$3}" value="${5}" />
snippet input:text
<input type="text" name="${1}" id="${2:$1}" value="${3}" />
snippet input:submit
<input type="submit" name="${1}" id="${2:$1}" value="${3}" />
snippet input:hidden
<input type="hidden" name="${1}" id="${2:$1}" value="${3}" />
snippet input:button
<input type="button" name="${1}" id="${2:$1}" value="${3}" />
snippet input:image
<input type="image" name="${1}" id="${2:$1}" src="${3}" alt="${4}" />
snippet input:checkbox
<input type="checkbox" name="${1}" id="${2:$1}" />
snippet input:radio
<input type="radio" name="${1}" id="${2:$1}" />
snippet input:color
<input type="color" name="${1}" id="${2:$1}" value="${3}" />
snippet input:date
<input type="date" name="${1}" id="${2:$1}" value="${3}" />
snippet input:datetime
<input type="datetime" name="${1}" id="${2:$1}" value="${3}" />
snippet input:datetime-local
<input type="datetime-local" name="${1}" id="${2:$1}" value="${3}" />
snippet input:email
<input type="email" name="${1}" id="${2:$1}" value="${3}" />
snippet input:file
<input type="file" name="${1}" id="${2:$1}" value="${3}" />
snippet input:month
<input type="month" name="${1}" id="${2:$1}" value="${3}" />
snippet input:number
<input type="number" name="${1}" id="${2:$1}" value="${3}" />
snippet input:password
<input type="password" name="${1}" id="${2:$1}" value="${3}" />
snippet input:range
<input type="range" name="${1}" id="${2:$1}" value="${3}" />
snippet input:reset
<input type="reset" name="${1}" id="${2:$1}" value="${3}" />
snippet input:search
<input type="search" name="${1}" id="${2:$1}" value="${3}" />
snippet input:time
<input type="time" name="${1}" id="${2:$1}" value="${3}" />
snippet input:url
<input type="url" name="${1}" id="${2:$1}" value="${3}" />
snippet input:week
<input type="week" name="${1}" id="${2:$1}" value="${3}" />
snippet ins
<ins>${0}</ins>
snippet kbd
<kbd>${0}</kbd>
snippet label
<label for="${0:$1}">${1}</label>
snippet label:i
<label for="${2:$1}">${1}</label>
<input type="${3:text/submit/hidden/button}" name="${4:$2}" id="${5:$2}" value="${6}" />
snippet label:s
<label for="${2:$1}">${1}</label>
<select name="${3:$2}" id="${4:$2}">
<option value="${5}">${0:$5}</option>
</select>
snippet legend
<legend>${0}</legend>
snippet legend+
<legend><span>${0}</span></legend>
snippet li
<li>${0}</li>
snippet li.
<li class="${1}">${0}</li>
snippet li+
<li>${1}</li>
li+
snippet lia
<li><a href="${0:#}">${1}</a></li>
snippet lia+
<li><a href="${2:#}">${1}</a></li>
lia+
snippet link
<link rel="${1}" href="${2}" title="${3}" type="${4}" />
snippet link:atom
<link rel="alternate" href="${1:atom.xml}" title="Atom" type="application/atom+xml" />
snippet link:s
<link rel="stylesheet" href="${1:style.css}" />
snippet link:css
<link rel="stylesheet" href="${1:style.css}" type="text/css" media="${2:all}" />
snippet link:favicon
<link rel="shortcut icon" href="${1:favicon.ico}" type="image/x-icon" />
snippet link:rss
<link rel="alternate" href="${1:rss.xml}" title="RSS" type="application/atom+xml" />
snippet link:touch
<link rel="apple-touch-icon" href="${1:favicon.png}" />
snippet main
<main role="main">
${0}
</main>
snippet map
<map name="${1}">
${0}
</map>
snippet map.
<map class="${1}" name="${2}">
${0}
</map>
snippet map#
<map name="${1}" id="${2:$1}>
${0}
</map>
snippet map+
<map name="${1}">
<area shape="${2}" coords="${3}" href="${4}" alt="${5}" />${6}
</map>
snippet mark
<mark>${0}</mark>
snippet menu
<menu>
${0}
</menu>
snippet menu:c
<menu type="context">
${0}
</menu>
snippet menu:t
<menu type="toolbar">
${0}
</menu>
snippet meta
<meta http-equiv="${1}" content="${2}" />
snippet meta:s
<meta ${0} />
snippet meta:d
<meta name="description" content="${0}" />
snippet meta:compat
<meta http-equiv="X-UA-Compatible" content="IE=${1:7,8,edge}" />
snippet meta:refresh
<meta http-equiv="refresh" content="text/html;charset=UTF-8" />
snippet meta:utf
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
snippet meter
<meter>${0}</meter>
snippet nav
<nav>
${0}
</nav>
snippet nav.
<nav class="${1}">
${0}
</nav>
snippet nav#
<nav id="${1}">
${0}
</nav>
snippet noscript
<noscript>
${0}
</noscript>
snippet object
<object data="${1}" type="${2}">
${3}
</object>
# Embed QT Movie
snippet movie
<object width="$2" height="$3" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="$1" />
<param name="controller" value="$4" />
<param name="autoplay" value="$5" />
<embed src="${1:movie.mov}"
width="${2:320}" height="${3:240}"
controller="${4:true}" autoplay="${5:true}"
scale="tofit" cache="true"
pluginspage="http://www.apple.com/quicktime/download/" />
</object>
snippet ol
<ol>
${0}
</ol>
snippet ol.
<ol class="${1}">
${0}
</ol>
snippet ol#
<ol id="${1}">
${0}
</ol>
snippet ol+
<ol>
<li>${1}</li>
li+${0}
</ol>
snippet opt
<option value="${1}">${0:$1}</option>
snippet opt+
<option value="${1}">${2:$1}</option>
opt+${0}
snippet optt
<option>${0}</option>
snippet optgroup
<optgroup>
<option value="${1}">${2:$1}</option>
opt+${0}
</optgroup>
snippet output
<output>${0}</output>
snippet p
<p>${0}</p>
snippet p.
<p class="${1}">${0}</p>
snippet p#
<p id="${1}">${0}</p>
snippet param
<param name="${1}" value="${2}" />
snippet pre
<pre>
${0}
</pre>
snippet progress
<progress>${0}</progress>
snippet q
<q>${0}</q>
snippet rp
<rp>${0}</rp>
snippet rt
<rt>${0}</rt>
snippet ruby
<ruby>
<rp><rt>${0}</rt></rp>
</ruby>
snippet s
<s>${0}</s>
snippet samp
<samp>
${0}
</samp>
snippet script
<script type="text/javascript" charset="utf-8">
${0}
</script>
snippet scripts
<script src="${0}.js"></script>
snippet scriptt
<script type="${1}" id="${2}">
${0}
</script>
snippet scriptsrc
<script src="${0}.js" type="text/javascript" charset="utf-8"></script>
snippet section
<section>
${0}
</section>
snippet section.
<section class="${1}">
${0}
</section>
snippet section#
<section id="${1}">
${0}
</section>
snippet select
<select name="${1}" id="${2:$1}">
${0}
</select>
snippet select.
<select name="${1}" id="${2:$1}" class="${3}>
${0}
</select>
snippet select+
<select name="${1}" id="${2:$1}">
<option value="${3}">${4:$3}</option>
opt+${0}
</select>
snippet small
<small>${0}</small>
snippet source
<source src="${1}" type="${2}" media="${0}" />
snippet span
<span>${0}</span>
snippet span.
<span class="${1}">${0}</span>
snippet span#
<span id="${1}">${0}</span>
snippet strong
<strong>${0}</strong>
snippet style
<style type="text/css" media="${1:all}">
${0}
</style>
snippet sub
<sub>${0}</sub>
snippet summary
<summary>
${0}
</summary>
snippet sup
<sup>${0}</sup>
snippet table
<table>
${0}
</table>
snippet table.
<table class="${1}">
${0}
</table>
snippet table#
<table id="${1}">
${0}
</table>
snippet tbody
<tbody>
${0}
</tbody>
snippet td
<td>${0}</td>
snippet td.
<td class="${1}">${0}</td>
snippet td#
<td id="${1}">${0}</td>
snippet td+
<td>${1}</td>
td+${0}
snippet textarea
<textarea name="${1}" id="${2:$1}" rows="${3:8}" cols="${4:40}">${5}</textarea>
snippet tfoot
<tfoot>
${0}
</tfoot>
snippet th
<th>${0}</th>
snippet th.
<th class="${1}">${0}</th>
snippet th#
<th id="${1}">${0}</th>
snippet th+
<th>${1}</th>
th+${0}
snippet thead
<thead>
${0}
</thead>
snippet time
<time datetime="${1}" pubdate="${2:$1}">${0:$1}</time>
snippet title
<title>${0:`substitute(vim_snippets#Filename('', 'Page Title'), '^.', '\u&', '')`}</title>
snippet tr
<tr>
${0}
</tr>
snippet tr+
<tr>
<td>${1}</td>
td+${0}
</tr>
snippet track
<track src="${1}" srclang="${2}" label="${3}" default="${4:default} />${5}
snippet ul
<ul>
${0}
</ul>
snippet ul.
<ul class="${1}">
${0}
</ul>
snippet ul#
<ul id="${1}">
${0}
</ul>
snippet ul+
<ul>
<li>${1}</li>
li+${0}
</ul>
snippet var
<var>${0}</var>
snippet video
<video src="${1} height="${2}" width="${3}" preload="${5:none}" autoplay="${6:autoplay}>${7}</video>
snippet wbr
<wbr />

View File

@ -0,0 +1,106 @@
snippet setup
void setup()
{
${0}
Serial.begin(9600);
}
snippet loop
void loop()
{
${0}
}
snippet inc
#include <${1}.h>
# if
snippet if
if (${1:/* condition */}) {
${2}
}
# else
snippet el
else {
${1}
}
# else if
snippet elif
else if (${1:/* condition */}) {
${2}
}
# ifi
snippet ifi
if (${1:/* condition */}) ${2};
# switch
snippet switch
switch (${1:/* variable */}) {
case ${2:/* variable case */}:
${3}
${4:break;}${5}
default:
${6}
}
snippet case
case ${1:/* variable case */}:
${2}
${3:break;}
# for
snippet for
for (${2:i} = 0; $2 < ${1:count}; $2${3:++}) {
${4}
}
# for (custom)
snippet forr
for (${1:i} = ${2:0}; ${3:$1 < 10}; $1${4:++}) {
${5}
}
# while
snippet wh
while (${1:/* condition */}) {
${2}
}
# do... while
snippet do
do {
${2}
} while (${1:/* condition */});
##
## Functions
# function definition
snippet fun
${1:void} ${2:function_name}(${3})
{
${4}
}
## IO
# pinMode OUTPUT
snippet pinout
pinMode(${1}, OUTPUT);
# pinMode INPUT
snippet pinin
pinMode(${1}, INPUT);
# digitalWrite HIGH
snippet dwHigh
digitalWrite(${1}, HIGH);
# digitalWrite LOW
snippet dwLow
digitalWrite(${1}, LOW);
# digitalRead
snippet dr
digitalRead(${1});
# serialRead
snippet sr
serialRead();
# serial.println
snippet sp
serial.println(${1});
# delay
snippet dl
delay(${1});

View File

@ -0,0 +1,287 @@
## Access Modifiers
snippet po
protected ${0}
snippet pu
public ${0}
snippet pr
private ${0}
##
## Annotations
snippet before
@Before
static void ${1:intercept}(${2:args}) { ${0} }
snippet mm
@ManyToMany
${0}
snippet mo
@ManyToOne
${0}
snippet om
@OneToMany${1:(cascade=CascadeType.ALL)}
${0}
snippet oo
@OneToOne
${1}
##
## Basic Java packages and import
snippet im
import ${0}
snippet j.b
java.beans.
snippet j.i
java.io.
snippet j.m
java.math.
snippet j.n
java.net.
snippet j.u
java.util.
##
## Class
snippet cl
class ${1:`vim_snippets#Filename("$1", "untitled")`} ${0}
snippet pcl
public class ${1:`vim_snippets#Filename("$1", "untitled")`} ${0}
snippet in
interface ${1:`vim_snippets#Filename("$1", "untitled")`} ${2:extends Parent}
snippet tc
public class ${1:`vim_snippets#Filename("$1")`} extends ${0:TestCase}
##
## Class Enhancements
snippet ext
extends ${0}
snippet imp
implements ${0}
##
## Comments
snippet /*
/*
* ${0}
*/
##
## Constants
snippet co
static public final ${1:String} ${2:var} = ${3};
snippet cos
static public final String ${1:var} = "${2}";
##
## Control Statements
snippet case
case ${1}:
${0}
snippet def
default:
${0}
snippet el
else
snippet eif
else if (${1}) ${0}
snippet if
if (${1}) ${0}
snippet sw
switch (${1}) {
${0}
}
##
## Create a Method
snippet m
${1:void} ${2:method}(${3}) ${4:throws }
##
## Create a Variable
snippet v
${1:String} ${2:var}${3: = null}${4};
##
## Declaration for ArrayList
snippet d.al
List<${1:Object}> ${2:list} = new ArrayList<$1>();${0}
## Declaration for HashMap
snippet d.hm
Map<${1:Object}, ${2:Object}> ${3:map} = new HashMap<$1, $2>();${0}
## Declaration for HashSet
snippet d.hs
Set<${1:Object}> ${2:set} = new HashSet<$1>();${0}
## Declaration for Stack
snippet d.st
Stack<${1:Object}> ${2:stack} = new Stack<$1>();${0}
##
## Singleton Pattern
snippet singlet
private static class Holder {
private static final ${1:`vim_snippets#Filename("$1")`} INSTANCE = new $1();
}
private $1() { }
public static $1 getInstance() {
return Holder.INSTANCE;
}
##
## Enhancements to Methods, variables, classes, etc.
snippet ab
abstract ${0}
snippet fi
final ${0}
snippet st
static ${0}
snippet sy
synchronized ${0}
##
## Error Methods
snippet err
System.err.print("${0:Message}");
snippet errf
System.err.printf("${1:Message}", ${0:exception});
snippet errln
System.err.println("${0:Message}");
##
## Exception Handling
snippet as
assert ${1:test} : "${2:Failure message}";
snippet ae
assertEquals("${1:Failure message}", ${2:expected}, ${3:actual});
snippet aae
assertArrayEquals("${1:Failure message}", ${2:expecteds}, ${3:actuals});
snippet af
assertFalse("${1:Failure message}", ${2:condition});
snippet at
assertTrue("${1:Failure message}", ${2:condition});
snippet an
assertNull("${1:Failure message}", ${2:object});
snippet ann
assertNotNull("${1:Failure message}", ${2:object});
snippet ass
assertSame("${1:Failure message}", ${2:expected}, ${3:actual});
snippet asns
assertNotSame("${1:Failure message}", ${2:expected}, ${3:actual});
snippet fa
fail("${1:Failure message}");
snippet ca
catch(${1:Exception} ${2:e}) ${0}
snippet thr
throw ${0}
snippet ths
throws ${0}
snippet try
try {
${0}
} catch(${1:Exception} ${2:e}) {
}
snippet tryf
try {
${0}
} catch(${1:Exception} ${2:e}) {
} finally {
}
##
## Find Methods
snippet findall
List<${1:listName}> ${2:items} = ${1}.findAll();
snippet findbyid
${1:var} ${2:item} = ${1}.findById(${3});
##
## Javadocs
snippet /**
/**
* ${0}
*/
snippet @au
@author `system("grep \`id -un\` /etc/passwd | cut -d \":\" -f5 | cut -d \",\" -f1")`
snippet @br
@brief ${0:Description}
snippet @fi
@file ${0:`vim_snippets#Filename("$1")`}.java
snippet @pa
@param ${0:param}
snippet @re
@return ${0:param}
##
## Logger Methods
snippet debug
Logger.debug(${1:param});
snippet error
Logger.error(${1:param});
snippet info
Logger.info(${1:param});
snippet warn
Logger.warn(${1:param});
##
## Loops
snippet enfor
for (${1} : ${2}) ${0}
snippet for
for (${1}; ${2}; ${3}) ${0}
snippet wh
while (${1}) ${0}
##
## Main method
snippet main
public static void main (String[] args) {
${0}
}
##
## Print Methods
snippet print
System.out.print("${0:Message}");
snippet printf
System.out.printf("${1:Message}", ${0:args});
snippet println
System.out.println(${0});
snippet printlna
System.out.println(Arrays.toString(${0}));
##
## Render Methods
snippet ren
render(${1:param});
snippet rena
renderArgs.put("${1}", ${2});
snippet renb
renderBinary(${1:param});
snippet renj
renderJSON(${1:param});
snippet renx
renderXml(${1:param});
##
## Setter and Getter Methods
snippet set
${1:public} void set${3:}(${2:String} ${0:}){
this.$4 = $4;
}
snippet get
${1:public} ${2:String} get${3:}(){
return this.${0:};
}
##
## Terminate Methods or Loops
snippet re
return ${0}
snippet br
break;
##
## Test Methods
snippet t
public void test${1:Name}() throws Exception {
${0}
}
snippet test
@Test
public void test${1:Name}() throws Exception {
${0}
}
##
## Utils
snippet Sc
Scanner
##
## Miscellaneous
snippet action
public static void ${1:index}(${2:args}) { ${0} }
snippet rnf
notFound(${1:param});
snippet rnfin
notFoundIfNull(${1:param});
snippet rr
redirect(${1:param});
snippet ru
unauthorized(${1:param});
snippet unless
(unless=${1:param});

View File

@ -0,0 +1,286 @@
# Functions
# prototype
snippet proto
${1:class_name}.prototype.${2:method_name} = function(${3}) {
${0}
};
# Function
snippet fun
function ${1:function_name}(${2}) {
${0}
}
# Anonymous Function
snippet f "" w
function(${1}) {
${0}
}
# Anonymous Function assigned to variable
snippet vaf
var ${1:function_name} = function(${2}) {
${0}
};
# Function assigned to variable
snippet vf
var ${1:function_name} = function $1(${2}) {
${0}
};
# Immediate function
snippet (f
(function(${1}) {
${0}
}(${2}));
# Minify safe iife
snippet ;fe
;(function(${1}) {
${0}
}(${2}))
# self-defining function
snippet sdf
var ${1:function_name} = function (${2:argument}) {
${3}
$1 = function ($2) {
${0}
};
};
# Flow control
# if
snippet if
if (${1:true}) {
${0}
}
# if ... else
snippet ife
if (${1:true}) {
${2}
} else {
${0}
}
# tertiary conditional
snippet ter
${1:/* condition */} ? ${2:/* if true */} : ${0:/* if false */}
# switch
snippet switch
switch (${1:expression}) {
case '${3:case}':
${4}
break;
${0}
default:
${2}
}
# case
snippet case
case '${1:case}':
${2}
break;
${0}
# try
snippet try
try {
${1}
} catch (${2:e}) {
${0:/* handle error */}
}
# try finally
snippet tryf
try {
${1}
} catch (${2:e}) {
${0:/* handle error */}
} finally {
${3:/* be executed regardless of the try / catch result*/}
}
# throw Error
snippet terr
throw new Error('${1:error message}')
# return
snippet ret
return ${0:result};
# Loops
# for loop
snippet for
for (var ${2:i} = 0, l = ${1:arr}.length; $2 < l; $2++) {
var ${3:v} = $1[$2];${0:}
}
# Reversed for loop
snippet forr
for (var ${2:i} = ${1:arr}.length - 1; $2 >= 0; $2--) {
var ${3:v} = $1[$2];${0:}
}
# While loop
snippet wh
while (${1:/* condition */}) {
${0}
}
# Do while loop
snippet do
do {
${0}
} while (${1:/* condition */});
# For in loop
snippet fori
for (var ${1:prop} in ${2:object}) {
${0:$2[$1]}
}
# Objects
# Object Method
snippet :f
${1:method_name}: function (${2:attribute}) {
${3}
},
# hasOwnProperty
snippet has
hasOwnProperty(${0})
# singleton
snippet sing
function ${1:Singleton} (${2:argument}) {
// the cached instance
var instance;
// rewrite the constructor
$1 = function $1($2) {
return instance;
};
// carry over the prototype properties
$1.prototype = this;
// the instance
instance = new $1();
// reset the constructor pointer
instance.constructor = $1;
${0}
return instance;
}
# Crockford's object function
snippet obj
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
# Define multiple properties
snippet props
var ${1:my_object} = Object.defineProperties(
${2:new Object()},
{
${3:property} : {
get : function $1_$3_getter() {
// getter code
},
set : function $1_$3_setter(value) {
// setter code
},
value : ${4:value},
writeable : ${5:boolean},
enumerable : ${6:boolean},
configurable : ${0:boolean}
}
}
);
# Define single property
snippet prop
Object.defineProperty(
${1:object},
'${2:property}',
{
get : function $1_$2_getter() {
// getter code
},
set : function $1_$2_setter(value) {
// setter code
},
value : ${3:value},
writeable : ${4:boolean},
enumerable : ${5:boolean},
configurable : ${0:boolean}
}
);
# Documentation
# docstring
snippet /**
/**
* ${0:description}
*
*/
snippet @par
@param {${1:type}} ${2:name} ${0:description}
snippet @ret
@return {${1:type}} ${0:description}
# JSON
# JSON.parse
snippet jsonp
JSON.parse(${0:jstr});
# JSON.stringify
snippet jsons
JSON.stringify(${0:object});
# DOM selectors
# Get elements
snippet get
getElementsBy${1:TagName}('${0}')
# Get element
snippet gett
getElementBy${1:Id}('${0}')
# Elements by class
snippet by.
${1:document}.getElementsByClassName('${0:class}')
# Element by ID
snippet by#
${1:document}.getElementById('${0:element ID}')
# Query selector
snippet qs
${1:document}.querySelector('${0:CSS selector}')
# Query selector all
snippet qsa
${1:document}.querySelectorAll('${0:CSS selector}')
# Debugging
snippet de
debugger;
# console.log
snippet cl
console.log(${0});
# console.debug
snippet cd
console.debug(${0});
# console.error
snippet ce
console.error(${0});
# console.trace
snippet ct
console.trace(${0:label});
# console.time
snippet ctime
console.time(${0:label});
# console.assert
snippet ca
console.assert(${1:expression}, ${0:obj});
# console.dir
snippet cdir
console.dir(${0:obj});
# Misc
# 'use strict';
snippet us
'use strict';
# setTimeout function
snippet timeout
setTimeout(function () {${0}}${2}, ${1:10});

View File

@ -0,0 +1,5 @@
# Ledger <http://ledger-cli.org/>
snippet ent
`strftime("%Y/%m/%d")` ${1:transaction}
${2:account} ${3:value}
${0:account}

View File

@ -0,0 +1,18 @@
snippet defmo
(defmodule ${1:`vim_snippets#Filename()`}
(export ${2:all}))
$0
snippet def
(defun $1 ($2)
$0)
snippet ltest
(defmodule ${1:`vim_snippets#Filename()`}
(behaviour ltest-unit)
(export all))
(include-lib "ltest/include/ltest-macros.lfe")
$0
snippet test
(deftest $1
$0)

View File

@ -0,0 +1,21 @@
snippet #!
#!/usr/bin/env lua
$1
snippet local
local ${1:x} = ${0:1}
snippet fun
function ${1:fname}(${2:...})
${0:-- body}
end
snippet for
for ${1:i}=${2:1},${3:10} do
${0:print(i)}
end
snippet forp
for ${1:i},${2:v} in pairs(${3:table_name}) do
${0:-- body}
end
snippet fori
for ${1:i},${2:v} in ipairs(${3:table_name}) do
${0:-- body}
end

View File

@ -0,0 +1,50 @@
# base
snippet base
.PHONY: clean, mrproper
CC = gcc
CFLAGS = -g -Wall
all: $1
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
${1:out}: $1.o
$(CC) $(CFLAGS) -o $@ $+
clean:
rm -f *.o core.*
mrproper: clean
rm -f $1
# add
snippet add
${1:out}: $1.o
$(CC) $(CFLAGS) -o $@ $+
# print
snippet print
print-%: ; @echo $*=$($*)
# ifeq
snippet if
ifeq (${1:cond0}, ${2:cond1})
${0}
endif
# ifeq ... else ... endif
snippet ife
ifeq (${1:cond0}, ${2:cond1})
${3}
else
${0}
endif
# else ...
snippet el
else
${0}
# .DEFAULT_GOAL := target
snippet default
.DEFAULT_GOAL := ${1}
# help target for self-documented Makefile
snippet help
help: ## Prints help for targets with comments
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $\$1, $\$2}'
${0}

View File

@ -0,0 +1,139 @@
# Markdown
# Includes octopress (http://octopress.org/) snippets
# The suffix `c` stands for "Clipboard".
snippet [
[${1:text}](http://${2:address})
snippet [*
[${1:link}](${2:`@*`})
snippet [c
[${1:link}](${2:`@+`})
snippet ["
[${1:text}](http://${2:address} "${3:title}")
snippet ["*
[${1:link}](${2:`@*`} "${3:title}")
snippet ["c
[${1:link}](${2:`@+`} "${3:title}")
snippet [:
[${1:id}]: http://${2:url}
snippet [:*
[${1:id}]: ${2:`@*`}
snippet [:c
[${1:id}]: ${2:`@+`}
snippet [:"
[${1:id}]: http://${2:url} "${3:title}"
snippet [:"*
[${1:id}]: ${2:`@*`} "${3:title}"
snippet [:"c
[${1:id}]: ${2:`@+`} "${3:title}"
snippet ![
![${1:alttext}](${2:/images/image.jpg})
snippet ![*
![${1:alt}](${2:`@*`})
snippet ![c
![${1:alt}](${2:`@+`})
snippet !["
![${1:alttext}](${2:/images/image.jpg} "${3:title}")
snippet !["*
![${1:alt}](${2:`@*`} "${3:title}")
snippet !["c
![${1:alt}](${2:`@+`} "${3:title}")
snippet ![:
![${1:id}]: ${2:url}
snippet ![:*
![${1:id}]: ${2:`@*`}
snippet ![:"
![${1:id}]: ${2:url} "${3:title}"
snippet ![:"*
![${1:id}]: ${2:`@*`} "${3:title}"
snippet ![:"c
![${1:id}]: ${2:`@+`} "${3:title}"
snippet <
<http://${1:url}>
snippet <*
<`@*`>
snippet <c
<`@+`>
snippet **
**${1:bold}**
snippet __
__${1:bold}__
snippet ===
`repeat('=', strlen(getline(line(".") - 1)) - strlen(getline('.')))`
${0}
snippet -
- ${0}
snippet ---
`repeat('-', strlen(getline(line(".") - 1)) - strlen(getline('.')))`
${0}
snippet blockquote
{% blockquote %}
${0:quote}
{% endblockquote %}
snippet blockquote-author
{% blockquote ${1:author}, ${2:title} %}
${0:quote}
{% endblockquote %}
snippet blockquote-link
{% blockquote ${1:author} ${2:URL} ${3:link_text} %}
${0:quote}
{% endblockquote %}
snippet ```
\`\`\`
${1:code}
\`\`\`
# Language.
snippet ```l
\`\`\`${1:language}
${2:code}
\`\`\`
snippet codeblock-short
{% codeblock %}
${0:code_snippet}
{% endcodeblock %}
snippet codeblock-full
{% codeblock ${1:title} lang:${2:language} ${3:URL} ${4:link_text} %}
${0:code_snippet}
{% endcodeblock %}
snippet gist-full
{% gist ${1:gist_id} ${0:filename} %}
snippet gist-short
{% gist ${0:gist_id} %}
snippet img
{% img ${1:class} ${2:URL} ${3:width} ${4:height} ${5:title_text} ${0:alt_text} %}
snippet youtube
{% youtube ${0:video_id} %}
# The quote should appear only once in the text. It is inherently part of it.
# See http://octopress.org/docs/plugins/pullquote/ for more info.
snippet pullquote
{% pullquote %}
${1:text} {" ${2:quote} "} ${0:text}
{% endpullquote %}

View File

@ -0,0 +1,363 @@
# #!/usr/bin/perl
snippet #!
#!/usr/bin/env perl
# Hash Pointer
snippet .
=>
# Function
snippet sub
sub ${1:function_name} {
${0}
}
# Conditional
snippet if
if (${1}) {
${0}
}
# Conditional if..else
snippet ife
if (${1}) {
${2}
}
else {
${0}
}
# Conditional if..elsif..else
snippet ifee
if (${1}) {
${2}
}
elsif (${3}) {
${4:# elsif...}
}
else {
${0}
}
snippet eif
elsif (${1}) {
${0}
}
# Conditional One-line
snippet xif
${1:expression} if ${2:condition};
# Unless conditional
snippet unless
unless (${1}) {
${0}
}
# Unless conditional One-line
snippet xunless
${1:expression} unless ${2:condition};
# Try/Except
snippet eval
local $@;
eval {
${1:# do something risky...}
};
if (my $e = $@) {
${0:# handle failure...}
}
# While Loop
snippet wh
while (${1}) {
${0}
}
# While Loop One-line
snippet xwh
${1:expression} while ${2:condition};
# C-style For Loop
snippet cfor
for (my $${2:var} = 0; $$2 < ${1:count}; $$2${3:++}) {
${0}
}
# For loop one-line
snippet xfor
${1:expression} for @${2:array};
# Foreach Loop
snippet for
foreach my $${1:x} (@${2:array}) {
${0}
}
# Foreach Loop One-line
snippet fore
${1:expression} foreach @${2:array};
# Package
snippet package
package ${1:`expand('%:p:s?.*lib/??:r:gs?/?::?')`};
use strict;
use warnings;
${0}
1;
__END__
# Package syntax perl >= 5.14
snippet packagev514
package ${1:`expand('%:p:s?.*lib/??:r:gs?/?::?')`} ${2:0.99};
use v5.14;
use warnings;
${0}
1;
__END__
#moose
snippet moose
use Moose;
use namespace::autoclean;
${1:#}BEGIN {extends '${2:ParentClass}'};
${0}
# parent
snippet parent
use parent qw(${0:Parent Class});
# Read File
snippet slurp
my $${1:var} = do { local $/; open my $file, '<', "${2:file}"; <$file> };
${0}
# strict warnings
snippet strwar
use strict;
use warnings;
# older versioning with perlcritic bypass
snippet vers
## no critic
our $VERSION = '${0:version}';
eval $VERSION;
## use critic
# new 'switch' like feature
snippet switch
use feature 'switch';
# Anonymous subroutine
snippet asub
sub {
${0}
}
# Begin block
snippet begin
BEGIN {
${0}
}
# call package function with some parameter
snippet pkgmv
__PACKAGE__->${1:package_method}(${0:var})
# call package function without a parameter
snippet pkgm
__PACKAGE__->${0:package_method}()
# call package "get_" function without a parameter
snippet pkget
__PACKAGE__->get_${0:package_method}()
# call package function with a parameter
snippet pkgetv
__PACKAGE__->get_${1:package_method}(${0:var})
# complex regex
snippet qrx
qr/
${0:regex}
/xms
#simpler regex
snippet qr/
qr/${0:regex}/x
#given
snippet given
given ($${1:var}) {
${2:# cases}
${0:# default}
}
# switch-like case
snippet when
when (${1:case}) {
${0}
}
# hash slice
snippet hslice
@{ ${1:hash} }{ ${0:array} }
# map
snippet map
map { ${0: body } } ${1: @array } ;
# Pod stub
snippet ppod
=head1 NAME
${1:ClassName} - ${2:ShortDesc}
=head1 SYNOPSIS
use $1;
${3:# synopsis...}
=head1 DESCRIPTION
${0:# longer description...}
=head1 INTERFACE
=head1 DEPENDENCIES
=head1 SEE ALSO
# Heading for a subroutine stub
snippet psub
=head2 ${1:MethodName}
${0:Summary....}
# Heading for inline subroutine pod
snippet psubi
=head2 ${1:MethodName}
${0:Summary...}
=cut
# inline documented subroutine
snippet subpod
=head2 $1
Summary of $1
=cut
sub ${1:subroutine_name} {
${0}
}
# Subroutine signature
snippet parg
=over 2
=item
Arguments
=over 3
=item
C<${1:DataStructure}>
${2:Sample}
=back
=item
Return
=over 3
=item
C<${0:...return data}>
=back
=back
# Moose has
snippet has
has ${1:attribute} => (
is => '${2:ro|rw}',
isa => '${3:Str|Int|HashRef|ArrayRef|etc}',
default => sub {
${4:defaultvalue}
},
${0:# other attributes}
);
# override
snippet override
override ${1:attribute} => sub {
${2:# my $self = shift;};
${0:# my ($self, $args) = @_;};
};
# use test classes
snippet tuse
use Test::More;
use Test::Deep; # (); # uncomment to stop prototype errors
use Test::Exception;
# local test lib
snippet tlib
use lib qw{ ./t/lib };
#test methods
snippet tmeths
$ENV{TEST_METHOD} = '${0:regex}';
# runtestclass
snippet trunner
use ${0:test_class};
$1->runtests();
# Test::Class-style test
snippet tsub
sub t${1:number}_${2:test_case} :Test(${3:num_of_tests}) {
my $self = shift;
${0}
}
# Test::Routine-style test
snippet trsub
test ${1:test_name} => { description => '${2:Description of test.}'} => sub {
my ($self) = @_;
${0}
};
#prep test method
snippet tprep
sub prep${1:number}_${2:test_case} :Test(startup) {
my $self = shift;
${0}
}
# cause failures to print stack trace
snippet debug_trace
use Carp; # 'verbose';
# cloak "die"
# warn "warning"
$SIG{'__DIE__'} = sub {
require Carp; Carp::confess
};
snippet dump
use Data::Dump qw(dump);
warn dump ${1:variable}
snippet subtest
subtest '${1: test_name}' => sub {
${2}
};

View File

@ -0,0 +1,116 @@
# shebang
snippet #!
#!/usr/bin/env perl6
# Hash Pointer
snippet .
=>
# Function
snippet sub
sub ${1:function_name}(${2:Str $var}) {
${3}
}
snippet mul
multi ${1:function_name}(${2:Str $var}) {
${3}
}
# Conditional
snippet if
if ${1} {
${2}
}
# Conditional if..else
snippet ife
if ${1} {
${2}
}
else {
${3}
}
snippet eif
elsif ${1) {
${2}
}
# Conditional One-line
snippet xif
${1:expression} if ${2:condition};
# Unless conditional
snippet unless
unless ${1} {
${2}
}
# Unless conditional One-line
snippet xunless
${1:expression} unless ${2:condition};
# Ternary conditional
snippet tc
${1:condition} ?? ${2:value-if-true} !! ${3:value-if-false};
# given - when (perl6 switch)
snippet switch
given ${1:$var} {
when ${2:condition} {
${3:# code block ...}
}
${4}
default {
${5}
}
}
# 'loop' - C's for.
snippet loop
loop (my ${1:$i} = 0; $$1 < ${2:count}; $$1++) {
${3}
}
# for loop
snippet for
for ${1:@array} -> ${2:$variable} {
${3}
}
# While Loop
snippet wh
while ${1} {
${2}
}
# Repeat while and repean until
snippet rp
repeat {
${1}
} ${2:while|until} ${3};
# classes ..
snippet cl
${1:my} class ${2:ClassName} ${3:is|does Parent|Role}{
${4}
}
snippet has
has ${1:Type} ${2:$!identifier};
snippet mth
method ${1:method_name}(${2:$attr}) {
${3}
}
snippet pmth
method ${1:!}${2:method_name}(${3:$attr}) {
${4}
}
snippet smth
submethod ${1:submethod_name}(${2:$attr}) {
${3}
}
# Tests
snippet test
use v6;
use Test;
${1:use lib 'lib';}
plan ${2:$num-tests};
# IO
snippet slurp
my ${1:$var} = "${2:filename}".IO.slurp;
snippet rfile
for "${1:filename}".IO.lines -> $line {
${2}
}
snippet open
my $fh = open "${1:filename}", ${2::r|:w|:a};
${3:# actions};
$fh.close;

View File

@ -0,0 +1,663 @@
snippet <?
<?php
${0}
snippet dst "declare(strict_types=1)"
declare(strict_types=${1:1});
snippet ec
echo ${0};
snippet <?e
<?php echo ${0} ?>
# this one is for php5.4
snippet <?=
<?=${0}?>
snippet ?=
<?= ${0} ?>
snippet ?
<?php ${0} ?>
snippet ?f
<?php foreach ($${1:vars} as $${2:$var}): ?>
${0}
<?php endforeach ?>
snippet ?i
<?php if ($${1:var}): ?>
${0}
<?php endif ?>
snippet ns
namespace ${1:Foo\Bar\Baz};
${0}
snippet c
class ${1:`vim_snippets#Filename()`}
{
${0}
}
snippet i
interface ${1:`vim_snippets#Filename()`}
{
${0}
}
snippet t.
$this->
snippet f
function ${1}(${3})
{
${0}
}
# method
snippet m
${1:protected} function ${2:foo}()
{
${0}
}
snippet sm "PHP Class Setter"
/**
* Sets the value of ${1:foo}
*
* @param ${2:string} $$1 ${3:description}
*
* @return ${4:`vim_snippets#Filename()`}
*/
${5:public} function set${6:$1}(${7:$2 }$$1)
{
$this->${8:$1} = $$1;
return $this;
}
snippet gm "PHP Class Getter Setter"
/**
* Gets the value of ${1:foo}
*
* @return ${2:string}
*/
${3:public} function get${4:$1}()
{
return $this->${5:$1};
}
#setter
snippet $s
${1:$foo}->set${2:Bar}(${0});
#getter
snippet $g
${1:$foo}->get${0:Bar}();
# Tertiary conditional
snippet =?:
$${1:foo} = ${2:true} ? ${3:a} : ${0};
snippet ?:
${1:true} ? ${2:a} : ${0}
snippet t "$retVal = (condition) ? a : b"
$${1:retVal} = (${2:condition}) ? ${3:a} : ${4:b};
# Predefined variables
snippet C
$_COOKIE['${1:variable}']
snippet E
$_ENV['${1:variable}']
snippet F
$_FILES['${1:variable}']
snippet G
$_GET['${1:variable}']
snippet P
$_POST['${1:variable}']
snippet R
$_REQUEST['${1:variable}']
snippet S
$_SERVER['${1:variable}']
snippet SS
$_SESSION['${1:variable}']
snippet get "get"
$_GET['${1}']
snippet post "post"
$_POST['${1}']
snippet session "session"
$_SESSION['${1}']
# the following are old ones
snippet inc
include '${1:file}';
snippet inc1
include_once '${1:file}';
snippet req
require '${1:file}';
snippet req1
require_once '${1:file}';
# Start Docblock
snippet /*
/**
* ${0}
*/
# Class - post doc
snippet doc_cp
/**
* ${1:undocumented class}
*
* @package ${2:default}
* @subpackage ${3:default}
* @author ${4:`g:snips_author`}
*/
# Class Variable - post doc
snippet doc_vp
/**
* ${1:undocumented class variable}
*
* @var ${2:string}
*/
# Class Variable
snippet doc_v
/**
* ${3:undocumented class variable}
*
* @var ${4:string}
*/
${1:var} $${2};
# Class
snippet doc_c
/**
* ${3:undocumented class}
*
* @package ${4:default}
* @subpackage ${5:default}
* @author ${6:`g:snips_author`}
*/
${1:}class ${2:}
{
${0}
} // END $1class $2
# Constant Definition - post doc
snippet doc_dp
/**
* ${1:undocumented constant}
*/
# Constant Definition
snippet doc_d
/**
* ${3:undocumented constant}
*/
define(${1}, ${2});
# Function - post doc
snippet doc_fp
/**
* ${1:undocumented function}
*
* @return ${2:void}
* @author ${3:`g:snips_author`}
*/
# Function signature
snippet doc_s
/**
* ${4:undocumented function}
*
* @return ${5:void}
* @author ${6:`g:snips_author`}
*/
${1}function ${2}(${3});
# Function
snippet doc_f
/**
* ${4:undocumented function}
*
* @return ${5:void}
* @author ${6:`g:snips_author`}
*/
${1}function ${2}(${3})
{${0}
}
# Header
snippet doc_h
/**
* ${1}
*
* @author ${2:`g:snips_author`}
* @version ${3:$Id$}
* @copyright ${4:$2}, `strftime('%d %B, %Y')`
* @package ${0:default}
*/
snippet doc_i "interface someClass {}"
/**
* $1
* @package ${2:default}
* @author ${3:`!v g:snips_author`}
**/
interface ${1:someClass}
{${4}
}
snippet inheritdoc "@inheritdoc docblock"
/**
* {@inheritdoc}
*/
# Interface
snippet interface
/**
* ${2:undocumented class}
*
* @package ${3:default}
* @author ${4:`g:snips_author`}
*/
interface ${1:`vim_snippets#Filename()`}
{
${0}
}
# Trait
snippet trait
/**
* ${2:undocumented class}
*
* @package ${3:default}
* @author ${4:`g:snips_author`}
*/
trait ${1:`vim_snippets#Filename()`}
{
${0}
}
# class ...
snippet class
/**
* ${1}
*/
class ${2:`vim_snippets#Filename()`}
{
${3}
/**
* ${4}
*/
${5:public} function ${6:__construct}(${7:argument})
{
${0}
}
}
snippet nc
namespace ${1:`substitute(substitute(expand("%:h"), '\v^\w+\/(\u)', '\1', ''), '\/', '\\\', 'g')`};
${2:abstract }class ${3:`vim_snippets#Filename()`}
{
${0}
}
# define(...)
snippet def "define('VARIABLE_NAME', 'definition')"
define('${1:VARIABLE_NAME}', ${2:'definition'});
# defined(...)
snippet def?
${1}defined('${2}')
snippet wh "while (condition) { ... }"
while (${1:/* condition */}) {
${0}
}
snippet do "do { ... } while (condition)"
do {
${0}
} while (${1});
snippet if "if (condition) { ... }"
if (${1}) {
${0}
}
snippet ifn "if (!condition) { ... }"
if (!${1}) {
${2}
}
snippet ifil "<?php if (condition): ?> ... <?php endif; ?>"
<?php if (${1}): ?>
${0}
<?php endif; ?>
snippet ife "if (cond) { ... } else { ... }"
if (${1}) {
${2}
} else {
${3}
}
${0}
snippet ifeil "<?php if (condition): ?> ... <?php else: ?> ... <?php endif; ?>"
<?php if (${1}): ?>
${2}
<?php else: ?>
${3}
<?php endif; ?>
${0}
snippet el "else { ... }"
else {
${0}
}
snippet eif "elseif(condition) { ... }"
elseif (${1}) {
${0}
}
snippet switch "switch($var) { case 'xyz': ... default: .... }"
switch ($${1:variable}) {
case '${2:value}':
${3}
break;
${0}
default:
${4}
break;
}
snippet case "case 'value': ... break"
case '${1:value}':
${2}
break;
snippet for "for ($i = 0; $i < $count; $i++) { ... }"
for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) {
${0}
}
snippet foreach "foreach ($var as $value) { .. }"
foreach ($${1:variable} as $${2:value}) {
${0}
}
snippet foreachil "<?php foreach ($var as $value): ?> ... <?php endforeach; ?>"
<?php foreach ($${1:variable} as $${2:value}): ?>
${0}
<?php endforeach; ?>
snippet foreachk "foreach ($var as $key => $value) { .. }"
foreach ($${1:variable} as $${2:key} => $${3:value}) {
${0}
}
snippet foreachkil "<?php foreach ($var as $key => $value): ?> ... <?php endforeach; ?>"
<?php foreach ($${1:variable} as $${2:key} => $${3:value}): ?>
${0:<!-- html... -->}
<?php endforeach; ?>
snippet array "$... = array(...)"
$${1:arrayName} = array('${2}' => ${3});
snippet try "try { ... } catch (Exception $e) { ... }"
try {
${0}
} catch (${1:Exception} $e) {
}
# lambda with closure
snippet lambda
${1:static }function (${2:args}) use (${3:&$x, $y /*put vars in scope (closure) */}) {
${0}
};
# pre_dump();
snippet pd
echo '<pre>'; var_dump(${0}); echo '</pre>';
# pre_dump(); die();
snippet pdd
echo '<pre>'; var_dump(${1}); echo '</pre>'; die(${0:});
snippet vd
var_dump(${0});
snippet vdd
var_dump(${1}); die(${0:});
snippet pr
print_r(${0});
snippet prs
print_r(${0}, 1);
snippet vdf
error_log(print_r($${1:foo}, true), 3, '${2:/tmp/debug.log}');
snippet http_redirect
header ("HTTP/1.1 301 Moved Permanently");
header ("Location: ".URL);
exit();
snippet log "error_log(var_export($var, true));"
error_log(var_export(${1}, true));
snippet var "var_export($var)"
var_export(${1});
snippet ve "Dumb debug helper in HTML"
echo '<pre>' . var_export(${1}, 1) . '</pre>';
snippet pc "Dumb debug helper in cli"
var_export($1);$0
# Getters & Setters
snippet gs "PHP Class Getter Setter"
/**
* Gets the value of ${1:foo}
*
* @return ${2:string}
*/
public function get${3:$1}()
{
return $this->${4:$1};
}
/**
* Sets the value of $1
*
* @param $2 $$1 ${5:description}
*
* @return ${6:`vim_snippets#Filename()`}
*/
public function set$3(${7:$2 }$$1)
{
$this->$4 = $$1;
return $this;
}
# anotation, get, and set, useful for doctrine
snippet ags
/**
* ${1:description}
*
* @${0}
*/
${2:protected} $${3:foo};
public function get${4:$3}()
{
return $this->$3;
}
public function set$4(${5:$4 }$${6:$3})
{
$this->$3 = $$6;
return $this;
}
snippet rett
return true;
snippet retf
return false;
snippet am
$${1:foo} = array_map(function($${2:v}) {
${0}
return $$2;
}, $$1);
snippet aw
array_walk($${1:foo}, function(&$${2:v}, $${3:k}) {
$$2 = ${0};
});
# static var assign once
snippet static_var
static $${1} = null;
if (is_null($$1)){
$$1 = ${2};
}
snippet CSVWriter
<?php
class CSVWriter {
public function __construct($file_or_handle, $sep = "\t", $quot = '"'){
$args = func_get_args();
$mode = isset($opts['mode']) ? $opts['mode'] : 'w';
$this->f =
is_string($file_or_handle)
? fopen($file_or_handle, $mode)
: $file_or_handle;
$this->fputcsv_args = array($this->f, null, $sep, $quot);
if (!$this->f) throw new Exception('bad file descriptor');
}
public function write($row){
$this->fputcsv_args[1] =& $row;
call_user_func_array('fputcsv', $this->fputcsv_args);
}
public function close(){
if (!is_null($this->f))
fclose($this->f);
$this->f = null;
}
public function __destruct(){
$this->close();
}
}
snippet CSVIterator
// http://snipplr.com/view.php?codeview&id=1986 // modified
class CSVIterator implements Iterator
{
private $f;
private $curr;
private $rowCounter;
/* opts keys:
* row_size
* escape
* enclosure
* delimiter
*/
public function __construct( $file_or_handle, $opts = array(4096, ',') )
{
$d = function($n) use(&$opts){ return isset($opts[$n]) ? $opts[$n] : false; };
$this->combine = $d('combine');
$this->headers = $d('headers');
$this->headerCheckFunction = $d('header_check_function');
$this->f =
is_string($file_or_handle)
? fopen( $file_or_handle, 'r' )
: $file_or_handle;
if (!$this->f) throw new Exception('bad file descriptor');
$this->fgetcsv_args = array(
$this->f,
isset($opts['row_size']) ? $opts['row_size'] : 4096,
isset($opts['delimiter']) ? $opts['delimiter'] : ',',
isset($opts['enclosure']) ? $opts['enclosure'] : '"',
isset($opts['escape']) ? $opts['escape'] : '\\',
);
$this->start();
}
protected function readRow(){
$this->curr = call_user_func_array('fgetcsv', $this->fgetcsv_args );
$this->rowCounter++;
if ($this->rowCounter == 1){
$this->processHeader();
} elseif ($this->curr) {
$this->processRow();
}
}
public function processHeader(){
if ($this->headers || $this->combine){
$this->header = $this->curr;
if ($this->headerCheckFunction){
$f = $this->headerCheckFunction;
$f($this->header);
}
$this->readRow();
}
}
public function processRow(){
if ($this->combine)
$this->curr = array_combine($this->header, $this->curr);
}
public function start(){
$this->rowCounter = 0;
rewind( $this->f );
$this->readRow();
}
public function rewind()
{
$this->start();
}
public function current()
{
$curr = $this->curr;
$this->readRow();
return $curr;
}
public function key()
{
return $this->rowCounter;
}
public function next()
{
return $this->curr;
}
public function valid(){
if( !$this->next() )
{
fclose( $this->f );
return FALSE;
}
return TRUE;
}
} // end class
# phpunit
snippet ase "$this->assertEquals()"
$this->assertEquals(${1:expected}, ${2:actual});
snippet asne "$this->assertNotEquals()"
$this->assertNotEquals(${1:expected}, ${2:actual});
snippet asf "$this->assertFalse()"
$this->assertFalse(${1});
snippet ast "$this->assertTrue()"
$this->assertTrue(${1});
snippet asfex "$this->assertFileExists()"
$this->assertFileExists(${1:'path/to/file'});
snippet asfnex "$this->assertFileNotExists()"
$this->assertFileNotExists(${1:'path/to/file'});
snippet ascon "$this->assertContains()"
$this->assertContains(${1:$needle}, ${2:$haystack});
snippet ashk "$this->assertArrayHasKey()"
$this->assertArrayHasKey(${1:$key}, ${2:$array});
snippet asnhk "$this->assertArrayNotHasKey()"
this->assertArrayNotHasKey(${1:$key}, ${2:$array});
snippet ascha "$this->assertClassHasAttribute()"
$this->assertClassHasAttribute(${1:$attributeName}, '${2:$className}');
snippet asi "$this->assertInstanceOf(...)"
$this->assertInstanceOf(${1:expected}, ${2:actual});
snippet test "public function testXYZ() { ... }"
public function test${1}()
{
${0}
}
snippet setup "protected function setUp() { ... }"
protected function setUp()
{
${0}
}
snippet teardown "protected function tearDown() { ... }"
protected function tearDown()
{
${0}
}
snippet exp "phpunit expects"
expects($this->${1:once}())
->method('${2}')
->with($this->equalTo(${3})${4})
->will($this->returnValue(${5}));
snippet testcmt "phpunit comment with group"
/**
* @group ${1}
*/
snippet fail "$this->fail()"
$this->fail(${1});
snippet marki "$this->markTestIncomplete()"
$this->markTestIncomplete(${1});
snippet marks "$this->markTestSkipped()"
$this->markTestSkipped(${1});
# end of phpunit snippets
snippet te "throw new Exception()"
throw new ${1:Exception}("${2:Error Processing Request}");
snippet fpc "file_put_contents" b
file_put_contents(${1:file}, ${2:content}${3:, FILE_APPEND});$0
snippet sr "str_replace"
str_replace(${1:search}, ${2:replace}, ${3:subject})$0
snippet ia "in_array"
in_array(${1:needle}, ${2:haystack})$0
snippet is "isset"
isset(${1:var})$0
snippet isa "isset array"
isset($${1:array}[${2:key}])$0
snippet in "is_null"
is_null($${1:var})$0
snippet fe "file_exists"
file_exists(${1:file})$0
snippet id "is_dir"
is_dir(${1:path})$0

View File

@ -0,0 +1,5 @@
snippet msg
msgid "${1}"
msgstr "${2}"
${0}

View File

@ -0,0 +1,269 @@
# Snippets for use with VIM and http://www.vim.org/scripts/script.php?script_id=2540
#
# Please contact R.I.Pienaar <rip@devco.net> for additions and feedback,
# see it in action @ http://www.devco.net/archives/2009/09/22/vim_and_puppet.php
# Header to match http://docs.puppetlabs.com/guides/style_guide.html#puppet-doc
snippet classheader
# == Class: ${1:`vim_snippets#Filename(expand('%:p:s?.*modules/??:h:h'), 'name')`}
#
# ${2:Full description of class $1 here}
#
# === Parameters
#
# Document parameters here.
#
# [*parameter1*]
# Explanation of what this parameter affects and what it defaults to.
# e.g. "Specify one or more upstream ntp servers as an array."
#
# === Variables
#
# Here you should define a list of variables that this module would require.
#
# [*variable1*]
# Explanation of how this variable affects the funtion of this class and
# if it has a default. e.g. "The parameter enc_ntp_servers must be set by the
# External Node Classifier as a comma separated list of hostnames."
#
# === Examples
#
# class { '$1':
# parameter1 => [ 'just', 'an', 'example', ]
# }
#
# === Authors
#
# `g:snips_author` <`g:snips_email`>
#
# === Copyright
#
# Copyright `strftime("%Y")` `g:snips_author`
#
class $1 (${3}){
${4}
}
snippet defheader
# == Define: ${1:`vim_snippets#Filename(expand('%:p:s?.*modules/??:r:s?/manifests/?::?'), 'name')`}
#
# ${2:Full description of defined resource type $1 here}
#
# === Parameters
#
# Document parameters here
#
# [*namevar*]
# If there is a parameter that defaults to the value of the title string
# when not explicitly set, you must always say so. This parameter can be
# referred to as a "namevar," since it's functionally equivalent to the
# namevar of a core resource type.
#
# [*basedir*]
# Description of this variable. For example, "This parameter sets the
# base directory for this resource type. It should not contain a trailing
# slash."
#
# === Examples
#
# Provide some examples on how to use this type:
#
# $1 { 'namevar':
# basedir => '/tmp/src',
# }
#
# === Authors
#
# `g:snips_author` <`g:snips_email`>
#
# === Copyright
#
# Copyright `strftime("%Y")` `g:snips_author`
#
define $1(${3}) {
${4}
}
# Language Constructs
snippet class
class ${1:`vim_snippets#Filename('', 'name')`} {
${0}
}
snippet node
node "${1:`vim_snippets#Filename('', 'fqdn')`}" {
${0}
}
snippet case
case $${1:variable} {
default: { ${0} }
}
snippet ife
if $${1:variable} {
${2}
} else {
${0}
}
snippet if
if $${1:variable} {
${0}
}
snippet ifd
if defined(${1:Resource}["${2:name}"]) {
${0}
}
snippet ifnd
if !defined(${1:Resource}["${2:name}"]) {
${0}
}
snippet el
else {
${0}
}
snippet ?
? {
"${1}" => ${0}
}
#
# blocks etc and general syntax sugar
snippet [
[ ${1} ]
snippet >
${1} => ${0}
snippet p:
"puppet://puppet/${1:module name}/${0:file name}"
#
# Functions
snippet alert
alert("${1:message}")
snippet crit
crit("${1:message}")
snippet debug
debug("${1:message}")
snippet defined
defined(${1:Resource}["${2:name}"])
snippet emerg
emerg("${1:message}")
snippet extlookup Simple extlookup
extlookup("${1:variable}")
snippet extlookup Extlookup with defaults
extlookup("${1:variable}", "${2:default}")
snippet extlookup Extlookup with defaults and custom data file
extlookup("${1:variable}", "${2:default}", "${3:data source}")
snippet fail
fail("${1:message}")
snippet info
info("${1:message}")
snippet inline_template
inline_template("<%= ${1} %>")
snippet notice
notice("${1:message}")
snippet realize
realize(${1:Resource}[${2:name}])
snippet regsubst
regsubst(${1:hay stack}, ${2:needle}, "${3:replacement}")
snippet inc
include ${1:classname}
snippet split
split(${1:hay stack}, "${2:patten}")
snippet versioncmp
versioncmp("${1:version}", "${2:version}")
snippet warning
warning("${1:message}")
#
# Types
snippet cron
cron { "${1:name}":
command => "${2}",
user => "${3:root}",
${4} => ${0},
}
snippet exec
exec { "${1:name}":
command => "${2:$1}",
user => "${3:root}",
${4} => ${0},
}
snippet user
user { "${1:user}":
ensure => present,
comment => "${2:$1}",
managehome => true,
home => "${0:/home/$1}",
}
snippet group
group { "${1:group}":
ensure => ${0:present},
}
snippet host
host { "${1:hostname}":
ip => ${0:127.0.0.1},
}
snippet mailalias
mailalias { "${1:localpart}":
recipient => "${0:recipient}",
}
snippet mount
mount { "${1:destination path}":
ensure => ${2:mounted},
device => "${0:device name or path}",
}
snippet package
package { "${1:package name}":
ensure => ${0:present},
}
snippet yumrepo
yumrepo { "${1:repo name}":
descr => "${2:$1}",
enabled => ${0:1},
}
snippet define
define ${1} (${2}) {
${0}
}
snippet service
service { "${1:service}" :
ensure => running,
enable => true,
require => [ Package["${2:package}"], File["${3:file}"], ],
subscribe => [ File["${4:configfile1}"], File["${5:configfile2}"], Package["${6:package}"], ],
}
snippet file
file { "${1:filename}" :
ensure => ${2:present},
owner => "${3:root}",
group => "${4:root}",
mode => "${5:0644}",
source => "puppet:///modules/${6:module}/${7:source}",
content => template("${8:module}/${9:template}"),
alias => "${10:alias}",
require => [ Package["${11:package}"], File["${12:file}"], ],
}
snippet archive
archive { "${1:filename}" :
ensure => ${2:present},
url => "http://${3:url}",
extension => "${4:tgz}",
target => "${5:target}",
checksum => ${6:false},
src_target => "${7:/tmp}",
}
snippet firewall
firewall { "${1:comment}" :
proto => ${2:tcp},
action => ${3:accept},
port => ${4},
}

View File

@ -0,0 +1,242 @@
snippet #!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
snippet #!3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
snippet imp
import ${0:module}
snippet uni
def __unicode__(self):
${0:representation}
snippet from
from ${1:package} import ${0:module}
# Module Docstring
snippet docs
"""
File: ${1:`vim_snippets#Filename('$1.py', 'foo.py')`}
Author: `g:snips_author`
Email: `g:snips_email`
Github: `g:snips_github`
Description: ${0}
"""
snippet wh
while ${1:condition}:
${0}
# dowh - does the same as do...while in other languages
snippet dowh
while True:
${1}
if ${0:condition}:
break
snippet with
with ${1:expr} as ${2:var}:
${0}
# New Class
snippet cl
class ${1:ClassName}(${2:object}):
"""${3:docstring for $1}"""
def __init__(self, ${4:arg}):
${5:super($1, self).__init__()}
self.$4 = $4
${0}
# New Function
snippet def
def ${1:fname}(${2:`indent('.') ? 'self' : ''`}):
"""${3:docstring for $1}"""
${0}
snippet deff
def ${1:fname}(${2:`indent('.') ? 'self' : ''`}):
${0}
# New Method
snippet defm
def ${1:mname}(self, ${2:arg}):
${0}
# New Property
snippet property
def ${1:foo}():
doc = "${2:The $1 property.}"
def fget(self):
${3:return self._$1}
def fset(self, value):
${4:self._$1 = value}
def fdel(self):
${0:del self._$1}
return locals()
$1 = property(**$1())
# Ifs
snippet if
if ${1:condition}:
${0}
snippet el
else:
${0}
snippet ei
elif ${1:condition}:
${0}
# For
snippet for
for ${1:item} in ${2:items}:
${0}
# Encodes
snippet cutf8
# -*- coding: utf-8 -*-
snippet clatin1
# -*- coding: latin-1 -*-
snippet cascii
# -*- coding: ascii -*-
# Lambda
snippet ld
${1:var} = lambda ${2:vars} : ${0:action}
snippet .
self.
snippet try Try/Except
try:
${1}
except ${2:Exception}, ${3:e}:
${0:raise $3}
snippet try Try/Except/Else
try:
${1}
except ${2:Exception}, ${3:e}:
${4:raise $3}
else:
${0}
snippet try Try/Except/Finally
try:
${1}
except ${2:Exception}, ${3:e}:
${4:raise $3}
finally:
${0}
snippet try Try/Except/Else/Finally
try:
${1}
except ${2:Exception}, ${3:e}:
${4:raise $3}
else:
${5}
finally:
${0}
# if __name__ == '__main__':
snippet ifmain
if __name__ == '__main__':
${0:main()}
# __magic__
snippet _
__${1:init}__
# python debugger (pdb)
snippet pdb
import pdb
pdb.set_trace()
# bpython debugger (bpdb)
snippet bpdb
import bpdb
bpdb.set_trace()
# ipython debugger (ipdb)
snippet ipdb
import ipdb
ipdb.set_trace()
# embed ipython itself
snippet iem
import IPython
IPython.embed()
# ipython debugger (pdbbb)
snippet pdbbb
import pdbpp
pdbpp.set_trace()
# remote python debugger (rpdb)
snippet rpdb
import rpdb
rpdb.set_trace()
# ptpython
snippet ptpython
from ptpython.repl import embed
embed(globals(), locals(), vi_mode=${1:False}, history_filename=${2:None})
# python console debugger (pudb)
snippet pudb
import pudb
pudb.set_trace()
# pdb in nosetests
snippet nosetrace
from nose.tools import set_trace
set_trace()
snippet pprint
import pprint
pprint.pprint(${1})
snippet "
"""${0:doc}
"""
# assertions
snippet a=
self.assertEqual(${0}, ${1})
# test function/method
snippet test
def test_${1:description}(${2:`indent('.') ? 'self' : ''`}):
${0}
# test case
snippet testcase
class ${1:ExampleCase}(unittest.TestCase):
def test_${2:description}(self):
${0}
snippet fut
from __future__ import ${0}
#getopt
snippet getopt
try:
# Short option syntax: "hv:"
# Long option syntax: "help" or "verbose="
opts, args = getopt.getopt(sys.argv[1:], "${1:short_options}", [${2:long_options}])
except getopt.GetoptError, err:
# Print debug info
print str(err)
${3:error_action}
for option, argument in opts:
if option in ("-h", "--help"):
${0}
elif option in ("-v", "--verbose"):
verbose = argument
# logging
# glog = get log
snippet glog
import logging
logger = logging.getLogger(${0:__name__})
snippet le
logger.error(${0:msg})
# conflict with lambda=ld, therefor we change into Logger.debuG
snippet lg
logger.debug(${0:msg})
snippet lw
logger.warning(${0:msg})
snippet lc
logger.critical(${0:msg})
snippet li
logger.info(${0:msg})
snippet epydoc
"""${1:Description}
@param ${2:param}: ${3: Description}
@type $2: ${4: Type}
@return: ${5: Description}
@rtype : ${6: Type}
@raise e: ${0: Description}
"""
snippet dol
def ${1:__init__}(self, *args, **kwargs):
super(${0:ClassName}, self).$1(*args, **kwargs)
snippet kwg
self.${1:var_name} = kwargs.get('$1', ${2:None})
snippet lkwg
${1:var_name} = kwargs.get('$1', ${2:None})
snippet args
*args${1:,}${0}
snippet kwargs
**kwargs${1:,}${0}
snippet akw
*args, **kwargs${1:,}${0}

View File

@ -0,0 +1,131 @@
snippet #!
#!/usr/bin/env Rscript
# includes
snippet lib
library(${0:package})
snippet req
require(${0:package})
snippet source
source('${0:file}')
# conditionals
snippet if
if (${1:condition}) {
${0}
}
snippet el
else {
${0}
}
snippet ei
else if (${1:condition}) {
${0}
}
# loops
snippet wh
while(${1}) {
${2}
}
snippet for
for (${1:item} in ${2:list}) {
${3}
}
# functions
snippet fun
${1:name} <- function (${2:variables}) {
${0}
}
snippet ret
return(${0})
# dataframes, lists, etc
snippet df
${1:name}[${2:rows}, ${0:cols}]
snippet c
c(${0:items})
snippet li
list(${0:items})
snippet mat
matrix(${1:data}, nrow = ${2:rows}, ncol = ${0:cols})
# apply functions
snippet apply
apply(${1:array}, ${2:margin}, ${0:function})
snippet lapply
lapply(${1:list}, ${0:function})
snippet sapply
lapply(${1:list}, ${0:function})
snippet vapply
vapply(${1:list}, ${2:function}, ${0:type})
snippet mapply
mapply(${1:function}, ${0:...})
snippet tapply
tapply(${1:vector}, ${2:index}, ${0:function})
snippet rapply
rapply(${1:list}, ${0:function})
# plyr functions
snippet dd
ddply(${1:frame}, ${2:variables}, ${0:function})
snippet dl
dlply(${1:frame}, ${2:variables}, ${0:function})
snippet da
daply(${1:frame}, ${2:variables}, ${0:function})
snippet d_
d_ply(${1:frame}, ${2:variables}, ${0:function})
snippet ad
adply(${1:array}, ${2:margin}, ${0:function})
snippet al
alply(${1:array}, ${2:margin}, ${0:function})
snippet aa
aaply(${1:array}, ${2:margin}, ${0:function})
snippet a_
a_ply(${1:array}, ${2:margin}, ${0:function})
snippet ld
ldply(${1:list}, ${0:function})
snippet ll
llply(${1:list}, ${0:function})
snippet la
laply(${1:list}, ${0:function})
snippet l_
l_ply(${1:list}, ${0:function})
snippet md
mdply(${1:matrix}, ${0:function})
snippet ml
mlply(${1:matrix}, ${0:function})
snippet ma
maply(${1:matrix}, ${0:function})
snippet m_
m_ply(${1:matrix}, ${0:function})
# plot functions
snippet pl
plot(${1:x}, ${0:y})
snippet ggp
ggplot(${1:data}, aes(${0:aesthetics}))
snippet img
${1:(jpeg,bmp,png,tiff)}(filename = '${2:filename}', width = ${3}, height = ${4}, unit = '${5}')
${0:plot}
dev.off()
# statistical test functions
snippet fis
fisher.test(${1:x}, ${0:y})
snippet chi
chisq.test(${1:x}, ${0:y})
snippet tt
t.test(${1:x}, ${0:y})
snippet wil
wilcox.test(${1:x}, ${0:y})
snippet cor
cor.test(${1:x}, ${0:y})
snippet fte
var.test(${1:x}, ${0:y})
snippet kvt
kv.test(${1:x}, ${0:y})

View File

@ -0,0 +1,98 @@
# rst
snippet :
:${1:field name}: ${0:field body}
snippet *
*${1:Emphasis}* ${0}
snippet **
**${1:Strong emphasis}** ${0}
snippet _
\`${1:hyperlink-name}\`_
.. _\`$1\`: ${0:link-block}
snippet =
${1:Title}
=====${2:=}
${0}
snippet -
${1:Title}
-----${2:-}
${0}
#some directive
snippet img:
.. |${0:alias}| image:: ${1:img}
snippet fig:
.. figure:: ${1:img}
:alt: ${0:alter text}
$2
snippet cont:
.. contents::
${0:content}
snippet code:
.. code:: ${1:type}
${0:write some code}
snippet tip:
.. tip::
${0:my tips}
snippet not:
.. note::
${0:my notes}
snippet war:
.. warning::
${0:attention!}
snippet imp:
.. important::
${0:this is importatnt}
snippet att:
.. attention::
${0:hey!}
snippet dan:
.. danger::
${0:ah!}
snippet err:
.. error::
${0:Error occur}
snippet cau:
.. caution::
${0:Watch out!}
#Sphinx only
snippet sid:
.. sidebar:: ${1:Title}
${0}
snippet tod:
.. todo::
${0}
snippet lis:
.. list-table:: ${0:Title}
:header-rows: 1
:stub-columns: 1
* - x1,y1
- x2,y1
- x3,y1
* - x1,y2
- x2,y2
- x3,y2
* - x1,y3
- x2,y3
- x3,y3
snippet toc:
.. toctree::
:maxdepth: 2
${0}
snippet dow:
:download:`${0:text} <${1:path}>`
snippet ref:
:ref:`${0:text} <${1:path}>`
snippet doc:
:doc:`${0:text} <${1:path}>`
# CJK optimize, CJK has no space between charaters
snippet *c
\ *${1:Emphasis}*\ ${0}
snippet **c
\ **${1:Strong emphasis}**\ ${0}

View File

@ -0,0 +1,731 @@
snippet enc
# encoding: utf-8
snippet frozen
# frozen_string_literal: true
snippet #!
#!/usr/bin/env ruby
# New Block
snippet =b
=begin rdoc
${0}
=end
snippet prot
protected
${0}
snippet priv
private
${0}
snippet y
:yields: ${0:arguments}
snippet rb
#!/usr/bin/env ruby -wKU
snippet beg
begin
${0}
rescue ${1:Exception} => ${2:e}
end
snippet req require
require '${1}'
snippet reqr
require_relative '${1}'
snippet #
# =>
snippet case
case ${1:object}
when ${2:condition}
${0}
end
snippet when
when ${1:condition}
${0}
snippet def
def ${1:method_name}
${0}
end
snippet deft
def test_${1:case_name}
${0}
end
snippet descendants
class Class
def descendants
ObjectSpace.each_object(::Class).select { |klass| klass < self }
end
end
snippet if
if ${1:condition}
${0}
end
snippet ife
if ${1:condition}
${2}
else
${0}
end
snippet eif
elsif ${1:condition}
${0}
snippet ifee
if ${1:condition}
$2
elsif ${3:condition}
$4
else
$0
end
snippet unless
unless ${1:condition}
${0}
end
snippet unlesse
unless ${1:condition}
$2
else
$0
end
snippet unlesee
unless ${1:condition}
$2
elsif ${3:condition}
$4
else
$0
end
snippet wh
while ${1:condition}
${0}
end
snippet for
for ${1:e} in ${2:c}
${0}
end
snippet until
until ${1:condition}
${0}
end
snippet cla class .. end
class ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`}
${0}
end
snippet clai class .. initialize .. end
class ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`}
def initialize(${2:args})
${0}
end
end
snippet cla< class .. < ParentClass .. initialize .. end
class ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} < ${2:ParentClass}
def initialize(${3:args})
${0}
end
end
snippet blankslate class BlankSlate .. initialize .. end
class ${0:BlankSlate}
instance_methods.each { |meth| undef_method(meth) unless meth =~ /\A__/ }
end
snippet claself class << self .. end
class << ${1:self}
${0}
end
# class .. < DelegateClass .. initialize .. end
snippet cla-
class ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} < DelegateClass(${2:ParentClass})
def initialize(${3:args})
super(${4:del_obj})
${0}
end
end
snippet mod module .. end
module ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`}
${0}
end
snippet mod module .. ClassMethods .. end
module ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`}
module ClassMethods
${0}
end
module InstanceMethods
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
# attr_reader
snippet r
attr_reader :${0:attr_names}
# attr_writer
snippet w
attr_writer :${0:attr_names}
# attr_accessor
snippet rw
attr_accessor :${0:attr_names}
snippet atp
attr_protected :${0:attr_names}
snippet ata
attr_accessible :${0:attr_names}
snippet ana
accepts_nested_attributes_for :${0:association}
# ivc == instance variable cache
snippet ivc
@${1:variable_name} ||= ${0:cached_value}
# include Enumerable
snippet Enum
include Enumerable
def each(&block)
${0}
end
# include Comparable
snippet Comp
include Comparable
def <=>(other)
${0}
end
# extend Forwardable
snippet Forw-
extend Forwardable
# def self
snippet defs
def self.${1:class_method_name}
${0}
end
# def initialize
snippet definit
def initialize(${1:args})
${0}
end
# def method_missing
snippet defmm
def method_missing(meth, *args, &blk)
${0}
end
snippet defd
def_delegator :${1:@del_obj}, :${2:del_meth}, :${0:new_name}
snippet defds
def_delegators :${1:@del_obj}, :${0:del_methods}
snippet am
alias_method :${1:new_name}, :${0:old_name}
snippet app
if __FILE__ == $PROGRAM_NAME
${0}
end
# usage_if()
snippet usai
if ARGV.${1}
abort "Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}"${0}
end
# usage_unless()
snippet usau
unless ARGV.${1}
abort "Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}"${0}
end
snippet array
Array.new(${1:10}) { |${2:i}| ${0} }
snippet hash
Hash.new { |${1:hash}, ${2:key}| $1[$2] = ${0} }
snippet file File.foreach() { |line| .. }
File.foreach(${1:'path/to/file'}) { |${2:line}| ${0} }
snippet file File.read()
File.read(${1:'path/to/file'})
snippet Dir Dir.global() { |file| .. }
Dir.glob(${1:'dir/glob/*'}) { |${2:file}| ${0} }
snippet Dir Dir[".."]
Dir[${1:'glob/**/*.rb'}]
snippet dir
Filename.dirname(__FILE__)
snippet deli
delete_if { |${1:e}| ${0} }
snippet fil
fill(${1:range}) { |${2:i}| ${0} }
# flatten_once()
snippet flao
reduce(Array.new) { |${1:arr}, ${2:a}| $1.push(*$2) }
snippet zip
zip(${1:enums}) { |${2:row}| ${0} }
# downto(0) { |n| .. }
snippet dow
downto(${1:0}) { |${2:n}| ${0} }
snippet ste
step(${1:2}) { |${2:n}| ${0} }
snippet tim
times { |${1:n}| ${0} }
snippet upt
upto(${1:1.0/0.0}) { |${2:n}| ${0} }
snippet loo
loop { ${0} }
snippet ea
each { |${1:e}| ${0} }
snippet ead
each do |${1:e}|
${0}
end
snippet eab
each_byte { |${1:byte}| ${0} }
snippet eac- each_char { |chr| .. }
each_char { |${1:chr}| ${0} }
snippet eac- each_cons(..) { |group| .. }
each_cons(${1:2}) { |${2:group}| ${0} }
snippet eai
each_index { |${1:i}| ${0} }
snippet eaid
each_index do |${1:i}|
${0}
end
snippet eak
each_key { |${1:key}| ${0} }
snippet eakd
each_key do |${1:key}|
${0}
end
snippet eal
each_line { |${1:line}| ${0} }
snippet eald
each_line do |${1:line}|
${0}
end
snippet eap
each_pair { |${1:name}, ${2:val}| ${0} }
snippet eapd
each_pair do |${1:name}, ${2:val}|
${0}
end
snippet eas-
each_slice(${1:2}) { |${2:group}| ${0} }
snippet easd-
each_slice(${1:2}) do |${2:group}|
${0}
end
snippet eav
each_value { |${1:val}| ${0} }
snippet eavd
each_value do |${1:val}|
${0}
end
snippet eawi
each_with_index { |${1:e}, ${2:i}| ${0} }
snippet eawid
each_with_index do |${1:e}, ${2:i}|
${0}
end
snippet eawo
each_with_object(${1:init}) { |${2:e}, ${3:var}| ${0} }
snippet eawod
each_with_object(${1:init}) do |${2:e}, ${3:var}|
${0}
end
snippet reve
reverse_each { |${1:e}| ${0} }
snippet reved
reverse_each do |${1:e}|
${0}
end
snippet inj
inject(${1:init}) { |${2:mem}, ${3:var}| ${0} }
snippet injd
inject(${1:init}) do |${2:mem}, ${3:var}|
${0}
end
snippet red
reduce(${1:init}) { |${2:mem}, ${3:var}| ${0} }
snippet redd
reduce(${1:init}) do |${2:mem}, ${3:var}|
${0}
end
snippet map
map { |${1:e}| ${0} }
snippet mapd
map do |${1:e}|
${0}
end
snippet mapwi-
enum_with_index.map { |${1:e}, ${2:i}| ${0} }
snippet sor
sort { |a, b| ${0} }
snippet sorb
sort_by { |${1:e}| ${0} }
snippet ran
sort_by { rand }
snippet all
all? { |${1:e}| ${0} }
snippet any
any? { |${1:e}| ${0} }
snippet cl
classify { |${1:e}| ${0} }
snippet col
collect { |${1:e}| ${0} }
snippet cold
collect do |${1:e}|
${0}
end
snippet det
detect { |${1:e}| ${0} }
snippet detd
detect do |${1:e}|
${0}
end
snippet fet
fetch(${1:name}) { |${2:key}| ${0} }
snippet fin
find { |${1:e}| ${0} }
snippet find
find do |${1:e}|
${0}
end
snippet fina
find_all { |${1:e}| ${0} }
snippet finad
find_all do |${1:e}|
${0}
end
snippet gre
grep(${1:/pattern/}) { |${2:match}| ${0} }
snippet sub
${1:g}sub(${2:/pattern/}) { |${3:match}| ${0} }
snippet sca
scan(${1:/pattern/}) { |${2:match}| ${0} }
snippet scad
scan(${1:/pattern/}) do |${2:match}|
${0}
end
snippet max
max { |a, b| ${0} }
snippet min
min { |a, b| ${0} }
snippet par
partition { |${1:e}| ${0} }
snippet pard
partition do |${1:e}|
${0}
end
snippet rej
reject { |${1:e}| ${0} }
snippet rejd
reject do |${1:e}|
${0}
end
snippet sel
select { |${1:e}| ${0} }
snippet seld
select do |${1:e}|
${0}
end
snippet lam
lambda { |${1:args}| ${0} }
snippet ->
-> { ${0} }
snippet ->a
->(${1:args}) { ${0} }
# I'm pretty sure that ruby users expect do to expand to do .. end
snippet do
do
${0}
end
# this is for one or more variables. typing a ", " is that cheap that it may
# not be worth adding another snippet. should 0/1 placeholders change order?
# its a good idea to think about the var name, so use it first
snippet dov
do |${1:v}|
${2}
end
snippet :
${1:key}: ${2:'value'}
snippet ope
open('${1:path/or/url/or/pipe}', '${2:w}') { |${3:io}| ${0} }
# path_from_here()
snippet fpath
File.join(File.dirname(__FILE__), *['${1:rel path here}'])
# unix_filter {}
snippet unif
ARGF.each_line${1} do |${2:line}|
${0}
end
# option_parse {}
snippet optp
require 'optparse'
options = { ${0:default: 'args'} }
ARGV.options do |opts|
opts.banner = "Usage: #{File.basename($PROGRAM_NAME)}"
end
snippet opt
opts.on('-${1:o}', '--${2:long-option-name}', ${3:String}, '${4:Option description.}') do |${5:opt}|
${0}
end
snippet tc
require 'test/unit'
require '${1:library_file_name}'
class Test${2:$1} < Test::Unit::TestCase
def test_${3:case_name}
${0}
end
end
snippet ts
require 'test/unit'
require 'tc_${1:test_case_file}'
require 'tc_${2:test_case_file}'
snippet as
assert ${1:test}, '${2:Failure message.}'
snippet ase
assert_equal ${1:expected}, ${2:actual}
snippet asne
assert_not_equal ${1:unexpected}, ${2:actual}
snippet asid
assert_in_delta ${1:expected_float}, ${2:actual_float}, ${3:2**-20}
snippet asi
assert_includes ${1:collection}, ${2:object}
snippet asio
assert_instance_of ${1:ExpectedClass}, ${2:actual_instance}
snippet asko
assert_kind_of ${1:ExpectedKind}, ${2:actual_instance}
snippet asn
assert_nil ${1:instance}
snippet asnn
assert_not_nil ${1:instance}
snippet asm
assert_match(/${1:expected_pattern}/, ${2:actual_string})
snippet asnm
assert_no_match(/${1:unexpected_pattern}/, ${2:actual_string})
snippet aso
assert_operator ${1:left}, :${2:operator}, ${3:right}
snippet asr
assert_raise ${1:Exception} { ${0} }
snippet asrd
assert_raise ${1:Exception} do
${0}
end
snippet asnr
assert_nothing_raised ${1:Exception} { ${0} }
snippet asnrd
assert_nothing_raised ${1:Exception} do
${0}
end
snippet asrt
assert_respond_to ${1:object}, :${2:method}
snippet ass assert_same(..)
assert_same ${1:expected}, ${2:actual}
snippet ass assert_send(..)
assert_send [${1:object}, :${2:message}, ${3:args}]
snippet asns
assert_not_same ${1:unexpected}, ${2:actual}
snippet ast
assert_throws :${1:expected}, -> { ${0} }
snippet astd
assert_throws :${1:expected} do
${0}
end
snippet asnt
assert_nothing_thrown { ${0} }
snippet asntd
assert_nothing_thrown do
${0}
end
snippet fl
flunk '${1:Failure message.}'
# Benchmark.bmbm do .. end
snippet bm-
TESTS = ${1:10_000}
Benchmark.bmbm do |results|
${0}
end
snippet rep
results.report('${1:name}:') { TESTS.times { ${0} } }
# Marshal.dump(.., file)
snippet Md
File.open('${1:path/to/file.dump}', 'wb') { |${2:file}| Marshal.dump(${3:obj}, $2) }
# Mashal.load(obj)
snippet Ml
File.open('${1:path/to/file.dump}', 'rb') { |${2:file}| Marshal.load($2) }
# deep_copy(..)
snippet deec
Marshal.load(Marshal.dump(${1:obj_to_copy}))
snippet Pn-
PStore.new('${1:file_name.pstore}')
snippet tra
transaction(${1:true}) { ${0} }
# xmlread(..)
snippet xml-
REXML::Document.new(File.read('${1:path/to/file}'))
# xpath(..) { .. }
snippet xpa
elements.each('${1://Xpath}') do |${2:node}|
${0}
end
# class_from_name()
snippet clafn
split('::').inject(Object) { |par, const| par.const_get(const) }
# singleton_class()
snippet sinc
class << self; self end
snippet nam
namespace :${1:`vim_snippets#Filename()`} do
${0}
end
snippet tas
desc '${1:Task description}'
task ${2:task_name: [:dependent, :tasks]} do
${0}
end
# block
snippet b
{ |${1:var}| ${0} }
snippet begin
begin
fail 'A test exception.'
rescue Exception => e
puts e.message
puts e.backtrace.inspect
else
# other exception
ensure
# always executed
end
#debugging
snippet debug
require 'byebug'; byebug
snippet debug19
require 'debugger'; debugger
snippet debug18
require 'ruby-debug'; debugger
snippet pry
require 'pry'; binding.pry
snippet strf
strftime('${1:%Y-%m-%d %H:%M:%S %z}')${0}
#
# Minitest snippets
#
snippet mb
must_be ${0}
snippet wb
wont_be ${0}
snippet mbe
must_be_empty
snippet wbe
wont_be_empty
snippet mbio
must_be_instance_of ${0:Class}
snippet wbio
wont_be_instance_of ${0:Class}
snippet mbko
must_be_kind_of ${0:Class}
snippet wbko
wont_be_kind_of ${0:Class}
snippet mbn
must_be_nil
snippet wbn
wont_be_nil
snippet mbsa
must_be_same_as ${0:other}
snippet wbsa
wont_be_same_as ${0:other}
snippet mbsi
-> { ${0} }.must_be_silent
snippet mbwd
must_be_within_delta ${1:0.1}, ${2:0.1}
snippet wbwd
wont_be_within_delta ${1:0.1}, ${2:0.1}
snippet mbwe
must_be_within_epsilon ${1:0.1}, ${2:0.1}
snippet wbwe
wont_be_within_epsilon ${1:0.1}, ${2:0.1}
snippet me
must_equal ${0:other}
snippet we
wont_equal ${0:other}
snippet mi
must_include ${0:what}
snippet wi
wont_include ${0:what}
snippet mm
must_match /${0:regex}/
snippet wm
wont_match /${0:regex}/
snippet mout
-> { ${1} }.must_output '${0}'
snippet mra
-> { ${1} }.must_raise ${0:Exception}
snippet mrt
must_respond_to :${0:method}
snippet wrt
wont_respond_to :${0:method}
snippet msend
must_send [ ${1:what}, :${2:method}, ${3:args} ]
snippet mthrow
-> { throw :${1:error} }.must_throw :${2:error}
##########################
# Rspec snippets #
##########################
snippet desc
describe ${1:`substitute(substitute(vim_snippets#Filename(), '_spec$', '', ''), '\(_\|^\)\(.\)', '\u\2', 'g')`} do
${0}
end
snippet descm
describe '${1:#method}' do
${0:pending 'Not implemented'}
end
snippet cont
context '${1:message}' do
${0}
end
snippet bef
before :${1:each} do
${0}
end
snippet aft
after :${1:each} do
${0}
end
snippet let
let(:${1:object}) { ${0} }
snippet let!
let!(:${1:object}) { ${0} }
snippet subj
subject { ${0} }
snippet s.
subject.${0:method}
snippet spec
specify { subject.${0} }
snippet exp
expect(${1:object}).to ${0}
snippet expb
expect { ${1:object} }.to ${0}
snippet experr
expect { ${1:object} }.to raise_error ${2:StandardError}, /${0:message_regex}/
snippet shared
shared_examples ${0:'shared examples name'}
snippet ibl
it_behaves_like ${0:'shared examples name'}
snippet it
it '${1:spec_name}' do
${0}
end
snippet its
its(:${1:method}) { should ${0} }
snippet is
it { should ${0} }
snippet isn
it { should_not ${0} }
snippet iexp
it { expect(${1:object}).${1} ${0} }
snippet iexpb
it { expect { ${1:object} }.${1} ${0} }
snippet iiexp
it { is_expected.to ${0} }
snippet iiexpn
it { is_expected.not_to ${0} }
snippet agg
aggregate_failures '${1:message}' do
${0}
end

View File

@ -0,0 +1,190 @@
#################
# Rust Snippets #
#################
# Functions
snippet fn "Function definition"
fn ${1:function_name}(${2})${3} {
${0}
}
snippet pfn "Function definition"
pub fn ${1:function_name}(${2})${3} {
${0}
}
snippet test "Unit test function"
#[test]
fn ${1:test_function_name}() {
${0}
}
snippet bench "Bench function" b
#[bench]
fn ${1:bench_function_name}(b: &mut test::Bencher) {
b.iter(|| {
${0}
})
}
snippet new "Constructor function"
pub fn new(${2}) -> ${1:Name} {
$1 { ${3} }
}
snippet main "Main function"
pub fn main() {
${0}
}
snippet let "let variable declaration with type inference"
let ${1} = ${2};
snippet lett "let variable declaration with explicit type annotation"
let ${1}: ${2} = ${3};
snippet letm "let mut variable declaration with type inference"
let mut ${1} = ${2};
snippet lettm "let mut variable declaration with explicit type annotation"
let mut ${1}: ${2} = ${3};
snippet pln "println!"
println!("${1}");
snippet pln, "println! with format param"
println!("${1}", ${2});
# Modules
snippet ec "extern crate"
extern crate ${1:sync};
snippet ecl "extern crate log"
#[macro_use]
extern crate log;
snippet mod
mod ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} {
${0}
} /* $1 */
snippet testmod "Test module" b
#[cfg(test)]
mod tests {
use super::${1:*};
test${0}
}
# Attributes
snippet allow "allow lint attribute" b
#[allow(${1:unused_variable})]
snippet cfg "cfg attribute" b
#[cfg(${1:target_os = "linux"})]
snippet feat "feature attribute" b
#![feature(${1:plugin})]
snippet der "#[derive(..)]" b
#[derive(${1:Debug})]
snippet attr "#[..]" b
#[${1:inline}]
snippet crate "Define create meta attributes"
// Crate name
#![crate_name = "${1:crate_name}"]
// Additional metadata attributes
#![desc = "${2:Descrption.}"]
#![license = "${3:BSD}"]
#![comment = "${4:Comment.}"]
// Specify the output type
#![crate_type = "${5:lib}"]
# Common types
snippet opt "Option<T>"
Option<${1:i32}>
snippet res "Result<T, E>"
Result<${1:~str}, ${2:()}>
# Control structures
snippet if
if ${1} {
${0}
}
snippet ife "if / else"
if ${1} {
${2}
} else {
${0}
}
snippet ifl "if let expression"
if let ${1} = ${2} {
${0}
}
snippet el "else"
else {
${0}
}
snippet eli "else if"
else if ${1} {
${0}
}
snippet mat "match pattern"
match ${1} {
${2} => ${3}
}
snippet case "Case clause of pattern match"
${1:_} => ${2:expression}
snippet loop "loop {}" b
loop {
${0}
}
snippet wh "while loop"
while ${1:condition} {
${0}
}
snippet for "for ... in ... loop"
for ${1:i} in ${2} {
${0}
}
# TODO commenting
snippet todo "TODO comment"
// [TODO]: ${0:Description}
snippet fixme "FIXME comment"
// FIXME: $0
# Struct
snippet st "Struct definition"
struct ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} {
${0}
}
snippet impl "Struct/Trait implementation"
impl ${1:Type/Trait}${2: for ${3:Type}} {
${0}
}
snippet stn "Struct with new constructor"
pub struct ${1:`substitute(vim_snippets#Filename(), '\(_\|^\)\(.\)', '\u\2', 'g')`} {
${0}
}
impl $1 {
pub fn new(${2}) -> $1 {
$1 { ${3} }
}
}
snippet type "Type alias"
type ${1:NewName} = $2;
snippet enum "enum definition"
enum ${1:Name} {
${2},
}
# Traits
snippet trait "Trait definition"
trait ${1:Name} {
${0}
}
snippet drop "Drop trait implementation (destructor)"
impl Drop for ${1:Name} {
fn drop(&mut self) {
${0}
}
}
# Statics
snippet ss "static string declaration"
static ${1}: &'static str = "${0}";
snippet stat "static item declaration"
static ${1}: ${2:usize} = ${0};
# Concurrency
snippet scoped "spawn a scoped thread"
thread::scoped(${1:move }|| {
${0}
});
snippet spawn "spawn a thread"
thread::spawn(${1:move }|| {
${0}
});
snippet chan "Declare (Sender, Receiver) pair of asynchronous channel()"
let (${1:tx}, ${2:rx}): (Sender<${3:i32}>, Receiver<${4:i32}>) = channel();
# Testing
snippet as "assert!"
assert!(${1:predicate})
snippet ase "assert_eq!"
assert_eq!(${1:expected}, ${2:actual})

View File

@ -0,0 +1,360 @@
################################################################
# © Copyright 2011 Konstantin Gorodinskiy. All Rights Reserved.#
# Do What The Fuck You Want To Public License, Version 2. #
# See http://sam.zoy.org/wtfpl/COPYING for more details. #
################################################################
# Scala lang
#if
snippet if
if (${1})
${0}
#if not
snippet ifn
if (!${1})
${0}
#if-else
snippet ife
if (${1})
${2}
else
${0}
#if-else-if
snippet ifelif
if (${1})
${2}
else if (${3})
${0}
snippet eif
else if (${3})
${0}
#while loop
snippet wh
while (${1:obj}) {
${0}
}
#for loop(classic)
snippet for
for (${1:item} <- ${2:obj}) {
${0}
}
#for loop(indexed)
snippet fori
for (${1:i} <- ${2:0} to ${3:obj}.length) {
${0}
}
#for comprehension
snippet fory
for {
${1:item} <- ${2:obj}
} yield ${0}
#exceptions
snippet try
try {
${1}
} catch {
case e: FileNotFoundException => ${2}
case e: IOException => ${3}
} finally {
${0}
}
#match
snippet match
${1: obj} match {
case ${2:e} => ${3}
case _ => ${0}
}
#case
snippet case
case ${1:value} => ${0}
############################
# methods and arguments
#
#arg
snippet arg
${1:a}: ${2:T}${0:, arg}
#args
snippet args
${1:args}: ${0:T}*
#def
snippet def
def ${1:name}(${2:arg}) = ${0:}
#private def
snippet prdef
private def ${1:name}(${2:arg}) = ${0:}
#override def
snippet ovdef
override def ${1:name}(${2:arg}) = ${0:}
#first class function(see scalabook p 188)
snippet fcf
(${1:a}: ${2:T}) => $1 ${0}
snippet =>
${1:name} => ${0}
#recursion
snippet rec
def ${1:name}(${0:arg}) =
if($2) $2
else $1($2)
#curried method
snippet crdef
def ${1:name}(${2:arg})(${3:arg}) = ${0:}
#main method
#check validity of T
snippet main
def main(args: Array[String]):${1:T} = ${0:}
############################
# basic types(general purpose)
# you might want to use basic types snippets
#1
snippet T Double
dbl
#2
snippet T Int
int
#3
snippet T Long
lng
#4
snippet T Char
chr
#5
snippet T String
str
#6
snippet T Array
arr
#7
snippet T Buffer
buf
#8
snippet T List
list
#9
snippet T Tuple
tpl
#10
snippet T Set
set
#11
snippet T Map
map
#12
snippet T HashSet
hset
#13
snippet T HashMap
hmap
#14
snippet T Boolean
bool
#end
#named snippets for types
snippet bool
Boolean
snippet anyr
AnyRef
snippet dbl
Double
snippet int
Int
snippet str
String
snippet chr
Char
snippet lng
Long
snippet arr
Array${1:[T]}${0:()}
snippet buf
Buffer${1:[T]}${0:()}
snippet list
List${1:[T]}${0:()}
snippet tpl
Tuple${1:2}[${2:T},${0:T}]
snippet set
Set${1:[T]}${0:()}
snippet hset
HashSet${1:[T]}${0:()}
snippet mhset
mutable.HashSet${1:[T]}${0:()}
#for maps
snippet keyval
${1:key}->${2:val}${0:, keyval}
snippet map
Map[${1:T},${2:T}]${0:(keyval)}
snippet hmap
HashMap[${1:T},${2:T}]${0:(keyval)}
snippet mmap
mutable.Map[${1:T},${2:T}]${0:(keyval)}
snippet mhmap
mutable.HashMap[${1:T},${2:T}]${0:(keyval)}
#TODO add TreeMap and TreeSet
#asInstanceOf[]
snippet as
${1:name}.asInstanceOf[${2:T}]
#isInstanceOf[]
snippet is
${1:name}.isInstanceOf[${2:T}]
#collections methods
#scope() with one arg
snippet (a
(${1:a} => ${0})
#scope() with two args
snippet {(
{(${1:a},${2:b}) =>
${0}
}
#filter
snippet filter
${0:name}.filter (a
#map function
snippet mapf
${0:name}.map (a
#flatmap
snippet flatmap
${1:name}.flatMap${0:[T]}(a
#fold left
snippet fldl
${1:name}.foldLeft(${0:first}) {(
#fold right
snippet fldr
${1:name}.foldRight(${0:first}) {(
#fold left operator(if u wanna reduce readability of ur code)
#use wildcard symbols
snippet /:
(${1:first}/:${2:name})(${0})
#fold right operator
snippet :\
(${1:first}:\${2:name})(${0})
#reduce left
snippet redl
${1:name}.reduceLeft[${0:T}] {(
#reduce right
snippet redr
${1:name}.reduceRight[${0:T}] {(
#zipWithIndex(safe way).
#see http://daily-scala.blogspot.com/2010/05/zipwithindex.html
snippet zipwi
${0:name}.view.zipWithIndex
#split
snippet spl
${1:name}.split("${0:,}")
#end
snippet val
val ${1:name}${2:: T} = ${0:value}
snippet var
var ${1:name}${2:: T} = ${0:value}
############################
# classes
#
#extends
snippet extends
extends ${0:what}
#with
snippet with
with ${1:what}${0: with}
#auxiliary constructor(a. this)
snippet athis
def this(arg) = this(arg)
#abstract class
snippet abstract
abstract class ${1:name}${2:(arg)}${3: extends }${4: with} {
${5:override def toString = "$1"}
${0}
}
#class
snippet class
class ${1:name}${2:(arg)}${3: extends }${4: with} {
${5:override def toString = "$1"}
${0}
}
#object
snippet object
object ${1:name}${2:(arg)}${3: extends }${4: with} ${0:}
#trait
snippet trait
trait ${1:name}${2: extends }${3: with} {
${0:}
}
#class with trait Ordered(page 265)
snippet ordered
class ${1:name}${2:(arg)} extends Ordered[$1] ${3: with} {
${4:override def toString = "$1"}
def compare(that: $1) = ${5:this - that}
${0}
}
#case class
snippet casecl
case class ${1:name}${2:(arg)}${3: extends }${4: with} ${0:}
############################
# testing
#
#scalatest imports
snippet scalatest
${1:import org.scalatest.Suite}
${0:import org.scalatest.FunSuite}
#assert
snippet assert
assert(${1:a} === ${0:b})
#ensuring(p 296)
snippet ensuring
ifel ensuring(${1:a}==${0:b})
#expect
snippet expect
expect(${1:what}) {
${0}
}
#intercept
snippet intercept
intercept[${1:IllegalArgumentException}] {
${0}
}
#test
snippet test
test("${1:description}") {
${0}
}
#suite
snippet suite
class ${0:name} extends Suite {
def test() {
}
#funsuite
snippet fsuite
class ${1:name} extends FunSuite {
test("${0:description}") {
}
############################
# SBT
#
snippet webproject
import sbt._
class ${1:Name}(info: ProjectInfo) extends DefaultWebProject(info) {
val liftVersion = "${0:2.3}"
override def libraryDependencies = Set(
) ++ super.libraryDependencies
val snapshots = ScalaToolsSnapshots
}
#depencies
snippet liftjar
"net.liftweb" %% "${0:lib}" % liftVersion % "compile->default",
snippet jettyjar
"org.mortbay.jetty" % "jetty" % "${0:version}" % "test->default",
############################
# Lift
#
#lift imports
snippet liftimports
import _root_.net.liftweb.http._
import S._
import _root_.net.liftweb.util._
import Helpers._
import _root_.scala.xml._
#TODO LIFT,SBT,WEB.XML,HTML snippets

View File

@ -0,0 +1,99 @@
# Shebang. Executing bash via /usr/bin/env makes scripts more portable.
snippet #!
#!/usr/bin/env sh
snippet bash
#!/usr/bin/env bash
snippet sbash
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
snippet if
if [[ ${1:condition} ]]; then
${0:#statements}
fi
snippet elif
elif [[ ${1:condition} ]]; then
${0:#statements}
snippet for
for (( ${2:i} = 0; $2 < ${1:count}; $2++ )); do
${0:#statements}
done
snippet fori
for ${1:needle} in ${2:haystack} ; do
${0:#statements}
done
snippet wh
while [[ ${1:condition} ]]; do
${0:#statements}
done
snippet until
until [[ ${1:condition} ]]; do
${0:#statements}
done
snippet case
case ${1:word} in
${2:pattern})
${0};;
esac
snippet go
while getopts '${1:o}' ${2:opts}
do
case $$2 in
${3:o0})
${0:#staments};;
esac
done
# Set SCRIPT_DIR variable to directory script is located.
snippet sdir
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# getopt
snippet getopt
__ScriptVersion="${1:version}"
#=== FUNCTION ================================================================
# NAME: usage
# DESCRIPTION: Display usage information.
#===============================================================================
function usage ()
{
echo "Usage : $${0:0} [options] [--]
Options:
-h|help Display this message
-v|version Display script version"
} # ---------- end of function usage ----------
#-----------------------------------------------------------------------
# Handle command line arguments
#-----------------------------------------------------------------------
while getopts ":hv" opt
do
case $opt in
h|help ) usage; exit 0 ;;
v|version ) echo "$${0:0} -- Version $__ScriptVersion"; exit 0 ;;
* ) echo -e "\n Option does not exist : $OPTARG\n"
usage; exit 1 ;;
esac # --- end of case ---
done
shift $(($OPTIND-1))
snippet root
if [ \$(id -u) -ne 0 ]; then exec sudo \$0; fi
snippet fun-sh
${1:function_name}() {
${0:#function_body}
}
snippet fun
function ${1:function_name}() {
${0:#function_body}
}

View File

@ -0,0 +1,26 @@
snippet tbl
create table ${1:table} (
${0:columns}
);
snippet col
${1:name} ${2:type} ${3:default ''} ${0:not null}
snippet ccol
${1:name} varchar2(${2:size}) ${3:default ''} ${0:not null}
snippet ncol
${1:name} number ${3:default 0} ${0:not null}
snippet dcol
${1:name} date ${3:default sysdate} ${0:not null}
snippet ind
create index ${0:$1_$2} on ${1:table}(${2:column});
snippet uind
create unique index ${1:name} on ${2:table}(${0:column});
snippet tblcom
comment on table ${1:table} is '${0:comment}';
snippet colcom
comment on column ${1:table}.${2:column} is '${0:comment}';
snippet addcol
alter table ${1:table} add (${2:column} ${0:type});
snippet seq
create sequence ${1:name} start with ${2:1} increment by ${3:1} minvalue ${0:1};
snippet s*
select * from ${0:table}

View File

@ -0,0 +1,96 @@
# #!/usr/bin/env tclsh
snippet #!
#!/usr/bin/env tclsh
# Process
snippet pro
proc ${1:function_name} {${2:args}} {
${0}
}
#xif
snippet xif
${1:expr}? ${2:true} : ${0:false}
# Conditional
snippet if
if {${1}} {
${0}
}
# Conditional if..else
snippet ife
if {${1}} {
${2}
} else {
${0:# else...}
}
snippet eif
elseif {${1}} {
${0}
}
# Conditional if..elsif..else
snippet ifee
if {${1}} {
${2}
} elseif {${3}} {
${4:# elsif...}
} else {
${0:# else...}
}
# If catch then
snippet ifc
if { [catch {${1:#do something...}} ${2:err}] } {
${0:# handle failure...}
}
# Catch
snippet catch
catch {${1}} ${2:err} ${0:options}
# While Loop
snippet wh
while {${1}} {
${0}
}
# For Loop
snippet for
for {set ${2:var} 0} {$$2 < ${1:count}} {${3:incr} $2} {
${0}
}
# Foreach Loop
snippet fore
foreach ${1:x} {${2:#list}} {
${0}
}
# after ms script...
snippet af
after ${1:ms} ${0:#do something}
# after cancel id
snippet afc
after cancel ${0:id or script}
# after idle
snippet afi
after idle ${0:script}
# after info id
snippet afin
after info ${0:id}
# Expr
snippet exp
expr {${0:#expression here}}
# Switch
snippet sw
switch ${1:var} {
${3:pattern 1} {
${0:#do something}
}
default {
${2:#do something}
}
}
# Case
snippet ca
${1:pattern} {
${2:#do something}
}
# Namespace eval
snippet ns
namespace eval ${1:path} {${0:#script...}}
# Namespace current
snippet nsc
namespace current

View File

@ -0,0 +1,317 @@
#PREAMBLE
#newcommand
snippet nc \newcommand
\newcommand{\\${1:cmd}}[${2:opt}]{${3:realcmd}} ${0}
#usepackage
snippet up \usepackage
\usepackage[${1:options}]{${2:package}} ${0}
#newunicodechar
snippet nuc \newunicodechar
\newunicodechar{${1}}{${2:\ensuremath}${3:tex-substitute}}} ${0}
#DeclareMathOperator
snippet dmo \DeclareMathOperator
\DeclareMathOperator{${1}}{${2}} ${0}
#DOCUMENT
# \begin{}...\end{}
snippet begin \begin{} ... \end{} block
\begin{${1:env}}
${0:${VISUAL}}
\end{$1}
# Tabular
snippet tab tabular (or arbitrary) environment
\begin{${1:tabular}}{${2:c}}
${0:${VISUAL}}
\end{$1}
snippet thm thm (or arbitrary) environment with optional argument
\begin[${1:author}]{${2:thm}}
${0:${VISUAL}}
\end{$2}
snippet center center environment
\begin{center}
${0:${VISUAL}}
\end{center}
# Align(ed)
snippet ali align(ed) environment
\begin{align${1:ed}}
\label{eq:${2}}
${0:${VISUAL}}
\end{align$1}
# Gather(ed)
snippet gat gather(ed) environment
\begin{gather${1:ed}}
${0:${VISUAL}}
\end{gather$1}
# Equation
snippet eq equation environment
\begin{equation}
${0:${VISUAL}}
\end{equation}
# Equation
snippet eql Labeled equation environment
\begin{equation}
\label{eq:${2}}
${0:${VISUAL}}
\end{equation}
# Equation
snippet eq* unnumbered equation environment
\begin{equation*}
${0:${VISUAL}}
\end{equation*}
# Unnumbered Equation
snippet \ unnumbered equation: \[ ... \]
\[
${0:${VISUAL}}
\]
# Equation array
snippet eqnarray eqnarray environment
\begin{eqnarray}
${0:${VISUAL}}
\end{eqnarray}
# Label
snippet lab \label
\label{${1:eq:}${2:fig:}${3:tab:}${0}}
# Enumerate
snippet enum enumerate environment
\begin{enumerate}
\item ${0}
\end{enumerate}
snippet enuma enumerate environment
\begin{enumerate}[(a)]
\item ${0}
\end{enumerate}
snippet enumi enumerate environment
\begin{enumerate}[(i)]
\item ${0}
\end{enumerate}
# Itemize
snippet itemize itemize environment
\begin{itemize}
\item ${0}
\end{itemize}
snippet item \item
\item ${1:${VISUAL}}
# Description
snippet desc description environment
\begin{description}
\item[${1}] ${0}
\end{description}
# Endless new item
snippet ]i \item (recursive)
\item ${1}
${0:]i}
# Matrix
snippet mat smart matrix environment
\begin{${1:p/b/v/V/B/small}matrix}
${0:${VISUAL}}
\end{$1matrix}
# Cases
snippet cas cases environment
\begin{cases}
${1:equation}, &\text{ if }${2:case}\\
${0:${VISUAL}}
\end{cases}
# Split
snippet spl split environment
\begin{split}
${0:${VISUAL}}
\end{split}
# Part
snippet part document \part
\part{${1:part name}} % (fold)
\label{prt:${2:$1}}
${0}
% part $2 (end)
# Chapter
snippet cha \chapter
\chapter{${1:chapter name}}
\label{cha:${2:$1}}
${0}
# Section
snippet sec \section
\section{${1:section name}}
\label{sec:${2:$1}}
${0}
# Section without number
snippet sec* \section*
\section*{${1:section name}}
\label{sec:${2:$1}}
${0}
# Sub Section
snippet sub \subsection
\subsection{${1:subsection name}}
\label{sub:${2:$1}}
${0}
# Sub Section without number
snippet sub* \subsection*
\subsection*{${1:subsection name}}
\label{sub:${2:$1}}
${0}
# Sub Sub Section
snippet subs \subsubsection
\subsubsection{${1:subsubsection name}}
\label{ssub:${2:$1}}
${0}
# Sub Sub Section without number
snippet subs* \subsubsection*
\subsubsection*{${1:subsubsection name}}
\label{ssub:${2:$1}}
${0}
# Paragraph
snippet par \paragraph
\paragraph{${1:paragraph name}}
\label{par:${2:$1}}
${0}
# Sub Paragraph
snippet subp \subparagraph
\subparagraph{${1:subparagraph name}}
\label{subp:${2:$1}}
${0}
snippet ni \noindent
\noindent
${0}
#References
snippet itd description \item
\item[${1:description}] ${0:item}
snippet figure reference to a figure
${1:Figure}~\ref{${2:fig:}}
snippet table reference to a table
${1:Table}~\ref{${2:tab:}}
snippet listing reference to a listing
${1:Listing}~\ref{${2:list}}
snippet section reference to a section
${1:Section}~\ref{sec:${2}} ${0}
snippet page reference to a page
${1:page}~\pageref{${2}} ${0}
snippet index \index
\index{${1:index}} ${0}
#Citations
snippet citen \citen
\citen{${1}} ${0}
# natbib citations
snippet citep \citep
\citep{${1}} ${0}
snippet citet \citet
\citet{${1}} ${0}
snippet cite \cite[]{}
\cite[${1}]{${2}} ${0}
snippet citea \citeauthor
\citeauthor{${1}} ${0}
snippet citey \citeyear
\citeyear{${1}} ${0}
snippet fcite \footcite[]{}
\footcite[${1}]{${2}}${0}
#Formating text: italic, bold, underline, small capital, emphase ..
snippet it italic text
\textit{${0:${VISUAL:text}}}
snippet bf bold face text
\textbf{${0:${VISUAL:text}}}
snippet under underline text
\underline{${0:${VISUAL:text}}}
snippet emp emphasize text
\emph{${0:${VISUAL:text}}}
snippet sc small caps text
\textsc{${0:${VISUAL:text}}}
#Choosing font
snippet sf sans serife text
\textsf{${0:${VISUAL:text}}}
snippet rm roman font text
\textrm{${0:${VISUAL:text}}}
snippet tt typewriter (monospace) text
\texttt{${0:${VISUAL:text}}}
#Math font
snippet mf mathfrak
\mathfrak{${0:${VISUAL:text}}}
snippet mc mathcal
\mathcal{${0:${VISUAL:text}}}
snippet ms mathscr
\mathscr{${0:${VISUAL:text}}}
#misc
snippet ft \footnote
\footnote{${0:${VISUAL:text}}}
snippet fig figure environment (includegraphics)
\begin{figure}
\begin{center}
\includegraphics[scale=${1}]{Figures/${2}}
\end{center}
\caption{${3}}
\label{fig:${4}}
\end{figure}
${0}
snippet tikz figure environment (tikzpicture)
\begin{figure}
\begin{center}
\begin{tikzpicture}[scale=${1:1}]
${2}
\end{tikzpicture}
\end{center}
\caption{${3}}
\label{fig:${4}}
\end{figure}
${0}
#math
snippet stackrel \stackrel{}{}
\stackrel{${1:above}}{${2:below}} ${0}
snippet frac \frac{}{}
\frac{${1:num}}{${2:denom}} ${0}
snippet sum \sum^{}_{}
\sum^{${1:n}}_{${2:i=1}} ${0}
snippet lim \lim_{}
\lim_{${1:n \to \infty}} ${0}
snippet frame frame environment
\begin{frame}[${1:t}]{${2:title}}
${0:${VISUAL}}
\end{frame}
snippet block block environment
\begin{block}{${1:title}}
${0:${VISUAL}}
\end{block}
snippet alert alertblock environment
\begin{alertblock}{${1:title}}
${0:${VISUAL}}
\end{alertblock}
snippet example exampleblock environment
\begin{exampleblock}{${1:title}}
${0:${VISUAL}}
\end{exampleblock}
snippet col2 two-column environment
\begin{columns}
\begin{column}{0.5\textwidth}
${1}
\end{column}
\begin{column}{0.5\textwidth}
${0}
\end{column}
\end{columns}
snippet \{ \{ \}
\\{ ${0} \\}
#delimiter
snippet lr left right
\left${1} ${0} \right$1
snippet lr( left( right)
\left( ${0} \right)
snippet lr| left| right|
\left| ${0} \right|
snippet lr{ left\{ right\}
\left\\{ ${0} \right\\}
snippet lr[ left[ right]
\left[ ${0} \right]
snippet lra langle rangle
\langle ${0} \rangle
# Code listings
snippet lst
\begin{listing}[language=${1:language}]
${0:${VISUAL}}
\end{listing}
snippet lsi
\lstinline|${1}| ${0}
# Hyperlinks
snippet url
\url{${1}} ${0}
snippet href
\href{${1}}{${2}} ${0}
# URL from Clipboard.
snippet urlc
\url{`@+`} ${0}
snippet hrefc
\href{`@+`}{${1}} ${0}

View File

@ -0,0 +1,52 @@
snippet header standard Vim script file header
" File: ${1:`expand('%:t')`}
" Author: ${2:`g:snips_author`}
" Description: ${3}
${0:" Last Modified: `strftime("%B %d, %Y")`}
snippet guard script reload guard
if exists('${1:did_`vim_snippets#Filename()`}') || &cp${2: || version < 700}
finish
endif
let $1 = 1${0}
snippet f function
fun! ${1:`expand('%') =~ 'autoload' ? substitute(matchstr(expand('%:p'),'autoload/\zs.*\ze.vim'),'[/\\]','#','g').'#' : ''`}${2:function_name}(${3})
${0}
endf
snippet t try ... catch statement
try
${1}
catch ${2}
${0}
endtry
snippet for for ... in loop
for ${1} in ${2}
${0}
endfor
snippet forkv for [key, value] in loop
for [${1},${2}] in items(${3})
${0}
unlet $1 $2
endfor
snippet wh while loop
while ${1}
${0}
endw
snippet if if statement
if ${1}
${0}
endif
snippet ife if ... else statement
if ${1}
${2}
else
${0}
endif
snippet au augroup ... autocmd block
augroup ${1:AU_NAME}
" this one is which you're most likely to use?
autocmd ${2:BufRead,BufNewFile} ${3:*.ext,*.ext3|<buffer[=N]>} ${0}
augroup end
snippet bun Vundle.vim Plugin definition
Plugin '${0}'
snippet plug Vundle.vim Plugin definition
Plugin '${0}'

View File

@ -0,0 +1,12 @@
# xml declaration
snippet xml
<?xml version="1.0" encoding="UTF-8"?>
# tag
snippet t
<${1:}>
${2}
</$1>
# inline tag
snippet ti
<${1:}>${2}</$1>

View File

@ -0,0 +1,66 @@
# #!/bin/zsh
snippet #!
#!/bin/zsh
snippet if
if ${1:condition}; then
${0:# statements}
fi
snippet ife
if ${1:condition}; then
${2:# statements}
else
${0:# statements}
fi
snippet eif
elif ${1:condition}; then
${0:# statements}
snippet for
for (( ${2:i} = 0; $2 < ${1:count}; $2++ )); do
${0:# statements}
done
snippet fori
for ${1:needle} in ${2:haystack}; do
${0:#statements}
done
snippet fore
for ${1:item} in ${2:list}; do
${0:# statements}
done
snippet wh
while ${1:condition}; do
${0:# statements}
done
snippet until
until ${1:condition}; do
${0:# statements}
done
snippet repeat
repeat ${1:integer}; do
${0:# statements}
done
snippet case
case ${1:word} in
${2:pattern})
${0};;
esac
snippet select
select ${1:answer} in ${2:choices}; do
${0:# statements}
done
snippet (
( ${0:#statements} )
snippet {
{ ${0:#statements} }
snippet [
[[ ${0:test} ]]
snippet always
{ ${1:try} } always { ${0:always} }
snippet fun
${1:function_name}() {
${0:# function_body}
}
snippet ffun
function ${1:function_name}() {
${0:# function_body}
}

View File

@ -0,0 +1,14 @@
WakaTime is written and maintained by Alan Hamlett and
various contributors:
Development Lead
----------------
- Alan Hamlett <alan.hamlett@gmail.com>
Patches and Suggestions
-----------------------
- Carlos Henrique Guardão Gandarez <gandarez@gmail.com>

View File

@ -0,0 +1,9 @@
# Changelog
## 1.0.0 (2020-11-15)
- Bugfixes
## 1.0.0 (2020-11-15)
- Birth

View File

@ -0,0 +1,63 @@
# WakaTime for Micro Editor
[![Coding time tracker](https://wakatime.com/badge/github/wakatime/WakaTime.novaextension.png?branch=master)](https://wakatime.com/badge/github/wakatime/WakaTime.novaextension)
Metrics, insights, and time tracking automatically generated from your programming activity.
## Installation
Using the plugin manager:
```shell
micro -plugin install wakatime
```
Or from within micro (must restart micro afterwards for the plugin to be loaded):
```shell
> plugin install wakatime
```
Or manually install by cloning this repo as `wakatime` into your `plug` directory:
```shell
git clone https://github.com/wakatime/micro-wakatime ~/.config/micro/plug/wakatime
```
For the first time you install WakaTime in your machine the Micro startup could delay a bit.
1. Enter your [api key](https://wakatime.com/api-key), then hit `Enter`.
> (If youre not prompted, press ctrl + e then type `wakatime.apikey`.)
2. Use Micro Editor and your coding activity will be displayed on your [WakaTime dashboard](https://wakatime.com).
## Usage
Visit https://wakatime.com to see your coding activity.
![Project Overview](https://wakatime.com/static/img/ScreenShots/Screen-Shot-2016-03-21.png)
## Configuring
Extension settings are stored in the INI file at `$HOME/.wakatime.cfg`.
More information can be found from [wakatime core](https://github.com/wakatime/wakatime#configuring).
## Troubleshooting
First, turn on debug mode:
1. Run micro with flag `-debug`.
> Logs are only generated when running with debug flag. Any other previous logs haven't been recorded.
Next, navigate to the folder you started micro and open `log.txt`.
Errors outside the scope of this plugin go to `$HOME/.wakatime.log` from [wakatime-cli][wakatime-cli-help].
The [How to Debug Plugins][how to debug] guide shows how to check when coding activity was last received from your editor using the [Plugins Status Page][plugins status page].
For more general troubleshooting info, see the [wakatime-cli Troubleshooting Section][wakatime-cli-help].
[wakatime-cli-help]: https://github.com/wakatime/wakatime#troubleshooting
[how to debug]: https://wakatime.com/faq#debug-plugins
[plugins status page]: https://wakatime.com/plugin-status

View File

@ -0,0 +1,36 @@
[{
"Name": "wakatime",
"Description": "Metrics, insights, and time tracking automatically generated from your programming activity",
"Website": "https://github.com/wakatime/micro-wakatime",
"Tags": ["productivity", "time tracking", "project", "git", "timer"],
"Versions": [
{
"Version": "1.0.0",
"Url": "https://github.com/wakatime/micro-wakatime/archive/1.0.0.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.0.1",
"Url": "https://github.com/wakatime/micro-wakatime/archive/1.0.1.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.0.2",
"Url": "https://github.com/wakatime/micro-wakatime/archive/1.0.2.zip",
"Require": {
"micro": ">=2.0.0"
}
},
{
"Version": "1.0.3",
"Url": "https://github.com/wakatime/micro-wakatime/archive/1.0.3.zip",
"Require": {
"micro": ">=2.0.0"
}
}
]
}]

View File

@ -0,0 +1,582 @@
VERSION = "1.0.3"
-- micro
local micro = import("micro")
local config = import("micro/config")
local util = import("micro/util")
local shell = import("micro/shell")
-- golang
local filepath = import("filepath")
local http = import("http")
local ioutil = import("io/ioutil")
local os2 = import("os")
local runtime = import("runtime")
-- wakatime
local userAgent = "micro/" .. util.SemVersion:String() .. " micro-wakatime/" .. VERSION
local s3Urlprefix = "https://wakatime-cli.s3-us-west-2.amazonaws.com/"
local lastFile = ""
local lastHeartbeat = 0
function init()
config.MakeCommand("wakatime.apikey", promptForApiKey, config.NoComplete)
micro.InfoBar():Message("WakaTime initializing...")
micro.Log("initializing WakaTime v" .. VERSION)
checkCli()
checkApiKey()
end
function postinit()
micro.InfoBar():Message("WakaTime initialized")
micro.Log("WakaTime initialized")
end
function checkCli()
if not cliUpToDate() then
downloadCli()
end
end
function checkApiKey()
if not hasApiKey() then
promptForApiKey()
end
end
function hasApiKey()
return getApiKey() ~= nil
end
function getApiKey()
return getSetting("settings", "api_key")
end
function getConfigFile()
return filepath.Join(os2.UserHomeDir(), ".wakatime.cfg")
end
function getSetting(section, key)
config, err = ioutil.ReadFile(getConfigFile())
if err ~= nil then
micro.InfoBar():Message("failed reading ~/.wakatime.cfg")
micro.Log("failed reading ~/.wakatime.cfg")
micro.Log(err)
end
lines = util.String(config)
currentSection = ""
for line in lines:gmatch("[^\r\n]+") do
line = string.trim(line)
if string.starts(line, "[") and string.ends(line, "]") then
currentSection = string.lower(string.sub(line, 2, string.len(line) -1))
elseif currentSection == section then
parts = string.split(line, "=")
currentKey = string.trim(parts[1])
if currentKey == key then
return string.trim(parts[2])
end
end
end
return ""
end
function setSetting(section, key, value)
config, err = ioutil.ReadFile(getConfigFile())
if err ~= nil then
micro.InfoBar():Message("failed reading ~/.wakatime.cfg")
micro.Log("failed reading ~/.wakatime.cfg")
micro.Log(err)
return
end
contents = {}
currentSection = ""
lines = util.String(config)
found = false
for line in lines:gmatch("[^\r\n]+") do
line = string.trim(line)
if string.starts(line, "[") and string.ends(line, "]") then
if currentSection == section and not found then
table.insert(contents, key .. " = " .. value)
found = true
end
currentSection = string.lower(string.sub(line, 2, string.len(line) -1))
table.insert(contents, string.rtrim(line))
elseif currentSection == section then
parts = string.split(line, "=")
currentKey = string.trim(parts[1])
if currentKey == key then
if not found then
table.insert(contents, key .. " = " .. value)
found = true
end
else
table.insert(contents, string.rtrim(line))
end
else
table.insert(contents, string.rtrim(line))
end
end
if not found then
if currentSection ~= section then
table.insert(contents, "[" .. section .. "]")
end
table.insert(contents, key .. " = " .. value)
end
_, err = ioutil.WriteFile(getConfigFile(), table.concat(contents, "\n"), 0700)
if err ~= nil then
micro.InfoBar():Message("failed saving ~/.wakatime.cfg")
micro.Log("failed saving ~/.wakatime.cfg")
micro.Log(err)
return
end
micro.Log("~/.wakatime.cfg successfully saved")
end
function downloadCli()
local io = import("io")
local zip = import("archive/zip")
local url = s3BucketUrl() .. "wakatime-cli.zip"
local zipFile = filepath.Join(resourcesFolder(), "wakatime-cli.zip")
micro.InfoBar():Message("downloading wakatime-cli...")
micro.Log("downloading wakatime-cli from " .. url)
_, err = os2.Stat(resourcesFolder())
if os2.IsNotExist(err) then
os.execute("mkdir " .. resourcesFolder())
end
-- download cli
local res, err = http.Get(url)
if err ~= nil then
micro.InfoBar():Message("error downloading wakatime-cli.zip")
micro.Log("error downloading wakatime-cli.zip")
micro.Log(err)
return
end
out, err = os2.Create(zipFile)
if err ~= nil then
micro.InfoBar():Message("error creating new wakatime-cli.zip")
micro.Log("error creating new wakatime-cli.zip")
micro.Log(err)
return
end
_, err = io.Copy(out, res.Body)
if err ~= nil then
micro.InfoBar():Message("error saving wakatime-cli.zip")
micro.Log("error saving wakatime-cli.zip")
micro.Log(err)
return
end
err = util.Unzip(zipFile, resourcesFolder())
os2.Remove(zipFile)
if err ~= nil then
micro.InfoBar():Message("failed to unzip wakatime-cli.zip")
micro.Log("failed to unzip wakatime-cli.zip")
micro.Log(err)
return
end
end
function resourcesFolder()
return filepath.Join(os2.UserHomeDir(), ".wakatime")
end
function cliPath()
local ext = ""
if isWindows() then
ext = ".exe"
end
return filepath.Join(resourcesFolder(), "wakatime-cli", ("wakatime-cli" .. ext))
end
function cliExists()
local _, err = os2.Stat(cliPath())
if os2.IsNotExist(err) then
return false
end
return true
end
function cliUpToDate()
if not cliExists() then
return false
end
local ioutil = import("ioutil")
local fmt = import("fmt")
local url = s3BucketUrl() .. "current_version.txt"
-- get current version from installed cli
local currentVersion, err = shell.ExecCommand(cliPath(), "--version")
if err ~= nil then
micro.InfoBar():Message("failed to determine current cli version")
micro.Log("failed to determine current cli version")
micro.Log(err)
return true
end
micro.Log("Current wakatime-cli version is " .. currentVersion)
micro.Log("Checking for updates to wakatime-cli...")
-- read version from S3
local res, err = http.Get(url)
if err ~= nil then
micro.InfoBar():Message("error retrieving wakatime-cli version from S3")
micro.Log("error retrieving wakatime-cli version from S3")
micro.Log(err)
return true
end
body, err = ioutil.ReadAll(res.Body)
if err ~= nil then
micro.InfoBar():Message("error reading all bytes from response body")
micro.Log("error reading all bytes from response body")
micro.Log(err)
return true
end
-- parse byte array to string
latestVersion = util.String(body)
if string.gsub(latestVersion, "[\n\r]", "") == string.gsub(currentVersion, "[\n\r]", "") then
micro.Log("wakatime-cli is up to date")
return true
end
micro.Log("Found an updated wakatime-cli v" .. latestVersion)
return false
end
function s3BucketUrl()
if runtime.GOOS == "darwin" then
return s3Urlprefix .. "mac-x86-64/"
elseif runtime.GOOS == "windows" then
return s3Urlprefix .. "windows-x86-" .. getOsArch() .. "/"
else
return s3Urlprefix .. "linux-x86-64/"
end
end
function getOsArch()
local arch
if (os2.getenv"os" or ""):match"^Windows" then
arch = os2.getenv"PROCESSOR_ARCHITECTURE"
else
arch = io.popen"uname -m":read"*a"
end
if (arch or ""):match"64" then
return "64"
else
return "32"
end
end
function isWindows()
return runtime.GOOS == "windows"
end
function onSave(bp)
onEvent(bp.buf.AbsPath, true)
return true
end
function onSaveAll(bp)
onEvent(bp.buf.AbsPath, true)
return true
end
function onSaveAs(bp)
onEvent(bp.buf.AbsPath, true)
return true
end
function onOpenFile(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onPaste(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectAll(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onDeleteLine(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorUp(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorDown(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorPageUp(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorPageDown(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorLeft(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorRight(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorStart(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onCursorEnd(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectToStart(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectToEnd(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectUp(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectDown(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectLeft(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectRight(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectToStartOfText(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectToStartOfTextToggle(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onWordRight(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onWordLeft(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectWordRight(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onSelectWordLeft(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onMoveLinesUp(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onMoveLinesDown(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onScrollUp(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function onScrollDown(bp)
onEvent(bp.buf.AbsPath, false)
return true
end
function enoughTimePassed(time)
return lastHeartbeat + 120000 < time
end
function onEvent(file, isWrite)
time = os.time()
if isWrite or enoughTimePassed(time) or lastFile ~= file then
sendHeartbeat(file, isWrite)
lastFile = file
lastHeartbeat = time
end
end
function sendHeartbeat(file, isWrite)
micro.Log("Sending heartbeat")
local isDebugEnabled = getSetting("settings", "debug"):lower()
local args = {"--entity", file, "--plugin", userAgent}
if isWrite then
table.insert(args, "--write")
end
if isDebugEnabled then
table.insert(args, "--verbose")
end
-- run it in a thread
shell.JobSpawn(cliPath(), args, nil, sendHeartbeatStdErr, sendHeartbeatExit)
end
function sendHeartbeatStdErr(err)
micro.Log(err)
micro.Log("Check your ~/.wakatime.log file for more details.")
end
function sendHeartbeatExit(out, args)
micro.Log("Last heartbeat sent " .. os.date("%c"))
end
function promptForApiKey()
micro.InfoBar():Prompt("API Key: ", getApiKey(), "api_key", function(input)
return
end, function(input, canceled)
if not canceled then
if isValidApiKey(input) then
setSetting("settings", "api_key", input)
else
micro.Log("Api Key not valid!")
end
end
end)
end
function isValidApiKey(key)
if key == "" then
return false
end
local regexp = import("regexp")
matched, _ = regexp.MatchString("(?i)^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$", key)
return matched
end
function ternary (cond, T, F)
if cond then return T else return F end
end
function string.starts(str, start)
return str:sub(1,string.len(start)) == start
end
function string.ends(str, ending)
return ending == "" or str:sub(-string.len(ending)) == ending
end
function string.trim(str)
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
function string.rtrim(str)
local n = #str
while n > 0 and str:find("^%s", n) do n = n - 1 end
return str:sub(1, n)
end
function string.split(str, delimiter)
t = {}
for match in (str .. delimiter):gmatch("(.-)" .. delimiter) do
table.insert(t, match);
end
return t
end

View File

@ -0,0 +1,4 @@
{
"autosu": true,
"colorscheme": "minimal-mistakes"
}