1

Regenerate nvim config

This commit is contained in:
2024-06-02 03:29:20 +02:00
parent 75eea0c030
commit ef2e28883d
5576 changed files with 604886 additions and 503 deletions

View File

@ -0,0 +1,32 @@
#!/nix/store/306znyj77fv49kwnkpxmb0j2znqpa8bj-bash-5.2p26/bin/sh
# SPDX-License-Identifier: Unlicense
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute
# this software, either in source code form or as a compiled binary, for any
# purpose, commercial or non-commercial, and by any means.
#
# In jurisdictions that recognize copyright laws, the author or authors of
# this software dedicate any and all copyright interest in the software to
# the public domain. We make this dedication for the benefit of the public
# at large and to the detriment of our heirs and successors. We intend this
# dedication to be an overt act of relinquishment in perpetuity of all
# present and future rights to this software under copyright law.
#
# 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 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.
#
# For more information, please refer to <https://unlicense.org/>
# A shim which acts as a command-line interface adapter for the busted test
# framework. If busted is installed using LuaRocks we cannot invoke it
# directly, but some tools might want to do so. This thin adapter can be used
# as a drop-in replacement for the busted executable.
eval $(luarocks path --lua-version 5.1 --bin) && busted $@

View File

@ -0,0 +1,86 @@
local yd = require 'yo-dawg'
describe('Attaching a strategy to a buffer', function()
local nvim
before_each(function()
nvim = yd.start()
-- Set up a tracking strategy
nvim:exec_lua([[
TSEnsure('lua', 'vim')
do
local track = require('rainbow-delimiters.strategy.track')
local noop = require('rainbow-delimiters.strategy.no-op')
the_strategy = track(noop)
end
vim.g.rainbow_delimiters = {
strategy = {
[''] = the_strategy
}
}]], {})
end)
after_each(function()
yd.stop(nvim)
end)
it('Does not attach a second time if the buffer is already attached', function()
-- Write buffer to a file
local tempfile = nvim:call_function('tempname', {})
nvim:call_function('writefile', {{'print((((("Hello, world!")))))', '-- vim:ft=lua'}, tempfile})
-- Edit the buffer multiple times, this will trigger attachment
for _ = 1, 3 do
nvim:cmd({cmd = 'edit', args = {tempfile}}, {})
nvim:cmd({cmd = 'filetype', args = {'detect'}}, {})
end
local count = nvim:exec_lua('return the_strategy.attachments[1]', {})
assert.is.equal(1, count, 'Buffer attached multiple times')
end)
it('Performs cleanup after a buffer is deleted', function()
local is_attached
nvim:buf_set_lines(0, 0, -1, true, {'print((((("Hello, world!")))))', '-- vim:ft=lua'})
nvim:cmd({cmd = 'filetype', args = {'detect'}}, {})
is_attached = nvim:exec_lua('return the_strategy.buffers[vim.fn.bufnr()] ~= nil', {})
assert.is_true(is_attached, 'Strategy must be attach to buffer')
-- Delete the buffer
nvim:cmd({cmd = 'bdelete', bang = true}, {})
is_attached = nvim:exec_lua('return the_strategy.buffers[vim.fn.bufnr()] ~= nil', {})
assert.is_false(is_attached, 'Strategy must not be attach to buffer')
end)
it('Detaches from the buffer and re-attached with the new language', function()
-- Switching the file type preserves the number of attachments, but
-- changes the language
for _, expected in ipairs({'lua', 'vim'}) do
nvim:buf_set_option(0, 'filetype', expected)
local lang = nvim:exec_lua('return the_strategy.buffers[vim.fn.bufnr()].lang', {})
local attachments = nvim:exec_lua('return the_strategy.attachments[1]', {})
assert.is.equal(1, attachments)
assert.is.equal(lang, expected)
end
end)
it('Unloads a buffer without raising errors', function()
-- Create two windows with different buffers, but with same file type
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:buf_set_lines(0, 0, -1, true, {'print(((("Hello world"))))', '-- vim:ft=lua'})
nvim:cmd({cmd = 'new'}, {})
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:buf_set_lines(0, 0, -1, true, {'print(((("Goodbye world"))))', '-- vim:ft=lua'})
local secondbuf = nvim:call_function('bufnr', {})
nvim:cmd({cmd = 'bdelete', args = {secondbuf}, bang = true}, {})
local errmsg = nvim:get_vvar('errmsg')
assert.is.equal('', errmsg)
end)
end)

View File

@ -0,0 +1,73 @@
local yd = require 'yo-dawg'
---Markdown document with Lua code inside a code block
local markdown_with_injected_lua = [[This is some Markdown
```lua
print(((('Hello world'))))
```
This is more markdown.]]
---Markdown document with Lua code outside a code block
local markdown_without_injected_lua = [[This is some Markdown
```lua
```
print(((('Hello world'))))
This is more markdown.]]
describe('Buffer Manipulation', function()
local nvim
before_each(function()
nvim = yd.start()
nvim:exec_lua('TSEnsure(...)', {'lua', 'vim', 'markdown'})
nvim:exec_lua([[
local rb = require 'rainbow-delimiters'
local global = rb.strategy.global
assert(nil ~= global)
vim.g.rainbow_delimiters = {
strategy = {
[''] = global
},
}
]], {})
end)
after_each(function()
yd.stop(nvim)
end)
it('Clears extmarks when moving line out of injected langauge', function()
nvim:exec_lua('TSEnsure(...)', {'lua', 'markdown'})
nvim:buf_set_lines(0, 0, -2, true, vim.fn.split(markdown_with_injected_lua, '\n'))
nvim:buf_set_option(0, 'filetype', 'markdown')
assert.nvim(nvim).has_extmarks_at(3, 5, 'lua')
-- Move Lua line out of code block
nvim:cmd({cmd = 'move', range = {4}, args = {5}}, {})
local given = vim.fn.join(nvim:buf_get_lines(0, 0, -2, true), '\n')
assert.is.equal(markdown_without_injected_lua, given)
assert.nvim(nvim).Not.has_extmarks_at(4, 5, 'lua')
end)
it('Adds extmarks when moving line into injected langauge', function()
nvim:exec_lua('TSEnsure(...)', {'lua', 'markdown'})
nvim:buf_set_lines(0, 0, -2, true, vim.fn.split(markdown_without_injected_lua, '\n'))
nvim:buf_set_option(0, 'filetype', 'markdown')
assert.nvim(nvim).Not.has_extmarks_at(4, 5, 'lua')
-- Move Lua line out of code block
nvim:cmd({cmd = 'move', range = {5}, args = {3}}, {})
local given = vim.fn.join(nvim:buf_get_lines(0, 0, -2, true), '\n')
assert.is.equal(markdown_with_injected_lua, given)
assert.nvim(nvim).has_extmarks_at(3, 5, 'lua')
end)
end)

View File

@ -0,0 +1,171 @@
local yd = require 'yo-dawg'
describe('User settings are respected', function()
local nvim
before_each(function()
nvim = yd.start()
end)
after_each(function()
yd.stop(nvim)
end)
describe('Strategy settings', function()
it('Applies the default strategy to all languages', function()
local strategy = 'default strategy'
nvim:exec2('let g:rainbow_delimiters = {"strategy": {"": "default strategy"}}', {})
local lua_strategy = nvim:exec_lua('return require("rainbow-delimiters.config").strategy.lua', {})
local c_strategy = nvim:exec_lua('return require("rainbow-delimiters.config").strategy.c', {})
assert.is.equal(strategy, lua_strategy)
assert.is.equal(strategy, c_strategy)
end)
it('Overrides the strategy for individual languages', function()
-- I had to use a trick here because we cannot compare dictionaries or
-- functions for identity between Vim script and Lua. Instead I
-- set a string as the strategy and compare for that equality.
nvim:exec_lua('require("rainbow-delimiters.default").strategy[""] = "default strategy"', {})
-- Override the strategy for Vim only
nvim:set_var('rainbow_delimiters', {strategy = {vim = 'vim strategy'}})
local lua_strategy = nvim:exec_lua('return require("rainbow-delimiters.config").strategy.lua', {})
local vim_strategy = nvim:exec_lua('return require("rainbow-delimiters.config").strategy.vim', {})
assert.is.equal('vim strategy', vim_strategy, 'Wrong strategy found for Vim')
assert.is.equal('default strategy', lua_strategy, 'Wrong strategy found for Lua')
end)
describe('Strategies can be thunks', function()
before_each(function()
-- Store strategies in global variables for later reference
nvim:exec_lua('noop = require("rainbow-delimiters").strategy.noop', {})
nvim:exec_lua('the_strategy = require("rainbow-delimiters.strategy.track")(noop)', {})
-- Set a thunk as the strategy
nvim:exec_lua([[
vim.g.rainbow_delimiters = {
strategy = {
[""] = function() return the_strategy end,
vim = function() return nil end
}
}]], {})
end)
it('Uses the strategy returned by the thunk', function()
nvim:exec_lua('TSEnsure(...)', {'lua'})
nvim:buf_set_lines(0, 0, -1, true, {'print "Hello world"', '-- vim:ft=lua'})
nvim:command('filetype detect')
local attachments = nvim:exec_lua('return the_strategy.attachments[1]', {})
assert.is.equal(1, attachments, 'The strategy should be attached to the Lua buffer')
end)
it('Does nothing if the thunk returns nil', function()
nvim:exec_lua('TSEnsure(...)', {'vim'})
nvim:buf_set_lines(0, 0, -1, true, {'echo "Hello world"', '" vim:ft=vim'})
nvim:command('filetype detect')
local attachments = nvim:exec_lua('return the_strategy.attachments[1]', {})
assert.is.equal(0, attachments, 'The strategy should not be attached to the Vim buffer')
end)
end)
end)
it('Overrides the query for an individual language', function()
-- Override the query for one language only
nvim:set_var('rainbow_delimiters', {query = {c = 'other-query'}})
local c_query = nvim:exec_lua('return require("rainbow-delimiters.config").query.c', {})
local lua_query = nvim:exec_lua('return require("rainbow-delimiters.config").query.lua', {})
assert.is.equal('other-query', c_query)
assert.is.equal('rainbow-delimiters', lua_query)
end)
it('Falls back to default highlighting if the highlight table is empty', function()
---The expected highlight groups in order
local hlgroups = {
'RainbowDelimiterRed',
'RainbowDelimiterYellow',
'RainbowDelimiterBlue',
'RainbowDelimiterOrange',
'RainbowDelimiterGreen',
'RainbowDelimiterViolet',
'RainbowDelimiterCyan',
}
-- Set highlight to empty list
nvim:set_var('rainbow_delimiters', {highlight = {}})
for i, expected in ipairs(hlgroups) do
local given = nvim:exec_lua('return require("rainbow-delimiters.config").highlight[...]', {i})
assert.is.equal(expected, given, string.format('Wrong highlight group at index %d', i))
end
end)
describe('White- and blacklist individual languages', function()
it('Has all languages enabled without configuration', function()
nvim:exec_lua('rbc = require("rainbow-delimiters.config")', {})
local lua_enabled = nvim:exec_lua('return rbc.enabled_for("lua")', {})
local vim_enabled = nvim:exec_lua('return rbc.enabled_for("vim")', {})
assert.is_true(lua_enabled, 'Lua should be enabled')
assert.is_true(vim_enabled, 'Vim script should be enabled')
end)
it('Has all languages enabled in blank configuration', function()
nvim:set_var('rainbow_delimiters', {})
nvim:exec_lua('rbc = require("rainbow-delimiters.config")', {})
local lua_enabled = nvim:exec_lua('return rbc.enabled_for("lua")', {})
local vim_enabled = nvim:exec_lua('return rbc.enabled_for("vim")', {})
assert.is_true(lua_enabled, 'Lua should be enabled')
assert.is_true(vim_enabled, 'Vim script should be enabled')
end)
it('Can whitelist individual file types by adding them to our configuration', function()
nvim:set_var('rainbow_delimiters', {whitelist = {'lua'}})
nvim:exec_lua('rbc = require("rainbow-delimiters.config")', {})
local lua_enabled = nvim:exec_lua('return rbc.enabled_for("lua")', {})
local vim_enabled = nvim:exec_lua('return rbc.enabled_for("vim")', {})
assert.is_true( lua_enabled, 'Lua should be enabled')
assert.is_false(vim_enabled, 'Vim script should be disabled')
end)
it('Can blacklist individual file types by adding them to our configuration', function()
nvim:set_var('rainbow_delimiters', {blacklist = {'vim'}})
nvim:exec_lua('rbc = require("rainbow-delimiters.config")', {})
local lua_enabled = nvim:exec_lua('return rbc.enabled_for("lua")', {})
local vim_enabled = nvim:exec_lua('return rbc.enabled_for("vim")', {})
assert.is_true( lua_enabled, 'Lua should be enabled')
assert.is_false(vim_enabled, 'Vim script should be disabled')
end)
end)
describe('The setup function sets configuration indirectly', function()
it('Can call the setup function', function()
nvim:exec_lua([[
require('rainbow-delimiters.setup').setup {
query = {
lua = 'rainbow-blocks'
}
}
]], {})
local lua_query = nvim:eval('g:rainbow_delimiters.query.lua')
assert.is.equal('rainbow-blocks', lua_query)
end)
it('Can call the table itset', function()
nvim:exec_lua([[
require('rainbow-delimiters.setup') {
query = {
lua = 'rainbow-blocks'
}
}
]], {})
local lua_query = nvim:eval('g:rainbow_delimiters.query.lua')
assert.is.equal('rainbow-blocks', lua_query)
end)
end)
end)

View File

@ -0,0 +1,182 @@
local yd = require 'yo-dawg'
describe('The Rainbow Delimiters public API', function()
local nvim
before_each(function()
nvim = yd.start()
-- Set up a tracking strategy
nvim:exec_lua([[
TSEnsure('markdown', 'lua', 'vim')
rb = require 'rainbow-delimiters'
vim.g.rainbow_delimiters = {
strategy = {
[''] = rb.strategy.global,
},
}]], {})
end)
after_each(function()
yd.stop(nvim)
end)
describe('Whether RB is enabled for a buffer at startup', function()
it('Is disabled for a buffer without file type', function()
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Is enabled for a supported language', function()
nvim:buf_set_option(0, 'filetype', 'lua')
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
describe('Blacklist', function()
before_each(function()
nvim:command('let g:rainbow_delimiters.blacklist = ["markdown"]')
end)
it('Is enabled for a not blacklisted language', function()
nvim:buf_set_option(0, 'filetype', 'lua')
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Is disabled for a blacklisted language', function()
nvim:buf_set_option(0, 'filetype', 'markdown')
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Is disabled for a blacklisted language with injected whitelisted language', function()
nvim:buf_set_lines(0, 0, -1, true, {
'This is Markdown',
'',
'```lua',
'print(((("This is Lua"))))',
'```',
'',
'More Markdown',
})
nvim:buf_set_option(0, 'filetype', 'markdown')
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
end)
describe('Whitelist', function()
before_each(function()
nvim:command('let g:rainbow_delimiters.whitelist = ["lua"]')
end)
it('Is disabled for a not whitelisted language', function()
nvim:buf_set_option(0, 'filetype', 'markdown')
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Is enabled for a whitelisted language', function()
nvim:buf_set_option(0, 'filetype', 'lua')
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Is enabled for whitelisted language with other language injected', function()
nvim:buf_set_lines(0, 0, -1, true, {
'print "This is Lua"',
'vim.cmd [[echo "This is Vim"]]',
})
nvim:buf_set_option(0, 'filetype', 'lua')
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Is disabled for not whitelisted language with injected whitelisted language', function()
nvim:buf_set_lines(0, 0, -1, true, {
'This is Markdown',
'',
'```lua',
'print(((("This is Lua"))))',
'```',
'',
'More Markdown',
})
nvim:buf_set_option(0, 'filetype', 'markdown')
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
end)
end)
describe('Manual toggling', function()
it('Can be disabled for a buffer', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.disable(0)', {})
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Can be turned back on', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.disable(0)', {})
nvim:exec_lua('rb.enable(0)', {})
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Can be toggled off', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.toggle(0)', {})
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Can be toggled on', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.toggle(0)', {})
nvim:exec_lua('rb.toggle(0)', {})
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Gets disabled idempotently', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.disable(0)', {})
nvim:exec_lua('rb.disable(0)', {})
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Gets enabled idempotently', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.disable(0)', {})
nvim:exec_lua('rb.enable(0)', {})
nvim:exec_lua('rb.enable(0)', {})
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
describe('Blacklist', function()
before_each(function()
nvim:command('let g:rainbow_delimiters.blacklist = ["markdown"]')
end)
it('Can be enabled for a blacklisted language', function()
nvim:buf_set_option(0, 'filetype', 'markdown')
nvim:exec_lua('rb.enable(0)', {})
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Can be toggled for a blacklisted language', function()
nvim:buf_set_option(0, 'filetype', 'markdown')
nvim:exec_lua('rb.toggle(0)', {})
assert.is.True(nvim:exec_lua('return rb.is_enabled()', {}))
end)
end)
describe('Whitelist', function()
before_each(function()
nvim:command('let g:rainbow_delimiters.whitelist = ["lua"]')
end)
it('Can be disabled for a whitelisted language', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.disable(0)', {})
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
it('Can be toggled for a whitelisted language', function()
nvim:buf_set_option(0, 'filetype', 'lua')
nvim:exec_lua('rb.toggle(0)', {})
assert.is.False(nvim:exec_lua('return rb.is_enabled()', {}))
end)
end)
end)
end)

View File

@ -0,0 +1,31 @@
local yd = require 'yo-dawg'
describe('We can disable rainbow delimiters for certain languages', function()
local nvim
before_each(function()
nvim = yd.start()
end)
after_each(function()
yd.stop(nvim)
end)
it('Does not run for a blacklisted language', function()
nvim:exec_lua('the_strategy = require("rainbow-delimiters.strategy.track")(require("rainbow-delimiters.strategy.no-op"))', {})
nvim:exec_lua('vim.g.rainbow_delimiters = {blacklist = {"lua"}, strategy = {[""] = the_strategy}}', {})
nvim:buf_set_lines(0, 0, -1, true, {'print "Hello world"', '-- vim:ft=lua'})
nvim:command('filetype detect')
local attachments = nvim:exec_lua('return the_strategy.attachments[1]', {})
assert.is.equal(0, attachments)
end)
it('Runs for a whitelisted language', function()
nvim:exec_lua('the_strategy = require("rainbow-delimiters.strategy.track")(require("rainbow-delimiters.strategy.no-op"))', {})
nvim:exec_lua('vim.g.rainbow_delimiters = {whitelist = {"lua"}, strategy = {[""] = the_strategy}}', {})
nvim:buf_set_lines(0, 0, -1, true, {'print "Hello world"', '-- vim:ft=lua'})
nvim:command('filetype detect')
local attachments = nvim:exec_lua('return the_strategy.attachments[1]', {})
assert.is.equal(1, attachments)
end)
end)

View File

@ -0,0 +1,99 @@
local yd = require 'yo-dawg'
describe('The global strategy', function()
local nvim
before_each(function()
nvim = yd.start()
nvim:exec_lua('TSEnsure(...)', {'lua', 'vim'})
nvim:exec_lua([[
local rb = require 'rainbow-delimiters'
local track = require('rainbow-delimiters.strategy.track')
local global = rb.strategy.global
assert(nil ~= global)
the_strategy = track(global)
vim.g.rainbow_delimiters = {
strategy = {
[''] = the_strategy
}, query = {
},
}
]], {})
end)
after_each(function()
yd.stop(nvim)
end)
it('Does not reactivate when making changes', function()
nvim:buf_set_lines(0, 0, -1, true, {'print({{{{{}}}}})', '-- vim:ft=lua'})
nvim:buf_set_option(0, 'filetype', 'lua')
assert.nvim(nvim).has_extmarks_at(0, 5, 'lua')
nvim:call_function('rainbow_delimiters#disable', {0})
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
-- Add a new pair of curly braces
-- (jump to first column, find the first closing brace, insert new pair)
local keys = vim.api.nvim_replace_termcodes('gg0f}i{}<esc>', true, false, true)
nvim:feedkeys(keys, 'n', false)
assert.is.same({'print({{{{{{}}}}}})'}, nvim:buf_get_lines(0, 0, 1, true))
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
assert.is.equal(0, nvim:exec_lua('return the_strategy.attachments[1]', {}))
end)
it('Ignores blacklisted injected languages', function()
nvim:exec_lua('vim.g.rainbow_delimiters.blacklist = {...}', {'vim'})
nvim:buf_set_lines(0, 0, -1, true, {
'print {{{{{}}}}}',
'vim.cmd [[',
' echo string(1 + (2 + (3 + 4)))',
']]',
'-- vim:ft=lua'
})
nvim:buf_set_option(0, 'filetype', 'lua')
-- The Lua code is highlighted, the Vim code not
assert.nvim(nvim).has_extmarks_at(0, 6, 'lua')
assert.nvim(nvim).Not.has_extmarks_at(2, 13, 'vim')
end)
it('Ignores non-whitelisted injected languages', function()
nvim:exec_lua('vim.g.rainbow_delimiters.whitelist = {...}', {'lua'})
nvim:buf_set_lines(0, 0, -1, true, {
'print {{{{{}}}}}',
'vim.cmd [[',
' echo string(1 + (2 + (3 + 4)))',
']]',
'-- vim:ft=lua'
})
nvim:buf_set_option(0, 'filetype', 'lua')
-- The Lua code is highlighted, the Vim code not
assert.nvim(nvim).has_extmarks_at(0, 6, 'lua')
assert.nvim(nvim).Not.has_extmarks_at(2, 13, 'vim')
end)
it('Applies highlighting to nested code', function()
-- See also https://github.com/HiPhish/rainbow-delimiters.nvim/pull/92
local content = [[local function foo()
return {
a = print('a'),
}
end
return foo]]
nvim:exec_lua('vim.g.rainbow_delimiters.query.lua = "rainbow-blocks"', {})
nvim:buf_set_lines(0, 0, -1, true, vim.fn.split(content, '\n'))
nvim:buf_set_option(0, 'filetype', 'lua')
-- Insert the line " b = print('b'),"
nvim:win_set_cursor(0, {3, 0})
local keys = vim.api.nvim_replace_termcodes("ob = print('b'),<esc>", true, false, true)
nvim:feedkeys(keys, '', false)
assert.nvim(nvim).has_extmarks_at(2, 11, 'lua')
assert.nvim(nvim).has_extmarks_at(3, 11, 'lua')
end)
end)

View File

@ -0,0 +1,46 @@
local yd = require 'yo-dawg'
describe('The local strategy', function()
local nvim
before_each(function()
nvim = yd.start()
nvim:exec_lua('TSEnsure(...)', {'lua', 'vim'})
nvim:exec_lua([[
local rb = require 'rainbow-delimiters'
local track = require('rainbow-delimiters.strategy.track')
local strategy = rb.strategy['local']
assert(nil ~= strategy)
the_strategy = track(strategy)
vim.g.rainbow_delimiters = {
strategy = {
[''] = the_strategy
}
}
]], {})
end)
after_each(function()
yd.stop(nvim)
end)
it('Does not reactivate when making changes', function()
nvim:buf_set_lines(0, 0, -1, true, {'print({{{{{}}}}})', '-- vim:ft=lua'})
nvim:win_set_cursor(0, {1, 5})
nvim:buf_set_option(0, 'filetype', 'lua')
assert.nvim(nvim).has_extmarks_at(0, 5, 'lua')
nvim:call_function('rainbow_delimiters#disable', {0})
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
-- Add a new pair of curly braces
-- (jump to first column, find the first closing brace, insert new pair)
local keys = vim.api.nvim_replace_termcodes('gg0f}i{}<esc>', true, false, true)
nvim:feedkeys(keys, 'n', false)
assert.is.same({'print({{{{{{}}}}}})'}, nvim:buf_get_lines(0, 0, 1, true))
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
assert.is.equal(0, nvim:exec_lua('return the_strategy.attachments[1]', {}))
end)
end)

View File

@ -0,0 +1,64 @@
local yd = require 'yo-dawg'
describe('We can use functions to turn rainbow delimiters off and on again.', function()
local nvim
before_each(function()
nvim = yd.start()
nvim:exec_lua('the_strategy = require("rainbow-delimiters.strategy.global")', {})
nvim:exec_lua('TSEnsure(...)', {'lua'})
nvim:buf_set_lines(0, 0, -1, true, {'print((((("Hello, world!")))))'})
nvim:buf_set_option(0, 'filetype', 'lua')
end)
after_each(function()
yd.stop(nvim)
end)
it('Does highlighting initially', function()
assert.nvim(nvim).has_extmarks_at(0, 5, 'lua')
end)
it('Disables rainbow delimiters', function()
nvim:call_function('rainbow_delimiters#disable', {0})
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
end)
it('Remains disabled when disabling twice', function()
nvim:call_function('rainbow_delimiters#disable', {0})
nvim:call_function('rainbow_delimiters#disable', {0})
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
end)
it('Turns rainbow delimiters back on', function()
nvim:call_function('rainbow_delimiters#disable', {0})
nvim:call_function('rainbow_delimiters#enable', {0})
assert.nvim(nvim).has_extmarks_at(0, 5, 'lua')
end)
it('Remains enabled when enabling twice', function()
nvim:call_function('rainbow_delimiters#disable', {0})
nvim:call_function('rainbow_delimiters#enable', {0})
nvim:call_function('rainbow_delimiters#enable', {0})
assert.nvim(nvim).has_extmarks_at(0, 5, 'lua')
end)
it('Can be disabled after being enabled', function()
nvim:call_function('rainbow_delimiters#disable', {0})
nvim:call_function('rainbow_delimiters#enable', {0})
nvim:call_function('rainbow_delimiters#disable', {0})
assert.nvim(nvim).Not.has_extmarks_at(0, 5, 'lua')
end)
it('Can be enabled after being disabled twice', function()
nvim:call_function('rainbow_delimiters#disable', {0})
nvim:call_function('rainbow_delimiters#disable', {0})
nvim:call_function('rainbow_delimiters#enable', {0})
assert.nvim(nvim).has_extmarks_at(0, 5, 'lua')
end)
end)

View File

@ -0,0 +1,33 @@
---
// component import
import MainLayout from "../../layouts/MainLayout.astro";
import PostCard from "../../components/PostCard.astro";
// utils imports
import { formatBlogPosts } from "../../js/utils";
const allPosts = await Astro.glob("./*.md");
const formattedPosts = formatBlogPosts(allPosts, {});
---
<MainLayout title="My Blog">
<section class="container" aria-label="New Blog Posts">
<h1 class="h1">New Blog Posts</h1>
<div class="post-container">
{
formattedPosts.map((post) => (
<PostCard
frontmatter={post.frontmatter}
url={post.url}
tagType="h2"
/>
))
}
</div>
</section>
<!-- <PostCard
frontmatter={allPosts[0].frontmatter}
url={allPosts[0].url}
tagType="h2"
/> -->
</MainLayout>

View File

@ -0,0 +1,30 @@
#!/nix/store/306znyj77fv49kwnkpxmb0j2znqpa8bj-bash-5.2p26/bin/bash
# Command substitution
echo $(basedir $(pwd))
# Variable expansion
echo ${FOO:-${BAR:-${BAZ}}}
# Test expression (using the `test` command)
if [ -d "herp/derp/" ]; then
echo "Yay"
fi
# Test expression (bashism)
if [[ -d "herp/derp/" ]]; then
echo "Yay"
fi
# Sub-shells
(true; false; (true; true; (false; true)))
person() {
array=(
[Alice]="$((2 ^ 10))"
[Bob]=2048
)
echo "${array[$1]}"
}
person "Alice"

View File

@ -0,0 +1,82 @@
#include <stdio.h>
#define PI 3.14
/* These aren't highlight correctly. A problem with the parser? */
#define TESTMACRO (-1)
#define min(X,Y) ((X) < (Y) ? (X) : (Y))
/* Declaration with parentheses, a function pointer */
static void (*callback)(int);
int c_init() { return 1; }
/* Macro type specifier */
#define Map int Foo
static Map(char *c_str) {return 4;}
typedef enum {
E1,
E2,
E3
// comment
} Myenum;
/* A function declaration */
int add(int, int);
struct Point2D {
int x;
int y;
};
/* Compound literal expression */
struct Point2D v = (struct Point2D){ 0, 0 };
/* A function definition */
int add(int x, int y) {
if (!y) {
if (1) {
if (1) {
if (1) {
return x;
}
}
}
}
while (0) {
while (0) {
while (0) {
;
}
}
}
for (int i = 0; i < 0; i++) {
for (int j = 0; j < 0; j++) {
for (int k = 0; k < 0; k++) {
;
}
}
}
return add(x + 1, y - 1);
}
float int2float(int i) {
return (float)i;
}
int main(int argc, char *argv[]) {
int a = 10, b = 5;
int result = add(a, b);
printf("The sum of %d and %d is %d", ((((a)))), b, result);
int indices[] = {0, };
int i = indices[indices[indices[indices[indices[indices[0]]]]]];
#if 0
/* A language server may mark this block semantically as a comment */
printf("The sum of %d and %d is %d", ((((a)))), b, result);
#endif
return 0;
}

View File

@ -0,0 +1,8 @@
using System;
// A version of the classic "Hello World" program
class Program {
static void Main() {
Console.WriteLine("Hello, world!");
}
}

View File

@ -0,0 +1,17 @@
using System;
// Arrays and nested arrays
class Program {
static void Main() {
int[,,] array3D = new int[,,] {
{ {1}, {2} },
{ {3}, {4} },
{ {5}, {6} },
{ {7}, {8} },
};
int[] indices = new int[] {0};
int i = array3D[0, 0, 0];
var implicitArray = new[] { "" };
int j = indices[indices[indices[indices[0]]]];
}
}

View File

@ -0,0 +1,8 @@
internal class TestAttribute : Attribute { }
[Test()]
public class Person
{
[Test()]
public string? Name { get; set; }
}

View File

@ -0,0 +1,14 @@
using System;
public class A<T> { }
public struct B<T> { }
public interface C<T> : A<IEnumerable<T>> { }
// Nested generic parameters
class Program {
static void Main(List<List<List<T>>> l) {
}
}

View File

@ -0,0 +1,21 @@
using System;
// Nested loops
class Program {
static int[] integers = {0, 1, 2, 3};
static void Main() {
foreach (int i in integers) {
foreach (int i in integers) {
foreach (int i in integers) {
foreach (int i in integers) {
while (false) {
Console.WriteLine("Hello, world!");
}
}
}
}
}
}
}

View File

@ -0,0 +1,39 @@
public class TestClass
{
public string? Name { get; set; }
public int[][]? MultiDimArray { get; set; }
private string MergeLines(IEnumerable<IEnumerable<string>> sections)
{
return string.Join(",", sections.SelectMany(t => t));
}
private void LoopTest()
{
foreach (var item in new string[0]) { }
for (int i = 0; i < 0; i++) { }
while (false) { }
do { } while (false);
}
private void Interpolation()
{
var passTitle = "123";
if (true) {
System.Console.WriteLine($"== {passTitle} ==");
}
}
private void AnonymousObject()
{
var a = new { Test = 123, };
}
private (int a, float b, (int c, float d)) TupleExpressions()
{
return (1, 2, (3, 4));
}
}

View File

@ -0,0 +1,8 @@
using System;
// Nested parenthesized expressions
class Program {
static void Main() {
var i = (((((1 + 2))) + ((((3))))));
}
}

View File

@ -0,0 +1,55 @@
public static class SwitchTest
{
private static string GenericFirstCharProcessing(
this string input,
Func<string, string> firstCharProcessor
) =>
input switch
{
null => throw new ArgumentNullException(nameof(input)),
"" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
_ => firstCharProcessor(input[0].ToString()) + input.Substring(1)
};
private static void T()
{
var defaultInt = default(int);
try { }
catch (Exception e) when (true) { }
finally { }
using (var stream = new Stream()) { }
lock (new string()) { }
var name = "test";
switch (name)
{
case "aab":
{
break;
}
case var o when (o?.Trim().Length ?? 0) == 0:
case "test":
break;
default:
break;
}
int c = (int)b; // explicit conversion from long to int
Type[] t = { typeof(int), };
sizeof(int);
int AllBits = unchecked((int)0xFFFFFFFF);
int AllBits = checked((int)0xFFFFFFFF);
Span<long> span5 = stackalloc[] { 11, 12, 13 };
}
enum Color
{
Red,
Blue,
Green
}
}

View File

@ -0,0 +1,9 @@
(defn fn-name "docs" [a0 a1 & xz]
[
"some _text_ with parens #() #{} {} [] (#())"
'(#(identity ""))
[[[], [[]]], #(:k {}), #{{}, ""}, '((())), `({})]
]
)
(fn-name 1 2 3 4)

View File

@ -0,0 +1,16 @@
(defun add (x y)
"A silly way to add two numbers recursively."
(if (zerop y)
x
(add (incf x)
(decf y))))
(defmacro foo (a &rest rest)
`(format t "~A~%" (list ,a ,@rest)))
;;; The LOOP macro has its own node type
(loop repeat 3
do (print "Hello world"))
'(((a . b)))
'((((a b . c))))

View File

@ -0,0 +1,79 @@
#include <vector>
#include <cstdio>
namespace herp {
const int derpiness = 9000;
int get_derpiness() {
return derpiness;
}
}
/* A function declaration */
int add(int, int);
// Structure and class definitions
struct Point2D {
public:
int x;
int y;
};
class Point3D {
public:
int x;
int y;
int z;
};
/* A function definition */
int add(int x, int y) {
if (!y) {
if (1) {
if (1) {
if (1) {
return x;
}
}
}
}
while (0) {
while (0) {
while (0) {
;
}
}
}
for (int i = 0; i < 0; i++) {
for (int j = 0; j < 0; j++) {
for (int k = 0; k < 0; k++) {
;
}
}
}
return add(x + 1, y - 1);
}
template <typename T> T myMax(T x, T y) {
return (x > y) ? x : y;
}
float int2float(int i) {
return (float)i;
}
void do_nothing_with_vector(std::vector<std::vector<std::vector<int>>> v) {
return;
}
int main(int argc, char *argv[]) {
auto a {10};
auto b (5);
auto result = add(a, b);
printf("The sum of %d and %d is %d", ((((a)))), b, result);
int indices[] = {0, };
auto i = indices[indices[indices[indices[indices[indices[0]]]]]];
return 0;
}

View File

@ -0,0 +1,22 @@
:root {
@media (prefers-color-scheme: dark) {
--color-bg: #3b4252;
--color-fg: #eceff4;
--color-gray: #434c5e;
--color-blue: #81a1c1;
}
}
li:has(input[type="checkbox"]) {
list-style-type: none;
}
.foo {
color: #ffffff;
}
@media (not (color)) {
.foo {
color: #ffffff;
}
}

View File

@ -0,0 +1,87 @@
#include <vector>
#include <iostream>
#include <cstdio>
/* A function declaration */
int add(int, int);
// Structure and class definitions
struct Point2D {
public:
int x;
int y;
};
class Point3D {
public:
int x;
int y;
int z;
};
/* A function definition */
int add(int x, int y) {
if (!y) {
if (1) {
if (1) {
if (1) {
return x;
}
}
}
}
while (0) {
while (0) {
while (0) {
;
}
}
}
for (int i = 0; i < 0; i++) {
for (int j = 0; j < 0; j++) {
for (int k = 0; k < 0; k++) {
;
}
}
}
return add(x + 1, y - 1);
}
template <typename T> T myMax(T x, T y) {
return (x > y) ? x : y;
}
float int2float(int i) {
return (float)i;
}
void do_nothing_with_vector(std::vector<std::vector<std::vector<int>>> v) {
return;
}
__global__ void add_array(int *a, int size) {
int i = threadIdx.x + blockIdx.x * blockDim.x;
if (i < size) {
a[i] += 1;
}
}
void call_device() {
int *dev_a;
cudaMalloc(&dev_a, 10 * sizeof(int));
add_array<<<1, 10, 1>>>(dev_a, 10);
cudaFree(dev_a);
}
int main(int argc, char *argv[]) {
auto a {10};
auto b (5);
auto result = add(a, b);
printf("The sum of %d and %d is %d", ((((a)))), b, result);
int indices[] = {0, };
auto i = indices[indices[indices[indices[indices[indices[0]]]]]];
return 0;
}

View File

@ -0,0 +1,25 @@
package main
import (
"strings"
)
HumanA: {
name: "Bob"
description: "A human named \(strings.ToUpper(name))"
}
_#ComplexType: (int | string) | bool
ok: _#ComplexType & 13
numList: [...int] & [ 1, 2, 3, 4 ]
elems: [Name=_]: {name: Name}
elems: {
one: {}
two: {}
}
_env: string | *"dev" @tag(env,type=string)
host: "\(_env).example.com"

View File

@ -0,0 +1,55 @@
import 'package:flutter/material.dart';
class ExampleWidget extends StatelessWidget {
final String title;
final String subtitle;
final String image;
final String id;
const WidgetItem({
super.key,
required this.id,
required this.title,
required this.subtitle,
required this.image,
});
@override
Widget build(BuildContext context) {
final data = {['field'] = "<value>"};
final theme = Theme.of(context);
return GestureDetector(
onTap: () => context.go('/example/$id'),
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const Expanded(
child: Image(
image: AssetImage('assets/image.jpg'),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
),
),
const SizedBox(height: 8),
Text(subtitle),
],
),
)
],
),
),
),
);
}
}

View File

@ -0,0 +1,35 @@
defmodule Regular do
@moduledoc """
A dummy test module.
"""
def first_plus_five([head | tail]) do
IO.puts "The first value is #{head}"
head + (((1 + (2 + 3))))
end
def first_plus_five({a, b}) do
IO.puts "The first value is #{a}"
a + (((1 + (2 + 3))))
end
def first_plus_five(<<r, g, b>>) do
IO.puts "The first value is #{r}"
r + (((1 + (2 + 3))))
end
def first_plus_five(%{head => _}) do
IO.puts "The first value is #{head}"
head + (((1 + (2 + 3))))
end
defp accessLookup(map, x) do
map[map[map[map[x]]]]
end
end
# Keyword list syntactic sugar
IO.puts inspect([a: 1, b: [c: 3, d: [e: 5, f: []]]])
# Map syntactic sugar
IO.puts inspect(%{a => 1, b => %{c => 3, d => %{e => 5, f => %{}}}})

View File

@ -0,0 +1,51 @@
module Regular exposing (CustomType(..))
import Browser exposing (UrlRequest(..))
import Url.Parser exposing ((</>), (<?>))
type CustomType a
= CustomType a
type alias NestedRecordOfCustomType a =
{ a : ( Int, List (Maybe ( Int, CustomType a )) )
, b : ( Int, { c : CustomType a } )
, d : { f : { g : String } }
}
nestedTypeExpr : Int -> (Int -> Int) -> (Int -> (Int -> Int))
nestedTypeExpr x y =
\z -> y
nestedListPatternFunction : List (List ( Int, List ( Int, String ) )) -> List ( String, Int )
nestedListPatternFunction list =
List.concatMap (\( _, strings ) -> List.map (\( a, b ) -> ( b, a )) strings) (List.concat list)
unwrapCustomType : { b | c : Int } -> CustomType (CustomType { a : Int }) -> Int
unwrapCustomType { c } (CustomType (CustomType ({ a } as b))) =
(a + (c * 1)) * (a - (a + (b.a * 1)))
patternMatchNestedListOfRecords : List (List (NestedRecordOfCustomType Int)) -> Maybe (List (List (NestedRecordOfCustomType Int)))
patternMatchNestedListOfRecords list =
case [ list ] of
[ [ [ { a, b } ] ] ] ->
case ( a, b ) of
( ( 1, [ Just ( 1, ct ) ] ), ( 2, { c } ) ) ->
Just
[ [ { a = ( 1, [ Just ( 1, c ) ] )
, b = ( 2, { c = ct } )
, d = { f = { g = "test" } }
}
]
]
_ ->
Nothing
_ ->
Nothing

View File

@ -0,0 +1,96 @@
(print (.. "foo" "bar"))
(local abcd { :a { :b { :c { :d {}}}}})
(let [one 1 two 2 tbl { : one : two}]
tbl)
;;; Destructuring a table binding
(let [{:a {:b {:c {:d d}}}} abcd]
(print d))
[0 [1 [2 [3 []]]]]
;; NOTE: the single ":" on the second line could also be a delimiter
{:a :b
: abcd}
;;; Get AST root
(fn get-root [bufnr]
;;; Get current buffer
(local bufnr (or bufnr
(vim.api.nvim_get_current_buf)))
;;; Early return if not in a Nix file
(when (not= (. vim :bo bufnr :filetype)
:nix)
(vim.notify_once "This is meant to be used with Nix files")
(lua "return nil"))
(let [parser (vim.treesitter.get_parser bufnr :nix {})
[tree] (parser:parse)]
(tree:root)))
(macro -m?> [val ...]
"Thread (maybe) a value through a list of method calls"
(assert-compile
val
"There should be an input value to the pipeline")
(var res# (gensym))
(var res `(do (var ,res# ,val)))
(each [_ [f & args] (ipairs [...])]
(table.insert
res
`(when (and (not= nil ,res#)
(not= nil (. ,res# ,f)))
(set ,res# (: ,res# ,f ,(unpack args))))))
res)
(fn add-partial [x]
(fn [y]
(fn [z] (+ x y z))))
(λ sub-partial [x]
(λ [y]
(λ [z] (- x y z))))
(let [a 1]
(let [b 2]
(let [c 3]
(+ a b c))))
(let [t {:a 4 :b 8}]
(set t.a 2) t)
(let [(a b c) (values 1 2 3)]
(+ a b c))
(match (add-partial 5 6 7)
[1 [2] 3] (print "osuhow")
12 :dont
x x)
(each [key value (pairs {"a" 1 "b" 2})]
(print key value))
(for [i 1 10]
(print i))
(var numbers [1 2 3 4 5 6])
(collect [_ x (ipairs numbers)]
(values x true))
(icollect [_ x (ipairs numbers)]
(+ x 1))
(fcollect [i 0 10 2]
(if (> i 2) (* i i)))
(accumulate [acc 0 _ x (ipairs numbers)]
(+ acc x))
(faccumulate [n 0 i 1 5] (+ n i)) ; => 15
(#(faccumulate [n 1 i 1 $] (* n i)) 5) ; => 120 (factorial!)
((hashfn (faccumulate [n 1 i 1 $] (* n i))) 5) ; => 120 (factorial!)

View File

@ -0,0 +1,7 @@
set -l shells "$SHELL" /bin/{zsh,bash,sh} (which nu) /usr/bin/xonsh
echo "Your first few shells is $shells[1..3]"
if set -q shells[10]
echo "You defined at least 10 shells"
end

View File

@ -0,0 +1,108 @@
package main
import (
"fmt"
"sort"
"regexp"
)
const (
TOOEXPENSIVE = 200
)
type Wine struct {
Name string
Produced int
Price float32
InStock bool
}
func (w Wine) String() string {
return fmt.Sprintf("Name: %s, Produced: %d, Cost: %0.2f", w.Name, w.Produced, w.Price)
}
type ByProduced []Wine
func (a ByProduced) Len() int { return len(a) }
func (a ByProduced) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByProduced) Less(i, j int) bool { return a[i].Produced < a[j].Produced }
func isFloat32(i interface{}) bool {
switch v := i.(type) {
case float32:
fmt.Printf("%v is a float32", i.(float32))
return true
default:
fmt.Printf("%v is not a float32", v)
return false
}
}
func SumUp[K comparable, V float32](v1 V, v2 V) V {
return v1 + (((v2)))
}
func main() {
var re = regexp.MustCompile(`x`)
wines := []Wine{
{"Cabernet Sauvignon", 1991, 200.0, true},
{"Merlot", 1939, 500.0, true},
{"Zinfandel", 1982, 120.0, false},
}
fmt.Println(len(wines[:2]))
stringArr := [4]string{"a", "b", "c", "d"}
addons := map[string]struct {
Item string
Price float32
}{
"Zinfandel": {Item: "chocolate", Price: 10.0},
"Cabernet Sauvignon": {Item: "cake", Price: 12.0},
}
var (
nonexpensive []Wine
)
LABEL:
for {
for {
for {
for {
for {
sort.Sort(ByProduced(wines))
for _, wine := range wines {
switch wprice := wine.Price; {
case wprice > TOOEXPENSIVE:
// Too expensive
default:
nonexpensive = append(nonexpensive, wine)
}
}
break LABEL
}
}
}
}
}
for _, wine := range nonexpensive {
if wine.InStock {
if wine.InStock {
if wine.InStock {
if wine.InStock {
if isFloat32(wine.Price) {
fmt.Println("I can sell you", wine)
if val, ok := addons[wine.Name]; ok {
fmt.Println("And I have a bundle with ", val.Item, " if you would like ? you can get it for ", SumUp[float32](wine.Price, val.Price))
}
}
}
}
}
}
}
}

View File

@ -0,0 +1,45 @@
{-# LANGUAGE RecordWildCards #-}
module ExampleModule
( ExampleRecord (..)
, someRecord
, mkRec
, mkRec2
, mkRec3
, mkRec4
) where
import Data.Maybe hiding (fromJust)
import Data.Functor ((<$>))
data ExampleRecord
= ExampleRecord
{ name :: String
, mmUnit :: Maybe (Maybe ())
}
deriving (Eq, Show)
getName :: ExampleRecord -> String
getName ExampleRecord {..} = name
someRecord :: ExampleRecord
someRecord = anotherRecord { name = "xyz" }
where anotherRecord = mkRec "" Nothing
mkRec :: String -> Maybe (Maybe a) -> ExampleRecord
mkRec name (Just (Just _)) = ExampleRecord {..}
where mmUnit = Just $ Just ()
mkRec name (Just _) = ExampleRecord {..}
where mmUnit = Just Nothing
mkRec name _ = ExampleRecord {..}
where mmUnit = Nothing
mkRec2 :: String -> String -> ExampleRecord
mkRec2 first last = mkRec (first <> " " <> last) Nothing
mkRec3 :: [Char] -> ExampleRecord
mkRec3 (a:b:c:_) = mkRec [a, b, c] Nothing
mkRec3 _ = mkRec "" Nothing
mkRec4 :: (String, String) -> ExampleRecord
mkRec4 (a, b) = mkRec (a <> b) Nothing

View File

@ -0,0 +1,72 @@
terraform {
required_providers {
provider1 = {
source = "provider1"
version = "0.1.3"
}
}
}
data "terraform_remote_state" "test_remotestate" {
backend = "test"
config = {
storage_account_name = "abc"
container_name = "terraform-state"
key = "prod.terraform.tfstate"
}
}
resource "provider_role_grants" "admins_role_grants" {
provider = provider.security_admin
role_name = provider_role.admins_role.name
users = [provider_user.user1.name]
roles = [provider_role.role2.name]
}
resource "provider_grant" "usage_grants" {
for_each = toset(["USAGE", "TEST"])
privilege = each.key
roles = [provider_role.role2.name]
}
resource "example" "binary_expressions" {
cond1 = (0*1) ? 1 : "foobar"
bin1 = ((!(1)+2)%3)*4
}
resource "example" "for_expressions" {
for1 = { for i, v in ["a", "a", "b"] : v => i... }
for2 = [ for k, v in x : "${k}-${v}" ]
}
variable "timestamp" {
type = string
validation {
# formatdate fails if the second argument is not a valid timestamp
condition = can(formatdate("", var.timestamp))
error_message = "Hello, %{ if var.name != "" }${var.name}%{ else }unnamed%{ endif }!"
}
}
block {
sample = <<-EOT
%{ for ip in aws_instance.example[*].private_ip }
server ${ip}
%{ endfor }
EOT
}
resource "terraform_data" "cluster" {
# Replacement of any instance of the cluster requires re-provisioning
triggers_replace = aws_instance.cluster.[*].id
# Bootstrap script can run on any instance of the cluster
# So we just choose the first in this case
connection {
host = aws_instance.cluster.[0].public_ip
}
}
# vim:ft=hcl

View File

@ -0,0 +1,264 @@
---@class ExpectedRainbowHighlight
---@field line number 0-based index of the line to be highlighted
---@field column number 0-based index of the character to be highlighted
---@field rainbow_level string The expected level of the rainbow to use in the highlight
---@param source_code_lines string[]
---@return ExpectedRainbowHighlight[]
local function get_expected_highlights(source_code_lines)
---@type ExpectedRainbowHighlight[]
local expected_highlights = {}
for line_index, line in ipairs(source_code_lines) do
local matches = string.find(line, "hl[%s%d]*")
if matches ~= nil then
for char_index = 1, #line do
local char = line:sub(char_index, char_index)
if string.match(char, "%d") then
table.insert(expected_highlights, {
-- NOTE: subtract 1 to get the index to be 0-based,
-- and another 1 because the hl-line describes the
-- expected highlights for the line above the hl-line
line = line_index - 2,
column = char_index - 1,
rainbow_level = char,
})
end
end
end
end
return expected_highlights
end
---Returns the name of the rainbow highlight group for a given level
---@param level string
---@return string
local function get_rainbow_highlight_group_name(level)
return "rainbowcol" .. level
end
---Prepares a line with the invalid column marked by ^.
---Used in error reporting.
---@param invalid_column number 0-based
---@return string
local function get_error_marker_line(invalid_column)
return string.rep(" ", invalid_column) .. "^"
end
---Prints the line with an error marker line that points to some character.
---@param line string The line to print
---@param line_number number The line number to be printed
---@param error_marker_column number 0-based column number to place the error marker
local function print_line_with_error_marker(line, line_number, error_marker_column)
local line_number_width = 3
print(string.format("%" .. line_number_width .. "d: %s", line_number, line))
print(
string.format(
"%" .. line_number_width .. "s %s\n",
"",
get_error_marker_line(error_marker_column)
)
)
end
---@class HighlightedSymbol
---@field line number 0-based
---@field column number 0-based
---@field hl_group string
---@param extmarks table[] Extmark returned from nvim_buf_get_extmarks
---@return HighlightedSymbol[]
local function get_highlighted_symbols_from_extmarks(extmarks)
---@type HighlightedSymbol[]
local highlighted_symbols = {}
for _, extmark in ipairs(extmarks) do
-- TODO: support multi-line extmarks
local line = extmark[2]
local start_col = extmark[3]
local details = extmark[4]
---Extmark is end_col-exclusive
local end_col = details.end_col
for col = start_col, end_col - 1 do
table.insert(highlighted_symbols, {
line = line,
column = col,
hl_group = details.hl_group,
})
end
end
return highlighted_symbols
end
---Prunes duplicate highlighted symbols ensuring that each symbol is highlighted
---with a single highlight group.
---nvim-ts-rainbow sometimes sets duplicated extmarks to highlight symbols.
---Not pruning duplicates would mean errors would be reported multiple times
--(once for each duplicate extmark).
---@param highlighted_symbols HighlightedSymbol[] The table of highlighted symbols. it will be modified in place.
---@param source_code_lines string[] Source code lines used for error reporting
local function remove_duplicate_highlighted_symbols(highlighted_symbols, source_code_lines)
local multiple_highlights_for_symbols = false
-- NOTE: manual index tracking because one loop iteration can remove
-- multiple elements. Using iterators could iterate over removed indices
local index = 1
while index <= #highlighted_symbols do
local symbol = highlighted_symbols[index]
-- The body of the loop tries to prune duplicates in the range of
-- index+1..#highlighted_symbols
-- NOTE: loop from the end to allow removing elements in the loop while
-- preserving indices that will be looped over in the future
for other_symbol_index = #highlighted_symbols, index + 1, -1 do
local other_symbol = highlighted_symbols[other_symbol_index]
if symbol.line == other_symbol.line and symbol.column == other_symbol.column then
if symbol.hl_group == other_symbol.hl_group then
table.remove(highlighted_symbols, other_symbol_index)
else
print("Symbol has multiple different highlight groups assigned to it.")
print(
string.format(
"Found highlight groups: %s %s",
symbol.hl_group,
other_symbol.hl_group
)
)
print_line_with_error_marker(
source_code_lines[symbol.line + 1],
symbol.line + 1,
symbol.column
)
multiple_highlights_for_symbols = true
end
end
end
index = index + 1
end
assert(not multiple_highlights_for_symbols, "There are multiple highlights for some symbols")
end
local function verify_highlights_in_file(filename)
local extended_mode = string.find(filename, "extended") ~= nil
local rainbow_module = require("nvim-treesitter.configs").get_module("rainbow")
rainbow_module.extended_mode = extended_mode
vim.cmd.edit(filename)
local source_code_lines = vim.api.nvim_buf_get_lines(0, 0, -1, 1)
vim.api.nvim_buf_set_lines(0, 0, -1, true, source_code_lines)
local rainbow_ns_id = vim.api.nvim_get_namespaces().rainbow_ns
assert.not_equal(nil, rainbow_ns_id, "rainbow namespace not found")
local parser = require("nvim-treesitter.parsers").get_parser(0)
assert.truthy(parser, "Parser not found")
parser:parse()
-- NOTE: nvim_buf_get_extmarks does not return extmarks that contain
-- some range. It only returns extmarks within the given range.
-- We cannot use it to look for extmarks for a given symbol, because sometimes
-- the extmarks are for a range (e.g. when highlighting a JSX tag, the
-- whole range "div" is a single extmark and asking for an extmark for
-- the position of "i" returns nothing).
-- Thus, we must filter through all extmarks set on the buffer and
-- check each symbol.
local extmarks = vim.api.nvim_buf_get_extmarks(0, rainbow_ns_id, 0, -1, { details = true })
local highlighted_symbols = get_highlighted_symbols_from_extmarks(extmarks)
remove_duplicate_highlighted_symbols(highlighted_symbols, source_code_lines)
local some_symbol_not_highlighted = false
local invalid_highlight = false
for _, expected_highlight in ipairs(get_expected_highlights(source_code_lines)) do
local symbol_highlighted = false
-- NOTE: loop from the end to allow removing elements inside of the loop
-- without changing the indices that will be looped over
for i = #highlighted_symbols, 1, -1 do
local highlighted_symbol = highlighted_symbols[i]
if
highlighted_symbol.line == expected_highlight.line
and highlighted_symbol.column == expected_highlight.column
then
symbol_highlighted = true
local expected_highlight_group =
get_rainbow_highlight_group_name(expected_highlight.rainbow_level)
if expected_highlight_group ~= highlighted_symbol.hl_group then
invalid_highlight = true
print(
string.format(
'Invalid rainbow highlight group. Expected "%s", found "%s"',
expected_highlight_group,
highlighted_symbol.hl_group
)
)
print_line_with_error_marker(
source_code_lines[expected_highlight.line + 1],
expected_highlight.line + 1,
expected_highlight.column
)
end
-- NOTE: remove the matched highlighted symbol to later
-- check that all highlighted symbols matched some expected
-- highlight
table.remove(highlighted_symbols, i)
end
end
if not symbol_highlighted then
print(
string.format(
'No highlight groups detected. Expected "%s".',
get_rainbow_highlight_group_name(expected_highlight.rainbow_level)
)
)
print_line_with_error_marker(
source_code_lines[expected_highlight.line + 1],
expected_highlight.line + 1,
expected_highlight.column
)
some_symbol_not_highlighted = true
end
end
for _, symbol in ipairs(highlighted_symbols) do
print(
string.format(
'Symbol was extraneously highlighted with highlight group "%s"',
symbol.hl_group
)
)
print_line_with_error_marker(
source_code_lines[symbol.line + 1],
symbol.line + 1,
symbol.column
)
end
assert(not invalid_highlight, "Some symbol was incorrectly highlighted")
assert(not some_symbol_not_highlighted, "Some symbol was not highlighted")
assert(#highlighted_symbols == 0, "Extraneous highlights")
end
describe("Highlighting integration tests", function()
local files = vim.fn.glob("test/highlight/**/*.*", nil, true)
for _, filename in ipairs(files) do
if not string.match(filename, "highlight_spec.lua") then
it(filename, function()
verify_highlights_in_file(filename)
end)
end
end
end)

View File

@ -0,0 +1,31 @@
<!DOCTYPE html>
<!-- This is a comment -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="style.css" type="text/css" media="all">
<title>Test page</title>
<style type="text/css" media="all">
body {
font-family: "sans-serif";
}
</style>
<script>
console.log('Hello, world!');
</script>
</head>
<body>
<p>
This is an <a href="https://example.com">Example link</a>.
</p>
<hr />
<p>
This is an <a href="https://example.com">Example<br/>link</a> with<br> line <br/>break.
</p>
<hr>
<div>
<p>Good<span>bye</span>.</p>
</div>
</body>
</html>

View File

@ -0,0 +1,251 @@
@(:ant :bee
:cat :dog
:elephant :fox
:giraffe :heron
:iguana :janet)
@["Archimedes" "Bohm"
"Cantor" "Deming"
"Erdos" "Feynman"
"Gauss" "Houdini"
"Ishikawa" "Janet"]
{"Ada"
{:file-extensions [".adb" ".ads"]
:people ["Jean Ichbiah"]
:year 1983}
"Bash"
{:file-extensions [".sh"]
:people ["Brian Fox"
"Chet Ramey"]
:year 1989}
"C"
{:file-extensions [".c" ".h"]
:people ["Dennis Ritchie"]
:year 1972}
"Dart"
{:file-extensions [".dart"]
:people ["Lars Bak"
"Kasper Lund"]
:year 2011}
"Emacs Lisp"
{:file-extensions [".el" ".elc" ".eln"]
:people ["Richard Stallman"
"Guy L. Steele, Jr."]
:year 1985}
"Forth"
{:file-extensions [".fs" ".fth" ".4th" ".f" ".forth"]
:people ["Charles H. Moore"]
:year 1970}
"Go"
{:file-extensions [".go"]
:people ["Robert Griesemer"
"Rob Pike"
"Ken Thompson"]
:year 2009}
"Haskell"
{:file-extensions [".hs" ".lhs"]
:people ["Lennart Augustsson"
"Dave Barton"
"Brian Boutel"
"Warren Burton"
"Joseph Fasel"
"Kevin Hammond"
"Ralf Hinze"
"Paul Hudak"
"John Hughes"
"Thomas Johnsson"
"Mark Jones"
"Simon Peyton Jones"
"John Launchbury"
"Erik Meijer"
"John Peterson"
"Alastair Reid"
"Colin Runciman"
"Philip Wadler"]
:year 1990}
"Idris"
{:file-extensions [".idr" ".lidr"]
:people ["Edwin Brady"]
:year 2007}
"Janet"
{:file-extensions [".cgen" ".janet" ".jdn"]
:people ["Calvin Rose"]
:year 2017}}
~@{:main
(some :input)
#
:input
(choice :non-form
:form)
#
:non-form
(choice :whitespace
:comment)
#
:whitespace
(choice (some (set " \0\f\t\v"))
(choice "\r\n"
"\r"
"\n"))
#
:comment
(sequence "#"
(any (if-not (set "\r\n") 1)))
#
:form
(choice :reader-macro
:collection
:literal)
#
:reader-macro
(choice :fn
:quasiquote
:quote
:splice
:unquote)
#
:fn
(sequence "|"
(any :non-form)
:form)
#
:quasiquote
(sequence "~"
(any :non-form)
:form)
#
:quote
(sequence "'"
(any :non-form)
:form)
#
:splice
(sequence ";"
(any :non-form)
:form)
#
:unquote
(sequence ","
(any :non-form)
:form)
#
:literal
(choice :number
:constant
:buffer
:string
:long-buffer
:long-string
:keyword
:symbol)
#
:collection
(choice :array
:bracket-array
:tuple
:bracket-tuple
:table
:struct)
#
:number
(drop (cmt
(capture (some :name-char))
,scan-number))
#
:name-char
(choice (range "09" "AZ" "az" "\x80\xFF")
(set "!$%&*+-./:<?=>@^_"))
#
:constant
(sequence (choice "false" "nil" "true")
(not :name-char))
#
:buffer
(sequence "@\""
(any (choice :escape
(if-not "\"" 1)))
"\"")
#
:escape
(sequence "\\"
(choice (set `"'0?\abefnrtvz`)
(sequence "x" [2 :h])
(sequence "u" [4 :h])
(sequence "U" [6 :h])
(error (constant "bad escape"))))
#
:string
(sequence "\""
(any (choice :escape
(if-not "\"" 1)))
"\"")
#
:long-string :long-bytes
#
:long-bytes
{:main (drop (sequence :open
(any (if-not :close 1))
:close))
:open (capture :delim :n)
:delim (some "`")
:close (cmt (sequence (not (look -1 "`"))
(backref :n)
(capture (backmatch :n)))
,=)}
#
:long-buffer
(sequence "@"
:long-bytes)
#
:keyword
(sequence ":"
(any :name-char))
#
:symbol (some :name-char)
#
:array
(sequence "@("
(any :input)
(choice ")"
(error (constant "missing )"))))
#
:tuple
(sequence "("
(any :input)
(choice ")"
(error (constant "missing )"))))
#
:bracket-array
(sequence "@["
(any :input)
(choice "]"
(error (constant "missing ]"))))
#
:bracket-tuple
(sequence "["
(any :input)
(choice "]"
(error (constant "missing ]"))))
:table
(sequence "@{"
(any :input)
(choice "}"
(error (constant "missing }"))))
#
:struct
(sequence "{"
(any :input)
(choice "}"
(error (constant "missing }"))))
}

View File

@ -0,0 +1,66 @@
@Author(name = "John Doe")
public class HelloWorld {
// Constructor body
public HelloWorld() {
}
// Method with formal parameters
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println(args[0]);
}
public static void printList(List<List<List<T>>> l) {
// Array initializer
String[] names = {"Alice", "Bob", "Carol", "Dan"};
// Multi-dimensional dimensions and a dimensions expression
Integer[][] inputArrays = new Integer[3][];
// Enhanced for statement (for-each)
for (var name: names) {
var msg = String.format("Hello, %s.", name);
System.out.println(msg);
}
// Regular for-statement
for (var i = 0; i < 3; ++i) {
System.out.print(i);
}
// Parentheses around condition
if (false) {
System.err.println("This will never print");
}
// Parentheses around catch clause
try {
// A parenthesized expression
System.out.print(((3/0)));
} catch(ArithmeticException e) {
System.err.print(e);
}
// Nested bodies
for (var item1: l) {
for (var item2: item1) {
for (var item3: item2) {
System.out.format("%d", item3)
}
}
}
// Try resource specification
try (FileWriter fw = new FileWriter("test");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.close();
} catch (IOException e) {
System.out.println(e);
}
double d = 13.37;
int i = (int) d; // cast expression
}
}
// vim:noexpandtab

View File

@ -0,0 +1,9 @@
class LambdaTest {
void singleton() {
version -> create;
// Inferred parameters
(record, b) -> record + b;
}
}
// vim:noexpandtab

View File

@ -0,0 +1,67 @@
// Named imports
import { useState } from 'react'
// Template strings
const who = 'world';
console.log(`Hello, ${who}`);
// Function with nested function
function add(x, y) {
function iter(i, acc) {
if (i == 0) {
return acc;
}
return iter(i - 1, acc + 1);
}
return iter(y, x)
}
// Loops
function iterate() {
for (let i = 0; i <= 2; i++) {
break;
}
let list = []
for (let element of list) {
console.log(element);
}
}
// Arrow function definition
const multiply = (x, y) => x * y;
// Nested object and array
let some_object = {
a: {
b: {
c: {},
},
d: [[1, 2, 3]]
}
};
// object pattern
const destructuredFunction = ({ value }) => {
return {}
}
// Subscript expressions
const zeroes = [0];
console.log(zeroes[zeroes[zeroes[0]]])
// Destructuring assignment
const [x, y] = array;
// Parenthesized expressions
console.log(1 + (2 + (3 + 4)))
let a = 1
switch(a) {
case 1:
break;
}
// export clause
export { zeroes }

View File

@ -0,0 +1,10 @@
{
"foo": "bar",
"bar": {
"baz": [
[
[]
]
]
}
}

View File

@ -0,0 +1,13 @@
{
// comments
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Look, Mom!
No \\n's!",
hexadecimal: 0xdecaf,
object: {a: {b: {c: {}}}},
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
trailingComma: 'in objects', andIn: [[['arrays',]]],
"backwardsCompatible": "with JSON",
}

View File

@ -0,0 +1,13 @@
// This is a comment
{
"foo": "bar",
/* This is a multi-line comment
*/
"bar": {
"baz": [
[
[]
]
]
}
}

View File

@ -0,0 +1,34 @@
{
concat_array: [1, 2, 3] + [4],
concat_string: '123' + 4,
equality1: 1 == '1',
equality2: [{}, { x: 3 - 1 }]
== [{}, { x: 2 }],
ex1: 1 + 2 * 3 / (4 + 5),
// Bitwise operations first cast to int.
ex2: self.ex1 | 3,
// Modulo operator.
ex3: self.ex1 % 2,
// Boolean logic
ex4: (4 > 3) && (1 <= 3) || false,
// Mixing objects together
obj: { a: 1, b: 2 } + { b: 3, c: 4 },
// Test if a field is in an object
obj_member: 'foo' in { foo: 1 },
// String formatting
str1: 'The value of self.ex2 is '
+ self.ex2 + '.',
str2: 'The value of self.ex2 is %g.'
% self.ex2,
str3: 'ex1=%0.2f, ex2=%0.2f'
% [self.ex1, self.ex2],
// By passing self, we allow ex1 and ex2 to
// be extracted internally.
str4: 'ex1=%(ex1)0.2f, ex2=%(ex2)0.2f'
% self,
// Do textual templating of entire files:
str5: |||
ex1=%(ex1)0.2f
ex2=%(ex2)0.2f
||| % self,
}

View File

@ -0,0 +1,31 @@
{
cocktails: {
"Bee's Knees": {
// Construct the ingredients by using
// 4/3 oz of each element in the given
// list.
ingredients: [ // Array comprehension.
{ kind: kind, qty: 4 / 3 }
for kind in [
'Honey Syrup',
'Lemon Juice',
'Farmers Gin',
]
],
garnish: 'Lemon Twist',
served: 'Straight Up',
},
} + { // Object comprehension.
[sd.name + 'Screwdriver']: {
ingredients: [
{ kind: 'Vodka', qty: 1.5 },
{ kind: sd.fruit, qty: 3 },
],
served: 'On The Rocks',
}
for sd in [
{ name: 'Yellow ', fruit: 'Lemonade' },
{ name: '', fruit: 'Orange Juice' },
]
},
}

View File

@ -0,0 +1,12 @@
local Margarita(salted) = {
ingredients: [
{ kind: 'Tequila Blanco', qty: 2 },
{ kind: 'Lime', qty: 1 },
{ kind: 'Cointreau', qty: 1 },
],
[if salted then 'garnish']: 'Salt',
};
{
Margarita: Margarita(true),
'Margarita Unsalted': Margarita(false),
}

View File

@ -0,0 +1,44 @@
// Define a local function.
// Default arguments are like Python:
local my_function(x, y=10) = x + y;
// Define a local multiline function.
local multiline_function(x) =
// One can nest locals.
local temp = x * 2;
// Every local ends with a semi-colon.
[temp, temp + 1];
local object = {
// A method
my_method(x): x * x,
};
{
// Functions are first class citizens.
call_inline_function:
(function(x) x * x)(5),
call_multiline_function: multiline_function(4),
// Using the variable fetches the function,
// the parens call the function.
call: my_function(2),
// Like python, parameters can be named at
// call time.
named_params: my_function(x=2),
// This allows changing their order
named_params2: my_function(y=3, x=2),
// object.my_method returns the function,
// which is then called like any other.
call_method1: object.my_method(3),
standard_lib:
std.join(' ', std.split('foo/bar', '/')),
len: [
std.length('hello'),
std.length([1, 2, 3]),
],
}

View File

@ -0,0 +1,46 @@
// Template strings
const who = 'world';
console.log(`Hello, ${who}`);
// Nested object
let some_object = {
a: {
b: {
c: {},
}
}
};
// Subscript expressions
const zeroes = [0];
console.log(zeroes[zeroes[zeroes[0]]])
// Parenthesized expressions
console.log(1 + (2 + (3 + 4)))
function hello() {
console.log('Hello, world!');
}
function app() {
const [x, y] = array;
return (
<div>
<p>
This is an <a href="https://example.com">Example link</a>.
</p>
<p>
This is an <a href="https://example.com">Example<br/>link</a> with<br/> line <br/>break.
</p>
<ComponentWithChildren>
{someFunction().map((x) => <div></div>)}
</ComponentWithChildren>
<ComponentWith.property>
{someFunction().map((x) => <div></div>)}
</ComponentWith.property>
<ComponentWith.property bool={true} arr={[1, 2, 3]} />
<button onClick={hello}>Click me!</button>
</div>
)
}

View File

@ -0,0 +1,9 @@
a = Vector{Int}([1, 2, 3, 4, 5, 6]);
A = [
28 32
11 70
];
f(x) = abs((x-4)*(x+2))
b = [f(x) for x A]
x = (1, 2)

View File

@ -0,0 +1,113 @@
// Define a simple class with a primary constructor
class Person<T>(private val name: String, private val age: Int, private val t: T) {
// Secondary constructor
constructor(name: String) : this(name, 0)
class Hello {
class Goodbye {
}
}
init {
println("New person created with name $name")
}
// Member function
fun greet() {
println("Hello, my name is $name and I am $age years old.")
}
}
// Extension function
fun String.exclaim() = "$this!"
// Top-level function
fun calculateFactorial(n: Int): Int {
return if (n == 1) n else n * calculateFactorial(n - 1)
}
// Main function - entry point of the program
fun main() {
val person = Person<Map<String, String>>("Alice", 30, emptyMap())
person.greet()
// Using the extension function
println("Wow".exclaim())
// Conditional
val number = 5
if (number % 2 == 0) {
println("$number is even")
} else {
println("$number is odd")
}
// Loop
for (i in 1..5) {
println("Factorial of $i is: ${calculateFactorial(i)}")
}
// Using a map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for ((key, value) in map) {
println("Key: $key, Value: $value")
}
// Lambda expression
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
println("Doubled numbers: $doubled")
}
val list = listOf(1, 2, 3)
list.forEach { item ->
println(item)
}
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val sum = operateOnNumbers(2, 3) { x, y -> x + y }
println("Sum: $sum")
val multiply = fun(x: Int, y: Int): Int {
return x * y
}
println("Product: ${multiply(2, 3)}")
val x = 2
when (x) {
1 -> println("x == 1")
2 -> println("x == 2")
else -> println("x is neither 1 nor 2")
}
when {
1 == 1 -> print("1")
else -> print("not")
}
val rows = 2
val cols = 3
val matrix = Array(rows) { IntArray(cols) }
// Fill the array
for (i in matrix.indices) {
for (j in matrix[i].indices) {
matrix[i][j] = i + j
}
matrix[matrix[i][i]]
}
// Print the 2D array
for (row in matrix) {
for (col in row) {
print("$col ")
}
println()
}

View File

@ -0,0 +1,31 @@
\documentclass{article} % Starts an article
\usepackage{amsmath} % Imports amsmath
\title{\LaTeX} % Title
\begin{document} % Begins a document
\maketitle
\LaTeX{} is a document preparation system for
the \TeX{} typesetting program. It offers
programmable desktop publishing features and
extensive facilities for automating most
aspects of typesetting and desktop publishing,
including numbering and cross-referencing,
tables and figures, page layout,
bibliographies, and much more. \LaTeX{} was
originally written in 1984 by Leslie Lamport
and has become the dominant method for using
\TeX; few people write in plain \TeX{} anymore.
The current version is \LaTeXe.
% This is a comment, not shown in final output.
% The following shows typesetting power of LaTeX:
\begin{align}
E_0 &= mc^2 \\
E &= \frac{mc^2}{\sqrt{1-\frac{v^2}{c^2}}}
\end{align}
This is testing {nesting {of {text} with a reference\ref{section:some_sec}}}.
\end{document}
% vim:ft=latex

View File

@ -0,0 +1,66 @@
-- This is a comment
local function f1(a, b)
local function f2(a2, b2)
return a2, b2
end
return f2(a, b)
end
function GlobalFunction()
print 'This is a global function'
end
if true then
print 'True condition'
elseif false then
print 'Alternative condition'
elseif false then
print 'Alternative condition'
else
print 'Alternative'
end
while false do
print 'A while-loop'
end
repeat
print 'This will repeat only once'
until true
do
print 'A block'
end
for i, v in ipairs({'a', 'b', 'c'}) do
print(string.format("%d = %s", i, v))
end
for i = 1, 5, 1 do
print(string.format("Number %d", i))
end
print(f1('a', 'b'))
print((((('Hello, world!')))))
print {
{
{
'Hello, world!'
}
}
}
local one = {1}
print(one[one[one[1]]])
-- Embedded Vim script
vim.cmd [[
echo a(b(c(d(e(f())))))
]]
local tbl = {
["highlight me"] = {}
}

View File

@ -0,0 +1,30 @@
---@type fun(x: (fun(): integer), y: fun(z: fun()))
---@type { key1: { key2: { [string]: table<number, number | integer> }, [integer]: integer } }
---@type table<integer | number, table<string, table<number, boolean>>>
---@class test
---@field a boolean
---@field b (((boolean)))
---@field x number | string | { key: number | string | boolean } | boolean
---@field [string] boolean
---@type string[]
local _str_tbl = { 'a', 'b', 'c' }
---@param f fun(i: integer): (integer, integer)
---@return integer, integer
local function _test_fun(f)
return f(1)
end
-- Note: The parser nests union types, which can mess
-- with rainbow-delimiters highlighting, so we don't
-- highlight the '|' here:
---@type number | integer[] | string | number[] | string[] | boolean | boolean[]
local _x = 1
---@type boolean[] | integer[]
local _t = { true, false } or { 0, 1 }
---@type (boolean | integer)[]
local _arr = { true, 0 }

View File

@ -0,0 +1,23 @@
.PHONY: all
all: herp derp
herp: a.txt
# Command substitution
echo $(basedir $(pwd))
# Variable expansion
echo ${FOO${BAR${BAZ}}}
# Test expression (using the `test` command)
if [ -d "herp/derp/" ]; then
echo "Yay"
fi
# Test expression (bashism)
if [[ -d "herp/derp/" ]]; then
echo "Yay"
fi
# Sub-shells
(true; false; (true; true; (false; true)))

View File

@ -0,0 +1,9 @@
Some markdown.
```markdown
~~~lua
print({{{{}}}})
print({{{{}}}})
vim.cmd[[echo str([])]]
~~~
```
More markdown

View File

@ -0,0 +1,72 @@
# A Markdown example
## Some nonsense text
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
## Injected languages
Here we test highlighting of an injected
### Lua
Lua is a good candidate
```lua
-- This is a comment
local function f1(a, b)
local function f2(a2, b2)
return a2, b2
end
return f2(a, b)
end
print(f1('a', 'b'))
print((((('Hello, world!')))))
print {
{
{
'Hello, wold!'
}
}
}
local one = {1}
print(one[one[one[1]]])
-- Embedded Vim script
vim.cmd [[
echo a(b(c(d(e(f())))))
]]
-- Embedded Vim script on one line
vim.cmd[[echo a(b(c(d())))]]
```
### Vim script
Let's try another embedded language
```vim
let g:my_list = [[[1]]]
let g:my_dict = {
\'a': {
\'b': {
\'c': {},
\}
\}
\ }
echo string(1 + (2 + (3 + 4)))
echo string(-(3))
echo string((5)-(3))
echo string((1) ? (2) : (3))
echo ((('Hello, world!')))
````

View File

@ -0,0 +1,26 @@
# parameter_declaration_list and generic_parameter_list
proc p[T: seq[int]](a: seq[seq[int]]): int =
result = 1
let
# array
a = [[[1], [1]], [[1], [1]]]
# tuple and tuple_deconstruct_declaration
(((q), (_)), ((p), (_))) = (((1, ), (1, )), ((1, ), (1, )))
# set
c = {'a'}
# table
d = {1: {1: {: }, 2: {: }}, 2: {1: {: }, 2: {: }}}
# parenthesized
e = (((
discard;
discard;
1)))
# call and bracket_expression
f = p[seq[int]](@[@[p[seq[int]](@[@[1]])]])
# cast and field_declaration_list
cast[tuple[a: seq[int], ]](p[seq[int]](@[@[1]]))
# term_rewriting_pattern and curly_expression
template t{(0|1|2){x}}(x: untyped): untyped = x + 1

View File

@ -0,0 +1,56 @@
{
description = "Test flake for rainbow-delimiters.nvim";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
pre-commit-hooks = {
url = "github:cachix/pre-commit-hooks.nix";
};
flake-utils.url = "github:numtide/flake-utils";
};
outputs = {
self,
nixpkgs,
flake-utils,
pre-commit-hooks,
...
}: let
supportedSystems = [
"x86_64-linux"
];
in
flake-utils.lib.eachSystem supportedSystems (system: let
inherit (nixpkgs) lib;
pkgs = nixpkgs.legacyPackages.${system};
formatting = pre-commit-hooks.lib.${system}.run {
src = lib.cleanSource self;
hooks = {
alejandra.enable = true;
markdownlint.enable = true;
};
settings = {
markdownlint.config = {
MD004 = false;
};
};
};
in {
apps = rec {
hi = with pkgs; flake-utils.lib.mkApp {
drv = writeShellScriptBin "hi" ''
echo "Hello, world"
'';
};
default = hi;
};
packages = {
};
checks = {
inherit formatting;
};
});
}

View File

@ -0,0 +1,47 @@
#!/usr/bin/perl
use v5.20;
use feature qw(signatures);
no warnings qw(experimental::signatures);
sub foobar($foo, $bar) {
my %h = (
foo => +{ foo => 'bar' },
($foo ? (
bar => hoge(foo => $bar)->id,
) : ()),
);
say $h{foo}{foo};
my $h_ref = \%h;
say $h_ref->{foo}{foo};
}
sub barfoo {
my ($foo, $bar) = @_;
say $_[0];
foobar([ $foo, $bar ]);
my ($ary) = ([ ($foo, $bar) ]);
$ary = [ $foo, $bar ];
my $result = ($foo ? $bar : $foo);
{
say @$ary[0];
say @{$ary}[0];
say $ary->[1];
}
if ($foo) {
# TODO: tree-sitter-perl cannot detect string interpolation yet.
# say "${foo} $bar";
}
my $sub = sub {
say $foo;
};
map { +{} } @ary;
qw(a b c d e);
qr(a b c d e);
qx(a b c d e);
qq(a b c d e);
q(a b c d e);
m(a b c d e);
s(a b c)(d e);
tr(a b c)(d e);
y(a b c)(d e);
}

View File

@ -0,0 +1,32 @@
<?php
// parenthesized expression
$var = ((3 + (18 - 5)) * 8);
// arguments
var_dump(max($var, 12));
// declaration list
class AddOp {
// encapsed string
private $innerValue = "var = {$var} - var value";
// formal parameters
public function concatStr($x, $y) {
// array creation expression
$arr = [1, 2, [3, [4, 5, 6]]];
$idx = [0, 1, 2];
// subscript expression
echo $arr[$idx[1]];
// compound statement
if ($x == $y) {
if ($x != $y) {
return $x . $y;
}
}
return $this->innerValue;
}
}

View File

@ -0,0 +1,49 @@
# NOTE: When updating this file update the Starlark test file as well if
# applicable.
from typing import (
Dict,
List,
)
def sum_list(lst: List[Dict[int, int]]) -> int:
result = 0
for inner in lst:
for i in inner:
result += i
return result
my_list = [[['Hello, world!']]]
my_dict = {'x': {'x': {'x': 'Hello, wold!'}}}
my_set = {{{{'Hello, wold!'}}}}
my_tuple = (((('Hello, wold!'),),),)
list_comp = [i for i in [j for j in range(5)] if i % 2 == 0]
dict_comp = {k: v for k, v in {k: v for k, v in {'k': 'v'}.items()}
if k == 'k'}
set_comp = {i for i in {j for j in range(5)} if i % 2 == 0}
gen_comp = (i for i in (j for j in range(5)) if i % 2 == 0)
match my_dict:
case {'x': {'x': {'x': message}}}:
print(message)
case [[[message]]]:
print(message)
case (((message))):
print(message)
zero = [0]
(a,b) = (1,2)
[c,d] = [3,4]
print(zero[zero[zero[0]]])
print(2 + ((((3)))))
print(len(my_list))
# Format-string with embedded delimiters
print(f'The sum of 2 and 3 is {2 + (1 + 2)}')

View File

@ -0,0 +1,7 @@
(foo (bar (baz)) @bar) @foo
[foo [bar [baz]] @bar] @foo
(foo [bar (baz)] @bar) @foo
;;; vim:ft=query

View File

@ -0,0 +1,35 @@
# call
suppressWarnings(library(datasets))
# outer subset, inner subset2
mtcars[mtcars[[1, 2]], ]
# if ladder, inner brace_list
var <- 10
if (var > 5) {
print(paste(var, "is greater than 5"))
if (var < 10) {
print(paste(var, "is less than 10"))
}
}
foobar <- function(num) {
for (i in 1:5) {
print(i)
}
while (TRUE) {
break
}
x <- "a"
v <- switch(x, "a"="apple", "b"="banana", "c"="cherry")
if (num > 0) {
return("Positive")
} else if (num < 0) {
return("Negative")
} else {
return("Zero")
}
}

View File

@ -0,0 +1,56 @@
#lang racket
(define [add x y]
"A silly way to add two numbers recursively."
(if (zero? y)
x
(add (add1 x)
(sub1 x))))
(define-syntax foo
  (syntax-rules ()
    ((_ a ...)
     (printf "~a\n" (list a ...)))))
{+ 2 {+ 3 {+ 4 5}}}
'(((a . b)))
'((((a b . c))))
'[[[a . b]]]
'[[[a b . c]]]
'{{{a . b}}}
'
'([{a . b}])
'([{a b . c}])
;;; Vector literals
#(#(#(a)))
#[#[#[a]]]
#{#{#{a}}}
;;; Inexact number vector literals
#fl(#fl(#fl(a)))
#fl[#fl[#fl[a]]]
#fl{#fl{#fl{a}}}
#Fl(#Fl(#Fl(a)))
#Fl[#Fl[#Fl[a]]]
#Fl{#Fl{#Fl{a}}}
;;; Fixnum vector literals
#fx(#fx(#fx(a)))
#fx[#fx[#fx[a]]]
#fx{#fx{#fx{a}}}
#Fx(#Fx(#Fx(a)))
#Fx[#Fx[#Fx[a]]]
#Fx{#Fx{#Fx{a}}}
;;; Structures
(struct prefab-point (x y) #:prefab)
'#s(prefab-point 1 2)

View File

@ -0,0 +1,20 @@
// Ref: https://github.com/davatorium/rofi/blob/next/doc/rofi-theme.5.markdown
* {
background-image: url("a.jpg", width);
background-color: env(ROFI_BACKGROUND_COLOR, transparent);
text-color: rgba(256, 256, 256, 0.9);
text-color-2: var(text-color, hsl(20, 1, 1));
text-color-3: hwb(20, 1, 10);
text-color-4: cmyk(20, 15, 10, 5);
width: 1024px
}
@media (monitor-id: ${ROFI_MAIN_MONITOR}) {
width: calc(120% * 1024px);
}
mainbox {
background-image: linear-gradient(to bottom, darkgreen/50%, black/70%);
children: [inputbar, listview];
}

View File

@ -0,0 +1,9 @@
a(b(c(d)))
a(b(c(d)?))
a(b(c[def]))
a(b(c[^def]))
a(b(c{1}))
a(b(c{1,4}))
a(b(c(?=d)))
vim:ft=regex

View File

@ -0,0 +1,74 @@
.. default-role:: code
############################
A reStructuredText example
############################
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
Injected languages
##################
Here we test highlighting of an injected
Lua
===
Lua is a good candidate
.. code:: lua
-- This is a comment
local function f1(a, b)
local function f2(a2, b2)
return a2, b2
end
return f2(a, b)
end
print(f1('a', 'b'))
print((((('Hello, world!')))))
print {
{
{
'Hello, world!'
}
}
}
local one = {1}
print(one[one[one[1]]])
-- Embedded Vim script
vim.cmd [[
echo a(b(c(d(e(f())))))
]]
Let's try another embedded language
.. code:: vim
let g:my_list = [[[1]]]
let g:my_dict = {
\'a': {
\'b': {
\'c': {},
\}
\}
\ }
echo string(1 + (2 + (3 + 4)))
echo string(-(3))
echo string((5)-(3))
echo string((1) ? (2) : (3))
echo ((('Hello, world!')))

View File

@ -0,0 +1,14 @@
# frozen_string_literal: true
an_array = [[['Hello', 'world!']]] # rubocop:disable Lint/UselessAssignment
a_hash = { 'x' => { 'x' => { 'x' => 'Hello, world!' } } } # rubocop:disable Lint/UselessAssignment
def greeting(name, age)
age_in_seconds = (((((age * 365))) * 24) * 60) * 60
puts "Hello, #{name}! You are #{age} years old, which is #{age_in_seconds} in seconds!"
end
puts greeting('Fry', 25)
[[1], [2], [3]].each { |nums| nums.each { |num| puts num } }

View File

@ -0,0 +1,171 @@
#![crate_type = "lib"]
struct NestedStruct {
value: u32,
inner: Inner,
}
struct Inner {
value: u32,
}
extern "C" {
fn extern_block();
}
union TestUnion {
val_1: f32,
val_2: u32,
}
#[derive(Default, Debug)]
struct TupleStruct(u32);
#[cfg_attr(all(target_os = "linux", feature = "multithreaded"), derive(Default))]
enum EnumTest {
TupleVariant(u32),
TupleVariantTupleStruct(TupleStruct),
StructVariant { value: u32 },
NestedStructVariant { inner: Inner },
}
fn test_type_param<A: Default>() -> usize {
std::mem::size_of::<A>()
}
fn test_param(a: u32, b: u32) -> u32 {
a * b
}
fn tuple_param(a: (u32, u32)) -> u32 {
let (a, b) = a;
a * a
}
macro_rules! inefficient_vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
pub(crate) struct VisibilityModifier;
pub const NAMES: &'static [(&'static str, u32)] = &[
("TEST NAME 1", 1),
("TEST NAME 2", 2),
];
fn main() {
let nested_vec: Vec<Vec<Vec<Vec<Vec<Vec<()>>>>>> = Vec::<_>::new();
let arr_arr_arr = [[[0; 4]; 4]; 4];
let constructed_struct = Inner { value: 0 };
let nested_constructed = NestedStruct {
value: 0,
inner: Inner { value: 0 },
};
let tuple_struct = TupleStruct(0);
let nested_tuple = (
((1, 2, 3, 4), (5, 6, 7, 8)),
((9, 10, 11, 12), (13, 14, 15, 16)),
);
let enums = vec![
EnumTest::TupleVariant(0),
EnumTest::TupleVariantTupleStruct(TupleStruct(0)),
EnumTest::StructVariant { value: 0 },
EnumTest::NestedStructVariant {
inner: Inner { value: 0 },
},
];
let closure = |long_parameter_name: u8,
long_parameter_name_two: u8,
very_long_parameter_name: u8,
extra_long_name: u8| {
let nested_closure = || {};
nested_closure();
};
let async_block = async { 0 };
let labelled_block = 'a: { 0 };
let boolean_expr = (((3 * 4) + 5) > 1 || false) && (true || true);
let num = 5;
let match_expr = match num {
_ => match boolean_expr {
_ => {}
},
};
let fancy_match_expr = match enums[0] {
EnumTest::TupleVariant(v) => {}
EnumTest::TupleVariantTupleStruct(TupleStruct(v)) => {}
EnumTest::StructVariant { value } => {}
EnumTest::NestedStructVariant {
inner: Inner { value },
} => {}
};
let array = [1, 2, 3, 4];
let array_match = match array {
[a, b, c, d] => {}
};
let nested_macro = vec![vec![vec![vec![vec![0]]]]];
test_param(3, 4);
let test_tuple: (u32, u32) = (0, 1);
tuple_param(test_tuple);
}
use level_1::{
level_2::{
level_3::{
level_4::{
level_5::{A, B},
C, D,
},
E, F,
},
G, H,
},
I, J,
};
mod level_1 {
pub mod level_2 {
pub mod level_3 {
pub mod level_4 {
pub mod level_5 {
pub struct A;
pub struct B;
}
pub struct C;
pub struct D;
}
pub struct E;
pub struct F;
}
pub struct G;
pub struct H;
}
pub struct I;
pub struct J;
}

View File

@ -0,0 +1,22 @@
(define (add x y)
"A silly way to add two numbers recursively."
(if (zero? y)
x
(add (add1 x)
(sub1 y))))
;; R6RS allows square brackets as well
(define [mult x y]
"A silly way of multiplying to numbers recursively"
(if [= 1 y]
x
(add (add x x)
(sub1 y))))
(define-syntax foo
  (syntax-rules ()
    ((_ a ...)
     (printf "~a\n" (list a ...)))))
'(((a . b)))
'((((a b . c))))

View File

@ -0,0 +1,19 @@
@mixin admon($fg, $sign, $title) {
border-top: 2.25rem solid $fg;
background: color-mix(in srgb, $fg 50%, var(--color-bg));
&::before {
position: absolute;
content: $sign;
top: 0.4rem;
left: 0.75rem;
}
&::after {
position: absolute;
content: $title;
font-weight: bold;
top: 0.5rem;
left: 2.25rem;
}
}

View File

@ -0,0 +1,34 @@
SELECT (1 + (2 + (3 + (4 + (5 + (6 + (7 + (8 + ((9) + (0))))))))));
SELECT
(1 + ((2)((())) - 3)) AS "expression",
(()) AS "list",
-- ((((())))) AS "list" -- this will cause problems with the highlighting!
"users"."id" AS "user_id",
SUM("orders"."sum_prices") AS "user_orders_amount"
FROM "users"
JOIN (
SELECT
"orders"."id",
"orders"."user_id",
SUM("orders"."amount") AS "sum_prices"
FROM "orders"
GROUP BY
"orders"."id",
"orders"."user_id"
) AS "orders" ON "orders"."user_id" = "users"."id"
WHERE "users"."age" = (2 + (3 * 4)) AND (4 - (5 * 0)) = (1 * (2 + 2 + (5)))
AND "users"."id" IN (1, 2, 3, 4)
GROUP BY
"users"."id";
SELECT *
FROM products
where (
Product_Category = 'Fit'
AND Product_number IN (1234, 1235, 1236, 1237, 1238)
)
or
(Product_Category IN ('Tight', 'Wide') AND Product_number = 1324);
SELECT 10 FROM generate_series(1, 10) WHERE (TRUE);

View File

@ -0,0 +1,43 @@
# This is mostly identical to Python, without the generator comprehension
# NOTE: if you update queries for Python, please consider adding the changes
# to this file as well
def sum_list(lst: List[Dict[int, int]]) -> int:
result = 0
for inner in lst:
for i in inner:
result += i
return result
my_list = [[['Hello, world!']]]
my_dict = {'x': {'x': {'x': 'Hello, wold!'}}}
my_set = {{{{'Hello, wold!'}}}}
my_tuple = (((('Hello, wold!'),),),)
(a,b) = (1,2)
list_comp = [i for i in [j for j in range(5)] if i % 2 == 0]
dict_comp = {k: v for k, v in {k: v for k, v in {'k': 'v'}.items()}
if k == 'k'}
set_comp = {i for i in {j for j in range(5)} if i % 2 == 0}
gen_comp = (i for i in (j for j in range(5)) if i % 2 == 0)
match my_dict:
case {'x': {'x': {'x': message}}}:
print(message)
case [[[message]]]:
print(message)
case (((message))):
print(message)
zero = [0]
(a,b) = (1,2)
[c,d] = [3,4]
print(zero[zero[zero[0]]])
print(2 + ((((3)))))
print(len(my_list))

View File

@ -0,0 +1,31 @@
<script lang="ts">
import { baz } from 'foo/bar';
baz({a: {b: {c: 'd'}}});
</script>
<style>
p {
font-size: 2em;
}
</style>
<svelte:head>
<title>Test page</title>
<meta name="description" content="A test page" />
</svelte:head>
<h1>A test page for Svelte</h1>
<form action="?/herp/derp" method="post">
<p>This is a paragraph</p>
<hr/>
<ul>
{#each ["foo", "bar", "baz"] as x}
<li class="some-class">{ x }</li>
{/each}
</ul>
{# if True}
<p>Some text </p>
{/if}
</form>

View File

@ -0,0 +1,62 @@
-- This is a comment
local function add(x: integer, y: integer): integer
if y == 0 then
return x
end
return add((x + (1)), (y - (1)))
end
if true then
print 'True condition'
elseif false then
print 'Alternative condition'
elseif false then
print 'Alternative condition'
else
print 'Alternative'
end
while false do
print 'A while-loop'
end
repeat
print 'This will repeat only once'
until true
do
print 'A block'
end
for i, v in ipairs({'a', 'b', 'c'}) do
print(string.format("%d = %s", i, v))
end
for i = 1, 5, 1 do
print(string.format("Number %d", i))
end
print(f1('a', 'b'))
print((((('Hello, world!')))))
print {
{
{
'Hello, world!'
}
}
}
local one = {1}
print(one[one[one[1]]])
-- Embedded Vim script
vim.cmd [[
echo a(b(c(d(e(f())))))
]]
local tbl = {
["highlight me"] = {}
}

View File

@ -0,0 +1,86 @@
package main
import "fmt"
import "time"
templ headerTemplate(name string) {
<header data-testid="headerTemplate">
switch name {
case "Alice", "Bob":
<h1>{ name }</h1>
default:
<h1>{ "Unknown" }</h1>
}
<script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script>
<style type="text/css">
p {
font-family: sans-serif;
}
</style>
</header>
}
templ footerTemplate() {
<footer data-testid="footerTemplate">
<div>&copy; { fmt.Sprintf("%d", time.Now().Year()) }</div>
</footer>
}
templ layout(name string) {
<html>
<head><title>{ name }</title></head>
<body>
@headerTemplate(name)
@navTemplate()
<main>
{ children... }
<p>
Hello<br/>world!
</p>
</main>
</body>
@footerTemplate()
</html>
}
templ navTemplate() {
<nav data-testid="navTemplate">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/posts">Posts</a></li>
</ul>
</nav>
}
templ posts(posts []Post) {
@layout("Posts") {
@postsTemplate(posts)
if len(posts) > 0 {
<div>{ "Not empty" }</div>
} else {
<div>{ "Empty" }</div>
}
}
}
templ postsTemplate(posts []Post) {
<div data-testid="postsTemplate">
for _, p := range posts {
<div data-testid="postsTemplatePost">
<div data-testid="postsTemplatePostName">{ p.Name }</div>
<div data-testid="postsTemplatePostAuthor">{ p.Author }</div>
</div>
}
</div>
}
script withParameters(a string, b string, c int) {
console.log(a, b, c);
}
css red() {
background-color: #ff0000;
font-family: "Iosevka";
}
// vim:ft=templ

View File

@ -0,0 +1,20 @@
[table]
[table.sub]
people.names = [ "John", "Joe" ]
inline-table = { x = 0.1, y = 2 }
array-of-table = [
{ name = "Alice", level = 2 },
{ name = "Bob", level = 1 },
]
[[array-of-table2]]
z = 3
[[array-of-table2.t]]
desc = "Index 1"
[[array-of-table2]]
z = 30
t.desc = "Index 2"

View File

@ -0,0 +1,79 @@
// Function with nested function
function add(x: number, y: number): number {
function iter(i: number, acc: number) {
if (i == 0) {
return acc;
}
return iter(i - 1, acc + 1);
}
return iter(y, x)
}
// Function with generic type parameter
function id<T>(x: T): T {
return x;
}
// Class with members
class Person {
private name: string;
private age: number;
private salary: number;
constructor(name: string, age: number, salary: number) {
this.name = name;
this.age = age;
this.salary = salary;
}
toString(): string {
return `${this.name} (${this.age}) (${this.salary})`; // As of version 1.4
}
}
// Template strings
const who = 'world';
console.log(`Hello, ${who}`);
// Nested object
let some_object = {
a: {
b: {
c: {},
}
}
};
// Subscript expressions
const zeroes = [0];
console.log(zeroes[zeroes[zeroes[0]]])
// Parenthesized expressions
console.log(1 + (2 + (3 + (4 + (5 + 6)))))
function hello() {
console.log('Hello, world!');
}
function app() {
return (
<div style={{ display: 'flex' }}>
<p>
This is an <a href="https://example.com">Example link</a>.
</p>
<p>
This is an <a href="https://example.com">Example<br/>link</a> with<br/> line <br/>break.
</p>
<button onClick={hello}>Click me!</button>
<ComponentWithChildren>
{someFunction().map((x) => <div></div>)}
</ComponentWithChildren>
<ComponentWith.property>
{someFunction().map((x) => <div></div>)}
</ComponentWith.property>
<ComponentWith.property bool={true} arr={[1, 2, 3]} />
<CustomComponent bool={true} arr={[1, 2, 3]} />
</div>
)
}

View File

@ -0,0 +1,5 @@
// Declarations
declare namespace arithmetics {
add(x: number, y: number): number;
}

View File

@ -0,0 +1,71 @@
// Function with nested function
function add(x: number, y: number): number {
function iter(i: number, acc: number) {
if (i == 0) {
return accu;
}
return iter(i - 1, acc + 1);
}
return iter(y, x)
}
// Function with generic type parameter
function id<T>(x: T): T {
return x;
}
// Class with members
class Person {
private name: string;
private age: number;
private salary: number;
constructor(name: string, age: number, salary: number) {
this.name = name;
this.age = age;
this.salary = salary;
}
toString(): string {
return `${this.name} (${this.age}) (${this.salary})`; // As of version 1.4
}
async method(): Promise<Array<Record<string, number>>> {
return []
}
}
interface Request {
body: RequestProp['body'];
}
enum A {
Foo = "Bar",
}
// Template strings
const who = 'world';
console.log(`Hello, ${who}`);
// Nested object
let some_object = {
a: {
b: {
c: {},
}
}
};
// Subscript expressions
const zeroes = [0];
console.log(zeroes[zeroes[zeroes[0]]])
let a = 1
switch(a) {
case 1:
break;
}
// Parenthesized expressions
console.log(1 + (2 + (3 + (4 + (5 + 6)))))

View File

@ -0,0 +1,29 @@
#let template(doc) = {
set page(paper: "a4", margin: (x: 2cm, y: 3cm))
set heading(numbering: "1.1")
set par(justify: true, leading: 0.55em)
show heading: it => {
set block(above: 1.6em, below: 1em)
it
}
doc
}
#show: template
= Typst
Typst is a markup language for typesetting documents. It is designed to be an
alternative to LaTeX and other document processing tools.
This is a #[nested section #[of text with #[multiple layers of nesting.]]]
Maths can either be typeset inline: $A = pi r^2$; or as a separate block:
$ frac(a^(2x), (5x + (3))) $
We can also put #[maths inside other content blocks: $V = 4/3 (pi r^3)$].
// vim:ft=typst

View File

@ -0,0 +1,140 @@
// Comment
`timescale 1ns/1ns
`default_nettype none
`include "filename.svh"
typedef enum {
A,
B,
C
} Enum_t;
module test #(
parameter int PARAM = 1
) (
input logic[15:0] a,
input logic[15:0] b,
output logic[15:0] c
);
logic[15:0][8:0] packed_data;
logic[8:0] to_be_casted;
divu #(
.WIDTH(24),
.FBITS(15)
) divider (
.clk(i_clk),
.rst(div_rst_actual),
.start(div_start),
.valid(o_avg_rdy),
.done(),
.dbz(),
.ovf(),
.busy(div_busy),
.a(div_dividend),
.b(div_divisor),
.val(div_result_q15_9)
);
always_comb begin
if (a > b) begin
c = 15'd1;
end else if ((a == b) || (a == c)) begin
c = 15'd2;
to_be_casted = 32'(c);
if (c == 15'd2) begin
c = 15'd3;
packed_data[2][3] = 8'd4;
end
end
end
always_ff @(posedge a) begin
c <= ((a + b) + b);
end
endmodule
// This module implements an unsigned fixed point divider.
// Source: https://projectf.io/posts/division-in-verilog/
module divu #(
parameter WIDTH=32, // width of numbers in bits (integer and fractional)
parameter FBITS=16 // fractional bits within WIDTH
) (
input wire logic clk, // clock
input wire logic rst, // reset
input wire logic start, // start calculation
output logic busy, // calculation in progress
output logic done, // calculation is complete (high for one tick)
output logic valid, // result is valid
output logic dbz, // divide by zero
output logic ovf, // overflow
input wire logic [WIDTH-1:0] a, // dividend (numerator)
input wire logic [WIDTH-1:0] b, // divisor (denominator)
output logic [WIDTH-1:0] val // result value: quotient
);
localparam FBITSW = (FBITS == 0) ? 1 : FBITS; // avoid negative vector width when FBITS=0
logic [WIDTH-1:0] b1; // copy of divisor
logic [WIDTH-1:0] quo, quo_next; // intermediate quotient
logic [WIDTH:0] acc, acc_next; // accumulator (1 bit wider)
localparam ITER = WIDTH + FBITS; // iteration count: unsigned input width + fractional bits
logic [$clog2(ITER)-1:0] i; // iteration counter
// division algorithm iteration
always_comb begin
if (acc >= {1'b0, b1}) begin
acc_next = acc - b1;
{acc_next, quo_next} = {acc_next[WIDTH-1:0], quo, 1'b1};
end else begin
{acc_next, quo_next} = {acc, quo} << 1;
end
end
// calculation control
always_ff @(posedge clk) begin
done <= 0;
if (start) begin
valid <= 0;
ovf <= 0;
i <= 0;
if (b == 0) begin // catch divide by zero
busy <= 0;
done <= 1;
dbz <= 1;
end else begin
busy <= 1;
dbz <= 0;
b1 <= b;
{acc, quo} <= {{WIDTH{1'b0}}, a, 1'b0}; // initialize calculation
end
end else if (busy) begin
if (i == ITER-1) begin // done
busy <= 0;
done <= 1;
valid <= 1;
val <= quo_next;
end else if (i == WIDTH-1 && quo_next[WIDTH-1:WIDTH-FBITSW] != 0) begin // overflow?
busy <= 0;
done <= 1;
ovf <= 1;
val <= 0;
end else begin // next iteration
i <= i + 1;
acc <= acc_next;
quo <= quo_next;
end
end
if (rst) begin
busy <= 0;
done <= 0;
valid <= 0;
dbz <= 0;
ovf <= 0;
val <= 0;
end
end
endmodule

View File

@ -0,0 +1,52 @@
// Comment
`timescale 1ns/1ns
`default_nettype none
`include "filename.vh"
module test #(
parameter PARAM = 1
) (
input reg[15:0] a,
input reg[15:0] b,
output reg[15:0] c
);
logic[15:0][8:0] packed_data;
always @* begin
if (a > b) begin
c = 15'd1;
end else if ((a == b) || (a == c)) begin
c = 15'd2;
if (c == 15'd2) begin
c = 15'd3;
packed_data[2][3] = 8'd4;
end
end
end
endmodule
module test2 #(
parameter PARAM = 1
) (
input reg[15:0] a,
input reg[15:0] b,
output reg[15:0] c
);
logic[15:0][8:0] packed_data;
always @* begin
if (a > b) begin
c = 15'd1;
end else if ((a == b) || (a == c)) begin
c = 15'd2;
if (c == 15'd2) begin
c = 15'd3;
packed_data[2][3] = 8'd4;
end
end
end
endmodule

View File

@ -0,0 +1,14 @@
let g:my_list = [[[1]]]
let g:my_dict = {
\'a': {
\'b': {
\'c': {},
\}
\}
\ }
echo string(1 + (2 + (3 + 4)))
echo string(-(3))
echo string((5)-(3))
echo string((1) ? (2) : (3))
echo ((('Hello, world!')))

View File

@ -0,0 +1,10 @@
<!-- A template element written in Pug -->
<template lang="pug">
| ErrorLayout
| {{ errCode }}
| {{ $t(errMsg) }}
a-button(type="primary" @click="goToHome") Go to home
template#footer
a-button(type="primary" @click="goToHome") {{ $t(errMsg) }}
</template>

View File

@ -0,0 +1,39 @@
<!-- A plain default Vue.js program using the default languages -->
<template>
{{ errCode }}
{{ $t(errMsg) }}
<a-button type="primary" @click="goToHome">goToHome</a-button>
<template #footer>
<a-button type="primary" @click="goToHome">{{ $t(errMsg) }}</a-button>
<div>
<p>Hello<br/>world</p>
<hr/>
</div>
</template>
</template>
<script setup>
// Template strings
let who = 'world';
console.log(`Hello, ${who}`);
// Nested object
let some_object = {
a: {
b: {
c: {},
}
}
};
</script>
<style>
.foo {
color: #ffffff;
}
@media (not (color)) {
.foo {
color: #ffffff;
}
}
</style>

View File

@ -0,0 +1,18 @@
<!-- A style elemet written in SCSS -->
<style lang="scss" scoped>
.foo {
color: red;
background: #000;
.bar {
color: red;
cursor: pointer;
}
}
@media (not (color)) {
.foo {
color: #ffffff;
}
}
</style>

View File

@ -0,0 +1,14 @@
<!-- A script element in Typescript -->
<script setup lang="ts">
// Function with nested function
function add(x: number, y: number): number {
function iter(i: number, acc: number) {
if (i == 0) {
return accu;
}
return iter(i - 1, acc + 1);
}
return iter(y, x)
}
</script>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example of MathML embedded in an XHTML file</title>
<meta name="description" content="Example of MathML embedded in an XHTML file"/>
</head>
<body>
<h1>Example of MathML embedded in an XHTML file</h1>
<p>
The area of a circle is
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mi>&#x03C0;<!-- π --></mi>
<mo>&#x2062;<!-- &InvisibleTimes; --></mo>
<msup>
<mi>r</mi>
<mn>2</mn>
</msup>
</math>
.
</p>
</body>
</html>

View File

@ -0,0 +1,25 @@
json_compatibility:
{
"foo": "bar",
"bar": {
"baz": [
[
[[['Hello, world!']]]
]
]
},
"key": {
"key": {
"key": {
"key": {
"key": "value"
}
}
}
}
}
list_of_objects:
- { key1: value, key2: value, key3: value }
- { key1: value, key2: value, key3: value } # A comment
- { key1: { key2: { key3: value, key4: value, key5: value } } } # Nested map

View File

@ -0,0 +1,86 @@
const std = @import("std");
const Void = struct {};
const MyBool = enum {
my_true,
my_false,
};
const SomeUnion = union(enum) {
top: u0,
kek: u1,
};
comptime {
const a: anyerror!SomeUnion = SomeUnion{.top = 0};
const b = switch (a catch |err| err) {
SomeUnion.top => |val| val,
SomeUnion.kek => |val| val,
else => undefined,
};
_ = b;
}
pub fn main() !void {
const some_type: type = *[][:8][*][*:.{ .mqu = false }]u123;
_ = some_type;
const stoqn = [_]u8{ 'k', 'o', 'l', 'e', 'v' };
std.debug.print("My last {s} is {s} and it's first letter is {s}\n", .{ "name", stoqn, [_]u8{ stoqn[0] } });
// stdout is for the actual output of your application, for example if you
// are implementing gzip, then only the compressed bytes should be sent to
// stdout, not any debugging messages.
const stdout_file = blk: {
break :blk std.io.getStdOut().writer();
};
var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer();
switch (6) {
5 => undefined,
_ => {
try stdout.print("Run `zig build test` to run the tests.\n", .{});
},
}
if (false) {
const k = undefined;
const a = undefined;
{
asm volatile (""
: [_] "=r,m" (k)
: [_] "r,m" (a)
: ""
);
}
} else if (true) {
for ("proba", 0..) |c, i| {
_ = c;
_ = i;
}
} else {
while (false) {
// ...
}
}
try bw.flush(); // don't forget to flush!
}
const truth linksection("lambda") = "calculus";
fn foo(a: *opaque {}) callconv(.C) void {
_ = a;
}
test "simple test" {
var list = std.ArrayList(i32).init(std.testing.allocator);
defer list.deinit(); // try commenting this out and see if zig detects the memory leak!
try list.append(42);
try std.testing.expectEqual(@as(i32, 42), list.pop());
}

View File

@ -0,0 +1,71 @@
#!/nix/store/306znyj77fv49kwnkpxmb0j2znqpa8bj-bash-5.2p26/bin/sh
# SPDX-License-Identifier: Unlicense
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or distribute
# this software, either in source code form or as a compiled binary, for any
# purpose, commercial or non-commercial, and by any means.
#
# In jurisdictions that recognize copyright laws, the author or authors of
# this software dedicate any and all copyright interest in the software to
# the public domain. We make this dedication for the benefit of the public
# at large and to the detriment of our heirs and successors. We intend this
# dedication to be an overt act of relinquishment in perpetuity of all
# present and future rights to this software under copyright law.
#
# 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 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.
#
# For more information, please refer to <https://unlicense.org/>
# A shim which acts as a command-line interface adapter to use Neovim as a Lua
# interpreter.
# Set custom XDG base directory paths to isolate the test Neovim from the
# user's own configuration and data files.
export XDG_CONFIG_HOME='test/xdg/config/'
export XDG_STATE_HOME='test/xdg/local/state/'
export XDG_DATA_HOME='test/xdg/local/share/'
# Handle Lua command-line arguments; not all options are supported
while getopts 'ilEve:' opt; do
case $opt in
e) lua_expr=$OPTARG;;
v) nvim --version; exit;;
i | l | E) echo "Option '$opt' not supported by shim"; exit 1;;
esac
done
# We need to add this plugin to the custom configuration. The easiest way is
# to create a symlink. Why not always have a symlink in the project? The Lua
# language server will search for Lua files in every directory, so if it enters
# the symlink it will be trapped in a cycle. What we do instead is create the
# symlink only for the duration of a test session and remove it again
# afterwards.
# We need separate symlinks if we want to run different tasks in parallel.
# Otherwise the one the finishes first would delete the symlink from underneath
# the one that is still running.
uuid=$(uuidgen)
mkdir -p ${XDG_DATA_HOME}/nvim/site/pack/self-${uuid}/start/
ln -fs $(pwd) ${XDG_DATA_HOME}/nvim/site/pack/self-${uuid}/start/
if [ -n "$lua_expr" ]; then
nvim --headless -c "lua $lua_expr" -c 'quitall!'
else
# We have to explicitly enable plugins, see ':h -l'
nvim --cmd 'set loadplugins' -l $@
fi
exit_code=$?
rm -rf ${XDG_DATA_HOME}/nvim/site/pack/self-${uuid}/
exit $exit_code

View File

@ -0,0 +1,177 @@
# Lorem Ipsum stress test
This is a large Markdown file with other languages injected.
```lua
print 'This is an injected language'
print({{{{{{{}}}}}}})
```
```markdown
Injected markdown.
~~~lua
print 'Injected Lua'
print({{{{}}}})
vim.cmd[[echo str([])]]
vim.cmd[[
echo 'Injected vim in injected Lua'
echo str([])
]]
~~~
More injected markdown.
```
## Cupit Phoce sonus
Lorem markdownum acernas. **Ignis ore amplius** dixit, supremumque miserere
vinoque peti tendit plebe ergo aguntur gerere expulsa, post loca sinebat. Nostra
minor comas saevit; quos rerum de ipsa, est bis [semine](http://caede.com/)
Saturnia saepius flet, sim. Antro remis patet genitam pariterque ipsum dum socia
vicit, tu nocens sororum? Hippomenes momentaque solusque Minyis
[Deucalion](http://anus.org/nec-tellus) aevo poena, voces instant consorte
fraternos occiderat tangit posita solo vellera me sanguis!
```vim
echo 'This is an injected language'
echo str([[[[[[[[[]]]]]]]]])
```
Fata quae: **falsi**: pares dea [agmine
hospite](http://www.quo-retro.net/sublimis) catenas? [Morte](http://corpus.net/)
ad putes. Dicentem Chariclo vidit!
```c
puts("This is an injected language")
{
{
{
{
{
return ((((((2)))))) + ((((3))))
}
}
}
}
}
```
```c
puts("This is a second c code block")
```
```c
puts("This is a third c code block")
```
> Delius irascere cuncti Argolis, femineis **ubi est** relatis Tityos supple
> alebat excusat animalia. Qua licet gentem laniaverat vidit Chromin: ut Thracum
> Lacedaemoniumque parantur tribuitque. Nec Acoete rogat satis gramine: mollibus
> regis, sermonibus deus, lumina at.
```python
print('This is an injected language')
print([[[[[[[[]]]]]]]])
```
## Silentia foret
Requievit eventuque sociis ordine ebur referam iussam accessit temperie in
fugant nymphas te ramos puellas, per. Posse per ait pressa dammas. Quam proximus
scopulum sonanti accensus ab *auras* nostra ambo forte medicina repulsa et quae
occuluere et.
```bash
echo 'This is an injected language'
echo $(echo $(echo $(echo $(echo 'test'))))
````
Aliquam sem et tortor consequat id porta. Lectus urna duis convallis convallis
tellus id interdum velit. Diam volutpat commodo sed egestas egestas fringilla
phasellus. Amet commodo nulla facilisi nullam vehicula ipsum a arcu cursus. Ac
turpis egestas maecenas pharetra convallis posuere morbi. Facilisis volutpat
est velit egestas dui id ornare arcu. Lacus sed turpis tincidunt id aliquet. Et
netus et malesuada fames ac turpis egestas sed tempus. Cursus in hac habitasse
platea. Lectus proin nibh nisl condimentum id.
```json
[[[[[[[[["This is an injected language"]]]]]]]]]
```
Pictos excipiunt saxea. Equorum esse fac iactatis resolvit fumantis tota faveas
ortu imago insanis. Nil Typhoea ramis timido teneris nunc septem, vale furor.
```html
<div>
<div>
<div>
<div>
<div>
<p>This is an injected language</p>
</div>
</div>
</div>
</div>
</div>
```
1. Cadmeides condi Pelagonaque manibus petit moderator sua
2. Et absumere dextera rediit
3. Suis priorum dixit flendo
4. Sic contingit mihi
5. Nec tenet adsiduis tua vidit invitaque caeli
```css
@media (not (color)) {
.foo {
color: #ffffff;
}
}
```
Sternentem raptamque meam requiret retentis et natum et, quoque, at tamen
peccasse *manet*. Tamen cuius, increpat solvunt meritum tibi veniente
semihomines ligo corpus de arma fata!
```javascript
console.log('This is an injected language')
console.log(1 + (2 + (3 + (4 + (5 + (6 + (7 + (8 + 9))))))))
```
## Aliquam sub nulla tandem movere oscula pulcherrima
In Cybeleia mearum illos est, superest viscera fugienti fabula Thisbes agros.
Cum nepotem quae aurum qua abest harundine, caput et noverca!
Caelum fore domus nox noxque bello Tempe erat ruent perstant te prope. Bis illis
ea maritum, pro est ferrum mihi ictu Cyllenius. Rogat ad et sed taedae Iphis, et
ad sinus afueram? Huc umbras: **asper iuro postquam**: ordine dum qualia diro
equorum nisi atque!
ntfs_party_memory.graphicPortalMask(drive_tween, infringementCompression);
brouterHard = thinFios;
arp.pppEpsUnmount -= refresh.wavelength(compression(wiki, 5), serverIpv) +
room.paper(kindleLeopardBarcraft, gigo) + serial;
Et opem primitias sine agrestes, me puto illo cum puer. Loca aptabat sed munera
crede, quem **veris volubilibus maximus** Desierat
[lanificae](http://natacognatas.net/ut-plus.php) inponit *pars* paratas est
anser. Tremoribus iste [furit](http://ira.net/)! Alis potiere praedelassat
increvit Cytherea, mediis in modo mitissima ad feto amavit. [Moenia
illo](http://www.estygius.net/nisi.php) ille, ars ramis alis tamen mihi iste
Naupliades et diu molles ultro agendo ire nullo.
> Vicimus locuturo, quod [pars](http://www.idomeneus.org/unus) iam hunc
> lacusque, toto. Partes **per** nec latuisse nullus isto dolore iungimus nervi.
> Illic vult cucurri, capit digitis longus nymphaeque plagis viribus virgae,
> ascendere sederunt urbs, aspergine trunca. Frigus [Leucothoen
> adsiduae](http://non.org/) duos; quae dari est Amorque domuisse proles
> quaerenti **haec**.
Ac rebus merentem, portas, eandem dea versos [laborum ab
posse](http://lignumsuccessibus.io/postquam) in mirata ad. Chirona terras;
aether morer proelia accedere, praesagaque avido clavae vestra, tamen. Vocas
Quirini sanguine insignia, aemula mea nomen [credere](http://pennas.io/); non
possit primoque bisque. Omni dea vultus, huc prodierat auras de per vel despice
retro aut. Aut generum timore, nam succedit, in sui Hector ramos loquuntur,
naias, traiecit.

View File

@ -0,0 +1,85 @@
local Stack = require 'rainbow-delimiters.stack'
describe('The stack data structure #stack', function()
describe('The empty stack', function()
local stack
before_each(function() stack = Stack.new() end)
it('Can instantiate an empty stack', function()
assert.is_not._nil(stack)
end)
it('Is empty', function()
assert.is.equal(0, stack:size())
end)
it('Can push items onto the stack', function ()
stack:push('a')
stack:push('b')
assert.is.equal(2, stack:size())
end)
end)
describe('Stack with contents', function()
local stack, items
before_each(function()
items = {'a', 'b', 'c', 'd'}
stack = Stack.new(items)
end)
it('Can instantiate stack with contents', function()
assert.is_not._nil(stack)
end)
it('Holds the correct amount of items', function()
assert.is.equal(4, stack:size())
end)
it('Can inspect the topmost element', function ()
local top = stack:peek()
assert.is.equal('d', top)
end)
it('Can pop items off the stack in reverse order', function()
for i = 3, 0, -1 do
local val = stack:pop()
assert.is.equal(items[i + 1], val)
assert.is.equal(i, stack:size())
end
end)
it('Can push an item onto the stack', function()
local val = 'e'
stack:push(val)
assert.is.equal(5, stack:size())
assert.is.equal(val, stack:pop())
end)
end)
describe('Stack traversal', function()
it('Traverses the stack from top to bottom', function()
local counter = 1
local expected_indices = {4, 3, 2, 1}
local expected_values = {'d', 'c', 'b', 'a'}
local stack = Stack.new {'a', 'b', 'c', 'd'}
for i, v in stack:iter() do
local index = expected_indices[counter]
local value = expected_values[ counter]
assert.is.equal(index, i)
assert.is.equal(value, v)
counter = counter + 1
end
end)
it('Does nothing for an empty stack', function()
local stack = Stack.new()
for _i, _v in stack:iter() do
-- This must never run because the stack is empty
assert.is_true(false)
end
end)
end)
end)

View File

@ -0,0 +1,6 @@
.. default-role:: code
This directory exists so that we can point Neovim to its sub-directories
instead of the default XDG base directories. This isolates the Neovim instance
used during testing from the user's own configuration and data.

View File

@ -0,0 +1,11 @@
-- Tree-sitter highlighting needs to be running, otherwise rainbow highlighting
-- won't get updated on tree changes. The following autocommand enables it on
-- every file type change.
local function on_file_type(_args)
vim.treesitter.start()
end
vim.api.nvim_create_autocmd('FileType', {pattern = '*', callback = on_file_type})

View File

@ -0,0 +1,35 @@
-- Custom configuration for Busted
local say = require 'say'
local assert = require 'luassert'
local filter = vim.fn.filter
local NVIM_STATE_KEY = {}
local function nvim(state, args, level)
assert(args.n > 0, "No Neovim channel provided to the modifier")
assert(rawget(state, NVIM_STATE_KEY) == nil, "Neovim already set")
rawset(state, NVIM_STATE_KEY, args[1])
return state
end
---Asserts that there are Rainbow Delimiters extmarks at the given position
---@param arguments integer[] Row and column, both zero-based
local function has_extmarks_at(_state, arguments, lang)
local nvim = rawget(_state, NVIM_STATE_KEY)
assert(nvim ~= nil, 'No Neovim channel set, use the nvim modifier to set the channel')
local row, column = arguments[1], arguments[2]
local nsid = nvim:exec_lua('return require("rainbow-delimiters.lib").nsids[...]', {lang})
local extmarks = nvim:exec_lua('return vim.inspect_pos(...).extmarks', {0, row, column})
filter(extmarks, function(_, v) return v.ns_id == nsid end)
return #extmarks > 0
end
say:set('assertion.extmarks_at.positive', 'Expected extmarks at (%s, %s)')
say:set('assertion.extmarks_at.negative', 'Expected no extmarks at (%s, %s)')
assert:register(
'assertion', 'has_extmarks_at', has_extmarks_at,
'assertion.has_extmarks_at.positive', 'assertion.has_extmarks_at.negative')
assert:register('modifier', 'nvim', nvim)

View File

@ -0,0 +1,14 @@
local get_runtime_file = vim.api.nvim_get_runtime_file
local parser_pattern = 'parser/%s.*'
---Wrapper around the `:TSinstall` command which will only install a parser if
---it is not installed yet
---@param lang string Language to install
function TSEnsure(lang, ...)
for _, l in ipairs({lang, ...}) do
local parsers = get_runtime_file(parser_pattern:format(l), true)
if #parsers == 0 then
vim.cmd {cmd = 'TSInstallSync', args = {l}}
end
end
end