fix: revert stylua config

This commit is contained in:
Barrett Ruth 2025-09-15 18:10:35 -04:00
parent fe4cf2b680
commit d4fd02499d
19 changed files with 1363 additions and 1579 deletions

View file

@ -1,6 +1,6 @@
vim.opt_local.number = false
vim.opt_local.relativenumber = false
vim.opt_local.statuscolumn = ''
vim.opt_local.signcolumn = 'no'
vim.opt_local.statuscolumn = ""
vim.opt_local.signcolumn = "no"
vim.opt_local.wrap = true
vim.opt_local.linebreak = true

View file

@ -1,6 +1,6 @@
vim.opt_local.number = false
vim.opt_local.relativenumber = false
vim.opt_local.statuscolumn = ''
vim.opt_local.signcolumn = 'no'
vim.opt_local.statuscolumn = ""
vim.opt_local.signcolumn = "no"
vim.opt_local.wrap = true
vim.opt_local.linebreak = true

View file

@ -1,7 +1,7 @@
vim.opt_local.number = false
vim.opt_local.relativenumber = false
vim.opt_local.statuscolumn = ''
vim.opt_local.signcolumn = 'no'
vim.opt_local.statuscolumn = ""
vim.opt_local.signcolumn = "no"
vim.opt_local.wrap = true
vim.opt_local.linebreak = true
vim.opt_local.modifiable = true

View file

@ -1,6 +1,6 @@
vim.filetype.add({
extension = {
cpin = 'cpin',
cpout = 'cpout',
cpin = "cpin",
cpout = "cpout",
},
})

View file

@ -18,17 +18,17 @@
local M = {}
local cache_file = vim.fn.stdpath('data') .. '/cp-nvim.json'
local cache_file = vim.fn.stdpath("data") .. "/cp-nvim.json"
local cache_data = {}
---@param platform string
---@return number?
local function get_expiry_date(platform)
vim.validate({
platform = { platform, 'string' },
platform = { platform, "string" },
})
if platform == 'cses' then
if platform == "cses" then
return os.time() + (30 * 24 * 60 * 60)
end
return nil
@ -39,11 +39,11 @@ end
---@return boolean
local function is_cache_valid(contest_data, platform)
vim.validate({
contest_data = { contest_data, 'table' },
platform = { platform, 'string' },
contest_data = { contest_data, "table" },
platform = { platform, "string" },
})
if platform ~= 'cses' then
if platform ~= "cses" then
return true
end
@ -67,7 +67,7 @@ function M.load()
return
end
local ok, decoded = pcall(vim.json.decode, table.concat(content, '\n'))
local ok, decoded = pcall(vim.json.decode, table.concat(content, "\n"))
if ok then
cache_data = decoded
else
@ -76,9 +76,9 @@ function M.load()
end
function M.save()
vim.fn.mkdir(vim.fn.fnamemodify(cache_file, ':h'), 'p')
vim.fn.mkdir(vim.fn.fnamemodify(cache_file, ":h"), "p")
local encoded = vim.json.encode(cache_data)
vim.fn.writefile(vim.split(encoded, '\n'), cache_file)
vim.fn.writefile(vim.split(encoded, "\n"), cache_file)
end
---@param platform string
@ -86,8 +86,8 @@ end
---@return ContestData?
function M.get_contest_data(platform, contest_id)
vim.validate({
platform = { platform, 'string' },
contest_id = { contest_id, 'string' },
platform = { platform, "string" },
contest_id = { contest_id, "string" },
})
if not cache_data[platform] then
@ -111,9 +111,9 @@ end
---@param problems Problem[]
function M.set_contest_data(platform, contest_id, problems)
vim.validate({
platform = { platform, 'string' },
contest_id = { contest_id, 'string' },
problems = { problems, 'table' },
platform = { platform, "string" },
contest_id = { contest_id, "string" },
problems = { problems, "table" },
})
if not cache_data[platform] then
@ -122,7 +122,7 @@ function M.set_contest_data(platform, contest_id, problems)
cache_data[platform][contest_id] = {
problems = problems,
scraped_at = os.date('%Y-%m-%d'),
scraped_at = os.date("%Y-%m-%d"),
expires_at = get_expiry_date(platform),
}
@ -133,8 +133,8 @@ end
---@param contest_id string
function M.clear_contest_data(platform, contest_id)
vim.validate({
platform = { platform, 'string' },
contest_id = { contest_id, 'string' },
platform = { platform, "string" },
contest_id = { contest_id, "string" },
})
if cache_data[platform] and cache_data[platform][contest_id] then
@ -149,13 +149,12 @@ end
---@return TestCase[]?
function M.get_test_cases(platform, contest_id, problem_id)
vim.validate({
platform = { platform, 'string' },
contest_id = { contest_id, 'string' },
problem_id = { problem_id, { 'string', 'nil' }, true },
platform = { platform, "string" },
contest_id = { contest_id, "string" },
problem_id = { problem_id, { "string", "nil" }, true },
})
local problem_key = problem_id and (contest_id .. '_' .. problem_id)
or contest_id
local problem_key = problem_id and (contest_id .. "_" .. problem_id) or contest_id
if not cache_data[platform] or not cache_data[platform][problem_key] then
return nil
end
@ -168,14 +167,13 @@ end
---@param test_cases TestCase[]
function M.set_test_cases(platform, contest_id, problem_id, test_cases)
vim.validate({
platform = { platform, 'string' },
contest_id = { contest_id, 'string' },
problem_id = { problem_id, { 'string', 'nil' }, true },
test_cases = { test_cases, 'table' },
platform = { platform, "string" },
contest_id = { contest_id, "string" },
problem_id = { problem_id, { "string", "nil" }, true },
test_cases = { test_cases, "table" },
})
local problem_key = problem_id and (contest_id .. '_' .. problem_id)
or contest_id
local problem_key = problem_id and (contest_id .. "_" .. problem_id) or contest_id
if not cache_data[platform] then
cache_data[platform] = {}
end

View file

@ -48,7 +48,7 @@
---@field filename? fun(contest: string, contest_id: string, problem_id?: string, config: cp.Config, language?: string): string
local M = {}
local constants = require('cp.constants')
local constants = require("cp.constants")
---@type cp.Config
M.defaults = {
@ -68,34 +68,34 @@ M.defaults = {
---@return cp.Config
function M.setup(user_config)
vim.validate({
user_config = { user_config, { 'table', 'nil' }, true },
user_config = { user_config, { "table", "nil" }, true },
})
if user_config then
vim.validate({
contests = { user_config.contests, { 'table', 'nil' }, true },
snippets = { user_config.snippets, { 'table', 'nil' }, true },
hooks = { user_config.hooks, { 'table', 'nil' }, true },
debug = { user_config.debug, { 'boolean', 'nil' }, true },
tile = { user_config.tile, { 'function', 'nil' }, true },
filename = { user_config.filename, { 'function', 'nil' }, true },
contests = { user_config.contests, { "table", "nil" }, true },
snippets = { user_config.snippets, { "table", "nil" }, true },
hooks = { user_config.hooks, { "table", "nil" }, true },
debug = { user_config.debug, { "boolean", "nil" }, true },
tile = { user_config.tile, { "function", "nil" }, true },
filename = { user_config.filename, { "function", "nil" }, true },
})
if user_config.hooks then
vim.validate({
before_run = {
user_config.hooks.before_run,
{ 'function', 'nil' },
{ "function", "nil" },
true,
},
before_debug = {
user_config.hooks.before_debug,
{ 'function', 'nil' },
{ "function", "nil" },
true,
},
setup_code = {
user_config.hooks.setup_code,
{ 'function', 'nil' },
{ "function", "nil" },
true,
},
})
@ -104,26 +104,16 @@ function M.setup(user_config)
if user_config.contests then
for contest_name, contest_config in pairs(user_config.contests) do
for lang_name, lang_config in pairs(contest_config) do
if type(lang_config) == "table" and lang_config.extension then
if
type(lang_config) == 'table' and lang_config.extension
then
if
not vim.tbl_contains(
vim.tbl_keys(constants.filetype_to_language),
lang_config.extension
)
not vim.tbl_contains(vim.tbl_keys(constants.filetype_to_language), lang_config.extension)
then
error(
("Invalid extension '%s' for language '%s' in contest '%s'. Valid extensions: %s"):format(
lang_config.extension,
lang_name,
contest_name,
table.concat(
vim.tbl_keys(
constants.filetype_to_language
),
', '
)
table.concat(vim.tbl_keys(constants.filetype_to_language), ", ")
)
)
end
@ -133,7 +123,7 @@ function M.setup(user_config)
end
end
local config = vim.tbl_deep_extend('force', M.defaults, user_config or {})
local config = vim.tbl_deep_extend("force", M.defaults, user_config or {})
return config
end
@ -142,8 +132,8 @@ end
---@return string
local function default_filename(contest_id, problem_id)
vim.validate({
contest_id = { contest_id, 'string' },
problem_id = { problem_id, { 'string', 'nil' }, true },
contest_id = { contest_id, "string" },
problem_id = { problem_id, { "string", "nil" }, true },
})
if problem_id then

View file

@ -1,10 +1,10 @@
local M = {}
M.PLATFORMS = { 'atcoder', 'codeforces', 'cses' }
M.ACTIONS = { 'run', 'debug', 'test', 'next', 'prev' }
M.PLATFORMS = { "atcoder", "codeforces", "cses" }
M.ACTIONS = { "run", "debug", "test", "next", "prev" }
M.CPP = 'cpp'
M.PYTHON = 'python'
M.CPP = "cpp"
M.PYTHON = "python"
---@type table<string, string>
M.filetype_to_language = {
@ -17,8 +17,8 @@ M.filetype_to_language = {
---@type table<string, string>
M.canonical_filetypes = {
[M.CPP] = 'cpp',
[M.PYTHON] = 'python',
[M.CPP] = "cpp",
[M.PYTHON] = "python",
}
return M

View file

@ -6,9 +6,9 @@
---@field timed_out boolean
local M = {}
local logger = require('cp.log')
local logger = require("cp.log")
local constants = require('cp.constants')
local constants = require("cp.constants")
local filetype_to_language = constants.filetype_to_language
---@param source_file string
@ -16,16 +16,13 @@ local filetype_to_language = constants.filetype_to_language
---@return string
local function get_language_from_file(source_file, contest_config)
vim.validate({
source_file = { source_file, 'string' },
contest_config = { contest_config, 'table' },
source_file = { source_file, "string" },
contest_config = { contest_config, "table" },
})
local extension = vim.fn.fnamemodify(source_file, ':e')
local language = filetype_to_language[extension]
or contest_config.default_language
logger.log(
('detected language: %s (extension: %s)'):format(language, extension)
)
local extension = vim.fn.fnamemodify(source_file, ":e")
local language = filetype_to_language[extension] or contest_config.default_language
logger.log(("detected language: %s (extension: %s)"):format(language, extension))
return language
end
@ -34,15 +31,15 @@ end
---@return string[]
local function substitute_template(cmd_template, substitutions)
vim.validate({
cmd_template = { cmd_template, 'table' },
substitutions = { substitutions, 'table' },
cmd_template = { cmd_template, "table" },
substitutions = { substitutions, "table" },
})
local result = {}
for _, arg in ipairs(cmd_template) do
local substituted = arg
for key, value in pairs(substitutions) do
substituted = substituted:gsub('{' .. key .. '}', value)
substituted = substituted:gsub("{" .. key .. "}", value)
end
table.insert(result, substituted)
end
@ -55,9 +52,9 @@ end
---@return string[]
local function build_command(cmd_template, executable, substitutions)
vim.validate({
cmd_template = { cmd_template, 'table' },
executable = { executable, { 'string', 'nil' }, true },
substitutions = { substitutions, 'table' },
cmd_template = { cmd_template, "table" },
executable = { executable, { "string", "nil" }, true },
substitutions = { substitutions, "table" },
})
local cmd = substitute_template(cmd_template, substitutions)
@ -68,25 +65,25 @@ local function build_command(cmd_template, executable, substitutions)
end
local signal_codes = {
[128] = 'SIGILL',
[130] = 'SIGINT',
[131] = 'SIGQUIT',
[132] = 'SIGILL',
[133] = 'SIGTRAP',
[134] = 'SIGABRT',
[135] = 'SIGBUS',
[136] = 'SIGFPE',
[137] = 'SIGKILL',
[138] = 'SIGUSR1',
[139] = 'SIGSEGV',
[140] = 'SIGUSR2',
[141] = 'SIGPIPE',
[142] = 'SIGALRM',
[143] = 'SIGTERM',
[128] = "SIGILL",
[130] = "SIGINT",
[131] = "SIGQUIT",
[132] = "SIGILL",
[133] = "SIGTRAP",
[134] = "SIGABRT",
[135] = "SIGBUS",
[136] = "SIGFPE",
[137] = "SIGKILL",
[138] = "SIGUSR1",
[139] = "SIGSEGV",
[140] = "SIGUSR2",
[141] = "SIGPIPE",
[142] = "SIGALRM",
[143] = "SIGTERM",
}
local function ensure_directories()
vim.system({ 'mkdir', '-p', 'build', 'io' }):wait()
vim.system({ "mkdir", "-p", "build", "io" }):wait()
end
---@param language_config table
@ -94,33 +91,26 @@ end
---@return {code: integer, stderr: string}
local function compile_generic(language_config, substitutions)
vim.validate({
language_config = { language_config, 'table' },
substitutions = { substitutions, 'table' },
language_config = { language_config, "table" },
substitutions = { substitutions, "table" },
})
if not language_config.compile then
logger.log('no compilation step required')
return { code = 0, stderr = '' }
logger.log("no compilation step required")
return { code = 0, stderr = "" }
end
local compile_cmd =
substitute_template(language_config.compile, substitutions)
logger.log(('compiling: %s'):format(table.concat(compile_cmd, ' ')))
local compile_cmd = substitute_template(language_config.compile, substitutions)
logger.log(("compiling: %s"):format(table.concat(compile_cmd, " ")))
local start_time = vim.uv.hrtime()
local result = vim.system(compile_cmd, { text = true }):wait()
local compile_time = (vim.uv.hrtime() - start_time) / 1000000
if result.code == 0 then
logger.log(('compilation successful (%.1fms)'):format(compile_time))
logger.log(("compilation successful (%.1fms)"):format(compile_time))
else
logger.log(
('compilation failed (%.1fms): %s'):format(
compile_time,
result.stderr
),
vim.log.levels.WARN
)
logger.log(("compilation failed (%.1fms): %s"):format(compile_time, result.stderr), vim.log.levels.WARN)
end
return result
@ -132,12 +122,12 @@ end
---@return ExecuteResult
local function execute_command(cmd, input_data, timeout_ms)
vim.validate({
cmd = { cmd, 'table' },
input_data = { input_data, 'string' },
timeout_ms = { timeout_ms, 'number' },
cmd = { cmd, "table" },
input_data = { input_data, "string" },
timeout_ms = { timeout_ms, "number" },
})
logger.log(('executing: %s'):format(table.concat(cmd, ' ')))
logger.log(("executing: %s"):format(table.concat(cmd, " ")))
local start_time = vim.uv.hrtime()
@ -153,25 +143,16 @@ local function execute_command(cmd, input_data, timeout_ms)
local actual_code = result.code or 0
if result.code == 124 then
logger.log(
('execution timed out after %.1fms'):format(execution_time),
vim.log.levels.WARN
)
logger.log(("execution timed out after %.1fms"):format(execution_time), vim.log.levels.WARN)
elseif actual_code ~= 0 then
logger.log(
('execution failed (exit code %d, %.1fms)'):format(
actual_code,
execution_time
),
vim.log.levels.WARN
)
logger.log(("execution failed (exit code %d, %.1fms)"):format(actual_code, execution_time), vim.log.levels.WARN)
else
logger.log(('execution successful (%.1fms)'):format(execution_time))
logger.log(("execution successful (%.1fms)"):format(execution_time))
end
return {
stdout = result.stdout or '',
stderr = result.stderr or '',
stdout = result.stdout or "",
stderr = result.stderr or "",
code = actual_code,
time_ms = execution_time,
timed_out = result.code == 124,
@ -184,40 +165,31 @@ end
---@return string
local function format_output(exec_result, expected_file, is_debug)
vim.validate({
exec_result = { exec_result, 'table' },
expected_file = { expected_file, 'string' },
is_debug = { is_debug, 'boolean' },
exec_result = { exec_result, "table" },
expected_file = { expected_file, "string" },
is_debug = { is_debug, "boolean" },
})
local output_lines = { exec_result.stdout }
local metadata_lines = {}
if exec_result.timed_out then
table.insert(metadata_lines, '[code]: 124 (TIMEOUT)')
table.insert(metadata_lines, "[code]: 124 (TIMEOUT)")
elseif exec_result.code >= 128 then
local signal_name = signal_codes[exec_result.code] or 'SIGNAL'
table.insert(
metadata_lines,
('[code]: %d (%s)'):format(exec_result.code, signal_name)
)
local signal_name = signal_codes[exec_result.code] or "SIGNAL"
table.insert(metadata_lines, ("[code]: %d (%s)"):format(exec_result.code, signal_name))
else
table.insert(metadata_lines, ('[code]: %d'):format(exec_result.code))
table.insert(metadata_lines, ("[code]: %d"):format(exec_result.code))
end
table.insert(
metadata_lines,
('[time]: %.2f ms'):format(exec_result.time_ms)
)
table.insert(
metadata_lines,
('[debug]: %s'):format(is_debug and 'true' or 'false')
)
table.insert(metadata_lines, ("[time]: %.2f ms"):format(exec_result.time_ms))
table.insert(metadata_lines, ("[debug]: %s"):format(is_debug and "true" or "false"))
if vim.fn.filereadable(expected_file) == 1 and exec_result.code == 0 then
local expected_content = vim.fn.readfile(expected_file)
local actual_lines = vim.split(exec_result.stdout, '\n')
local actual_lines = vim.split(exec_result.stdout, "\n")
while #actual_lines > 0 and actual_lines[#actual_lines] == '' do
while #actual_lines > 0 and actual_lines[#actual_lines] == "" do
table.remove(actual_lines)
end
@ -231,15 +203,10 @@ local function format_output(exec_result, expected_file, is_debug)
end
end
table.insert(
metadata_lines,
('[matches]: %s'):format(matches and 'true' or 'false')
)
table.insert(metadata_lines, ("[matches]: %s"):format(matches and "true" or "false"))
end
return table.concat(output_lines, '')
.. '\n'
.. table.concat(metadata_lines, '\n')
return table.concat(output_lines, "") .. "\n" .. table.concat(metadata_lines, "\n")
end
---@param ctx ProblemContext
@ -247,9 +214,9 @@ end
---@param is_debug boolean
function M.run_problem(ctx, contest_config, is_debug)
vim.validate({
ctx = { ctx, 'table' },
contest_config = { contest_config, 'table' },
is_debug = { is_debug, 'boolean' },
ctx = { ctx, "table" },
contest_config = { contest_config, "table" },
is_debug = { is_debug, "boolean" },
})
ensure_directories()
@ -258,10 +225,7 @@ function M.run_problem(ctx, contest_config, is_debug)
local language_config = contest_config[language]
if not language_config then
vim.fn.writefile(
{ 'Error: No configuration for language: ' .. language },
ctx.output_file
)
vim.fn.writefile({ "Error: No configuration for language: " .. language }, ctx.output_file)
return
end
@ -271,8 +235,7 @@ function M.run_problem(ctx, contest_config, is_debug)
version = tostring(language_config.version),
}
local compile_cmd = is_debug and language_config.debug
or language_config.compile
local compile_cmd = is_debug and language_config.debug or language_config.compile
if compile_cmd then
local compile_result = compile_generic(language_config, substitutions)
if compile_result.code ~= 0 then
@ -281,35 +244,23 @@ function M.run_problem(ctx, contest_config, is_debug)
end
end
local input_data = ''
local input_data = ""
if vim.fn.filereadable(ctx.input_file) == 1 then
input_data = table.concat(vim.fn.readfile(ctx.input_file), '\n') .. '\n'
input_data = table.concat(vim.fn.readfile(ctx.input_file), "\n") .. "\n"
end
local run_cmd = build_command(
language_config.run,
language_config.executable,
substitutions
)
local exec_result =
execute_command(run_cmd, input_data, contest_config.timeout_ms)
local formatted_output =
format_output(exec_result, ctx.expected_file, is_debug)
local run_cmd = build_command(language_config.run, language_config.executable, substitutions)
local exec_result = execute_command(run_cmd, input_data, contest_config.timeout_ms)
local formatted_output = format_output(exec_result, ctx.expected_file, is_debug)
local output_buf = vim.fn.bufnr(ctx.output_file)
if output_buf ~= -1 then
vim.api.nvim_buf_set_lines(
output_buf,
0,
-1,
false,
vim.split(formatted_output, '\n')
)
vim.api.nvim_buf_set_lines(output_buf, 0, -1, false, vim.split(formatted_output, "\n"))
vim.api.nvim_buf_call(output_buf, function()
vim.cmd.write()
end)
else
vim.fn.writefile(vim.split(formatted_output, '\n'), ctx.output_file)
vim.fn.writefile(vim.split(formatted_output, "\n"), ctx.output_file)
end
end

View file

@ -1,94 +1,88 @@
local M = {}
local function check_nvim_version()
if vim.fn.has('nvim-0.10.0') == 1 then
vim.health.ok('Neovim 0.10.0+ detected')
if vim.fn.has("nvim-0.10.0") == 1 then
vim.health.ok("Neovim 0.10.0+ detected")
else
vim.health.error('cp.nvim requires Neovim 0.10.0+')
vim.health.error("cp.nvim requires Neovim 0.10.0+")
end
end
local function check_uv()
if vim.fn.executable('uv') == 1 then
vim.health.ok('uv executable found')
if vim.fn.executable("uv") == 1 then
vim.health.ok("uv executable found")
local result = vim.system({ 'uv', '--version' }, { text = true }):wait()
local result = vim.system({ "uv", "--version" }, { text = true }):wait()
if result.code == 0 then
vim.health.info('uv version: ' .. result.stdout:gsub('\n', ''))
vim.health.info("uv version: " .. result.stdout:gsub("\n", ""))
end
else
vim.health.warn(
'uv not found - install from https://docs.astral.sh/uv/ for problem scraping'
)
vim.health.warn("uv not found - install from https://docs.astral.sh/uv/ for problem scraping")
end
end
local function check_python_env()
local plugin_path = debug.getinfo(1, 'S').source:sub(2)
plugin_path = vim.fn.fnamemodify(plugin_path, ':h:h:h')
local venv_dir = plugin_path .. '/.venv'
local plugin_path = debug.getinfo(1, "S").source:sub(2)
plugin_path = vim.fn.fnamemodify(plugin_path, ":h:h:h")
local venv_dir = plugin_path .. "/.venv"
if vim.fn.isdirectory(venv_dir) == 1 then
vim.health.ok('Python virtual environment found at ' .. venv_dir)
vim.health.ok("Python virtual environment found at " .. venv_dir)
else
vim.health.warn(
'Python virtual environment not set up - run :CP command to initialize'
)
vim.health.warn("Python virtual environment not set up - run :CP command to initialize")
end
end
local function check_scrapers()
local plugin_path = debug.getinfo(1, 'S').source:sub(2)
plugin_path = vim.fn.fnamemodify(plugin_path, ':h:h:h')
local plugin_path = debug.getinfo(1, "S").source:sub(2)
plugin_path = vim.fn.fnamemodify(plugin_path, ":h:h:h")
local scrapers = { 'atcoder.py', 'codeforces.py', 'cses.py' }
local scrapers = { "atcoder.py", "codeforces.py", "cses.py" }
for _, scraper in ipairs(scrapers) do
local scraper_path = plugin_path .. '/scrapers/' .. scraper
local scraper_path = plugin_path .. "/scrapers/" .. scraper
if vim.fn.filereadable(scraper_path) == 1 then
vim.health.ok('Scraper found: ' .. scraper)
vim.health.ok("Scraper found: " .. scraper)
else
vim.health.error('Missing scraper: ' .. scraper)
vim.health.error("Missing scraper: " .. scraper)
end
end
end
local function check_luasnip()
local has_luasnip, luasnip = pcall(require, 'luasnip')
local has_luasnip, luasnip = pcall(require, "luasnip")
if has_luasnip then
vim.health.ok('LuaSnip integration available')
local snippet_count = #luasnip.get_snippets('all')
vim.health.info('LuaSnip snippets loaded: ' .. snippet_count)
vim.health.ok("LuaSnip integration available")
local snippet_count = #luasnip.get_snippets("all")
vim.health.info("LuaSnip snippets loaded: " .. snippet_count)
else
vim.health.info(
'LuaSnip not available - template expansion will be limited'
)
vim.health.info("LuaSnip not available - template expansion will be limited")
end
end
local function check_config()
vim.health.ok('Plugin ready')
vim.health.ok("Plugin ready")
local cp = require('cp')
local cp = require("cp")
local context = cp.get_current_context()
if context.platform then
local info = context.platform
if context.contest_id then
info = info .. ' ' .. context.contest_id
info = info .. " " .. context.contest_id
if context.problem_id then
info = info .. ' ' .. context.problem_id
info = info .. " " .. context.problem_id
end
end
vim.health.info('Current context: ' .. info)
vim.health.info("Current context: " .. info)
else
vim.health.info('No contest context set')
vim.health.info("No contest context set")
end
end
function M.check()
local version = require('cp.version')
vim.health.start('cp.nvim health check')
local version = require("cp.version")
vim.health.start("cp.nvim health check")
vim.health.info('Version: ' .. version.version)
vim.health.info("Version: " .. version.version)
check_nvim_version()
check_uv()

View file

@ -1,16 +1,16 @@
local M = {}
local config_module = require('cp.config')
local snippets = require('cp.snippets')
local execute = require('cp.execute')
local scrape = require('cp.scrape')
local window = require('cp.window')
local logger = require('cp.log')
local problem = require('cp.problem')
local cache = require('cp.cache')
local config_module = require("cp.config")
local snippets = require("cp.snippets")
local execute = require("cp.execute")
local scrape = require("cp.scrape")
local window = require("cp.window")
local logger = require("cp.log")
local problem = require("cp.problem")
local cache = require("cp.cache")
if not vim.fn.has('nvim-0.10.0') then
vim.notify('[cp.nvim]: requires nvim-0.10.0+', vim.log.levels.ERROR)
if not vim.fn.has("nvim-0.10.0") then
vim.notify("[cp.nvim]: requires nvim-0.10.0+", vim.log.levels.ERROR)
return {}
end
@ -29,24 +29,19 @@ local state = {
test_states = {},
}
local constants = require('cp.constants')
local constants = require("cp.constants")
local platforms = constants.PLATFORMS
local actions = constants.ACTIONS
local function set_platform(platform)
if not vim.tbl_contains(platforms, platform) then
logger.log(
('unknown platform. Available: [%s]'):format(
table.concat(platforms, ', ')
),
vim.log.levels.ERROR
)
logger.log(("unknown platform. Available: [%s]"):format(table.concat(platforms, ", ")), vim.log.levels.ERROR)
return false
end
state.platform = platform
vim.fn.mkdir('build', 'p')
vim.fn.mkdir('io', 'p')
vim.fn.mkdir("build", "p")
vim.fn.mkdir("io", "p")
return true
end
@ -55,87 +50,55 @@ end
---@param language? string
local function setup_problem(contest_id, problem_id, language)
if not state.platform then
logger.log(
'no platform set. run :CP <platform> <contest> first',
vim.log.levels.ERROR
)
logger.log("no platform set. run :CP <platform> <contest> first", vim.log.levels.ERROR)
return
end
local problem_name = state.platform == 'cses' and contest_id
or (contest_id .. (problem_id or ''))
logger.log(('setting up problem: %s'):format(problem_name))
local problem_name = state.platform == "cses" and contest_id or (contest_id .. (problem_id or ""))
logger.log(("setting up problem: %s"):format(problem_name))
local metadata_result =
scrape.scrape_contest_metadata(state.platform, contest_id)
local metadata_result = scrape.scrape_contest_metadata(state.platform, contest_id)
if not metadata_result.success then
logger.log(
'failed to load contest metadata: '
.. (metadata_result.error or 'unknown error'),
"failed to load contest metadata: " .. (metadata_result.error or "unknown error"),
vim.log.levels.WARN
)
end
vim.cmd('silent only')
vim.cmd("silent only")
state.contest_id = contest_id
state.problem_id = problem_id
local cached_test_cases =
cache.get_test_cases(state.platform, contest_id, problem_id)
local cached_test_cases = cache.get_test_cases(state.platform, contest_id, problem_id)
if cached_test_cases then
state.test_cases = cached_test_cases
end
local scrape_ctx = problem.create_context(
state.platform,
contest_id,
problem_id,
config,
language
)
local scrape_ctx = problem.create_context(state.platform, contest_id, problem_id, config, language)
local scrape_result = scrape.scrape_problem(scrape_ctx)
if not scrape_result.success then
logger.log(
'scraping failed: ' .. (scrape_result.error or 'unknown error'),
vim.log.levels.WARN
)
logger.log(
'you can manually add test cases to io/ directory',
vim.log.levels.INFO
)
logger.log("scraping failed: " .. (scrape_result.error or "unknown error"), vim.log.levels.WARN)
logger.log("you can manually add test cases to io/ directory", vim.log.levels.INFO)
state.test_cases = nil
else
local test_count = scrape_result.test_count or 0
logger.log(
('scraped %d test case(s) for %s'):format(
test_count,
scrape_result.problem_id
)
)
logger.log(("scraped %d test case(s) for %s"):format(test_count, scrape_result.problem_id))
state.test_cases = scrape_result.test_cases
if scrape_result.test_cases then
cache.set_test_cases(
state.platform,
contest_id,
problem_id,
scrape_result.test_cases
)
cache.set_test_cases(state.platform, contest_id, problem_id, scrape_result.test_cases)
end
end
vim.cmd.e(scrape_ctx.source_file)
if vim.api.nvim_buf_get_lines(0, 0, -1, true)[1] == '' then
local has_luasnip, luasnip = pcall(require, 'luasnip')
if vim.api.nvim_buf_get_lines(0, 0, -1, true)[1] == "" then
local has_luasnip, luasnip = pcall(require, "luasnip")
if has_luasnip then
local prefixed_trigger = ('cp.nvim/%s.%s'):format(
state.platform,
language
)
local prefixed_trigger = ("cp.nvim/%s.%s"):format(state.platform, language)
vim.api.nvim_buf_set_lines(0, 0, -1, false, { prefixed_trigger })
vim.api.nvim_win_set_cursor(0, { 1, #prefixed_trigger })
@ -145,23 +108,17 @@ local function setup_problem(contest_id, problem_id, language)
if luasnip.expandable() then
luasnip.expand()
else
vim.api.nvim_buf_set_lines(0, 0, 1, false, { '' })
vim.api.nvim_buf_set_lines(0, 0, 1, false, { "" })
vim.api.nvim_win_set_cursor(0, { 1, 0 })
end
vim.cmd.stopinsert()
end)
else
vim.api.nvim_input(('i%s<c-space><esc>'):format(state.platform))
vim.api.nvim_input(("i%s<c-space><esc>"):format(state.platform))
end
end
local ctx = problem.create_context(
state.platform,
state.contest_id,
state.problem_id,
config,
language
)
local ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config, language)
if config.hooks and config.hooks.setup_code then
config.hooks.setup_code(ctx)
@ -174,13 +131,13 @@ local function setup_problem(contest_id, problem_id, language)
local tile_fn = config.tile or window.default_tile
tile_fn(source_buf, input_buf, output_buf)
logger.log(('switched to problem %s'):format(ctx.problem_name))
logger.log(("switched to problem %s"):format(ctx.problem_name))
end
local function get_current_problem()
local filename = vim.fn.expand('%:t:r')
if filename == '' then
logger.log('no file open', vim.log.levels.ERROR)
local filename = vim.fn.expand("%:t:r")
if filename == "" then
logger.log("no file open", vim.log.levels.ERROR)
return nil
end
return filename
@ -192,20 +149,15 @@ local function run_problem()
return
end
logger.log(('running problem: %s'):format(problem_id))
logger.log(("running problem: %s"):format(problem_id))
if not state.platform then
logger.log('no platform set', vim.log.levels.ERROR)
logger.log("no platform set", vim.log.levels.ERROR)
return
end
local contest_config = config.contests[state.platform]
local ctx = problem.create_context(
state.platform,
state.contest_id,
state.problem_id,
config
)
local ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config)
if config.hooks and config.hooks.before_run then
config.hooks.before_run(ctx)
@ -224,17 +176,12 @@ local function debug_problem()
end
if not state.platform then
logger.log('no platform set', vim.log.levels.ERROR)
logger.log("no platform set", vim.log.levels.ERROR)
return
end
local contest_config = config.contests[state.platform]
local ctx = problem.create_context(
state.platform,
state.contest_id,
state.problem_id,
config
)
local ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config)
if config.hooks and config.hooks.before_debug then
config.hooks.before_debug(ctx)
@ -250,35 +197,28 @@ end
---@param language? string
local function navigate_problem(delta, language)
if not state.platform or not state.contest_id then
logger.log(
'no contest set. run :CP <platform> <contest> first',
vim.log.levels.ERROR
)
logger.log("no contest set. run :CP <platform> <contest> first", vim.log.levels.ERROR)
return
end
cache.load()
local contest_data =
cache.get_contest_data(state.platform, state.contest_id)
local contest_data = cache.get_contest_data(state.platform, state.contest_id)
if not contest_data or not contest_data.problems then
logger.log(
'no contest metadata found. set up a problem first to cache contest data',
vim.log.levels.ERROR
)
logger.log("no contest metadata found. set up a problem first to cache contest data", vim.log.levels.ERROR)
return
end
local problems = contest_data.problems
local current_problem_id
if state.platform == 'cses' then
if state.platform == "cses" then
current_problem_id = state.contest_id
else
current_problem_id = state.problem_id
end
if not current_problem_id then
logger.log('no current problem set', vim.log.levels.ERROR)
logger.log("no current problem set", vim.log.levels.ERROR)
return
end
@ -291,24 +231,21 @@ local function navigate_problem(delta, language)
end
if not current_index then
logger.log('current problem not found in contest', vim.log.levels.ERROR)
logger.log("current problem not found in contest", vim.log.levels.ERROR)
return
end
local new_index = current_index + delta
if new_index < 1 or new_index > #problems then
local direction = delta > 0 and 'next' or 'previous'
logger.log(
('no %s problem available'):format(direction),
vim.log.levels.INFO
)
local direction = delta > 0 and "next" or "previous"
logger.log(("no %s problem available"):format(direction), vim.log.levels.INFO)
return
end
local new_problem = problems[new_index]
if state.platform == 'cses' then
if state.platform == "cses" then
setup_problem(new_problem.id, nil, language)
else
setup_problem(state.contest_id, new_problem.id, language)
@ -318,54 +255,54 @@ end
local function parse_command(args)
if #args == 0 then
return {
type = 'error',
message = 'Usage: :CP <platform> <contest> [problem] [--lang=<language>] | :CP <action> | :CP <problem>',
type = "error",
message = "Usage: :CP <platform> <contest> [problem] [--lang=<language>] | :CP <action> | :CP <problem>",
}
end
local language = nil
for i, arg in ipairs(args) do
local lang_match = arg:match('^--lang=(.+)$')
local lang_match = arg:match("^--lang=(.+)$")
if lang_match then
language = lang_match
elseif arg == '--lang' then
elseif arg == "--lang" then
if i + 1 <= #args then
language = args[i + 1]
else
return { type = 'error', message = '--lang requires a value' }
return { type = "error", message = "--lang requires a value" }
end
end
end
local filtered_args = vim.tbl_filter(function(arg)
return not (arg:match('^--lang') or arg == language)
return not (arg:match("^--lang") or arg == language)
end, args)
local first = filtered_args[1]
if vim.tbl_contains(actions, first) then
return { type = 'action', action = first, language = language }
return { type = "action", action = first, language = language }
end
if vim.tbl_contains(platforms, first) then
if #filtered_args == 1 then
return {
type = 'platform_only',
type = "platform_only",
platform = first,
language = language,
}
elseif #filtered_args == 2 then
if first == 'cses' then
if first == "cses" then
return {
type = 'cses_problem',
type = "cses_problem",
platform = first,
problem = filtered_args[2],
language = language,
}
else
return {
type = 'contest_setup',
type = "contest_setup",
platform = first,
contest = filtered_args[2],
language = language,
@ -373,92 +310,80 @@ local function parse_command(args)
end
elseif #filtered_args == 3 then
return {
type = 'full_setup',
type = "full_setup",
platform = first,
contest = filtered_args[2],
problem = filtered_args[3],
language = language,
}
else
return { type = 'error', message = 'Too many arguments' }
return { type = "error", message = "Too many arguments" }
end
end
if state.platform and state.contest_id then
return { type = 'problem_switch', problem = first, language = language }
return { type = "problem_switch", problem = first, language = language }
end
return { type = 'error', message = 'Unknown command or no contest context' }
return { type = "error", message = "Unknown command or no contest context" }
end
function M.handle_command(opts)
local cmd = parse_command(opts.fargs)
if cmd.type == 'error' then
if cmd.type == "error" then
logger.log(cmd.message, vim.log.levels.ERROR)
return
end
if cmd.type == 'action' then
if cmd.action == 'run' then
if cmd.type == "action" then
if cmd.action == "run" then
run_problem()
elseif cmd.action == 'debug' then
elseif cmd.action == "debug" then
debug_problem()
elseif cmd.action == 'next' then
elseif cmd.action == "next" then
navigate_problem(1, cmd.language)
elseif cmd.action == 'prev' then
elseif cmd.action == "prev" then
navigate_problem(-1, cmd.language)
end
return
end
if cmd.type == 'platform_only' then
if cmd.type == "platform_only" then
set_platform(cmd.platform)
return
end
if cmd.type == 'contest_setup' then
if cmd.type == "contest_setup" then
if set_platform(cmd.platform) then
state.contest_id = cmd.contest
local metadata_result =
scrape.scrape_contest_metadata(cmd.platform, cmd.contest)
local metadata_result = scrape.scrape_contest_metadata(cmd.platform, cmd.contest)
if not metadata_result.success then
logger.log(
'failed to load contest metadata: '
.. (metadata_result.error or 'unknown error'),
"failed to load contest metadata: " .. (metadata_result.error or "unknown error"),
vim.log.levels.WARN
)
else
logger.log(
('loaded %d problems for %s %s'):format(
#metadata_result.problems,
cmd.platform,
cmd.contest
)
("loaded %d problems for %s %s"):format(#metadata_result.problems, cmd.platform, cmd.contest)
)
end
end
return
end
if cmd.type == 'full_setup' then
if cmd.type == "full_setup" then
if set_platform(cmd.platform) then
state.contest_id = cmd.contest
local metadata_result =
scrape.scrape_contest_metadata(cmd.platform, cmd.contest)
local metadata_result = scrape.scrape_contest_metadata(cmd.platform, cmd.contest)
if not metadata_result.success then
logger.log(
'failed to load contest metadata: '
.. (metadata_result.error or 'unknown error'),
"failed to load contest metadata: " .. (metadata_result.error or "unknown error"),
vim.log.levels.WARN
)
else
logger.log(
('loaded %d problems for %s %s'):format(
#metadata_result.problems,
cmd.platform,
cmd.contest
)
("loaded %d problems for %s %s"):format(#metadata_result.problems, cmd.platform, cmd.contest)
)
end
@ -467,14 +392,12 @@ function M.handle_command(opts)
return
end
if cmd.type == 'cses_problem' then
if cmd.type == "cses_problem" then
if set_platform(cmd.platform) then
local metadata_result =
scrape.scrape_contest_metadata(cmd.platform, '')
local metadata_result = scrape.scrape_contest_metadata(cmd.platform, "")
if not metadata_result.success then
logger.log(
'failed to load contest metadata: '
.. (metadata_result.error or 'unknown error'),
"failed to load contest metadata: " .. (metadata_result.error or "unknown error"),
vim.log.levels.WARN
)
end
@ -483,8 +406,8 @@ function M.handle_command(opts)
return
end
if cmd.type == 'problem_switch' then
if state.platform == 'cses' then
if cmd.type == "problem_switch" then
if state.platform == "cses" then
setup_problem(cmd.problem, nil, cmd.language)
else
setup_problem(state.contest_id, cmd.problem, cmd.language)

View file

@ -9,7 +9,7 @@ end
function M.log(msg, level)
level = level or vim.log.levels.INFO
if not config or config.debug or level >= vim.log.levels.WARN then
vim.notify(('[cp.nvim]: %s'):format(msg), level)
vim.notify(("[cp.nvim]: %s"):format(msg), level)
end
end

View file

@ -19,11 +19,11 @@ local M = {}
---@return ProblemContext
function M.create_context(contest, contest_id, problem_id, config, language)
vim.validate({
contest = { contest, 'string' },
contest_id = { contest_id, 'string' },
problem_id = { problem_id, { 'string', 'nil' }, true },
config = { config, 'table' },
language = { language, { 'string', 'nil' }, true },
contest = { contest, "string" },
contest_id = { contest_id, "string" },
problem_id = { problem_id, { "string", "nil" }, true },
config = { config, "table" },
language = { language, { "string", "nil" }, true },
})
local contest_config = config.contests[contest]
@ -34,43 +34,32 @@ function M.create_context(contest, contest_id, problem_id, config, language)
local target_language = language or contest_config.default_language
local language_config = contest_config[target_language]
if not language_config then
error(
("No language config found for '%s' in contest '%s'"):format(
target_language,
contest
)
)
error(("No language config found for '%s' in contest '%s'"):format(target_language, contest))
end
if not language_config.extension then
error(
("No extension configured for language '%s' in contest '%s'"):format(
target_language,
contest
)
)
error(("No extension configured for language '%s' in contest '%s'"):format(target_language, contest))
end
local base_name
if config.filename then
local source_file =
config.filename(contest, contest_id, problem_id, config, language)
base_name = vim.fn.fnamemodify(source_file, ':t:r')
local source_file = config.filename(contest, contest_id, problem_id, config, language)
base_name = vim.fn.fnamemodify(source_file, ":t:r")
else
local default_filename = require('cp.config').default_filename
local default_filename = require("cp.config").default_filename
base_name = default_filename(contest_id, problem_id)
end
local source_file = base_name .. '.' .. language_config.extension
local source_file = base_name .. "." .. language_config.extension
return {
contest = contest,
contest_id = contest_id,
problem_id = problem_id,
source_file = source_file,
binary_file = ('build/%s.run'):format(base_name),
input_file = ('io/%s.cpin'):format(base_name),
output_file = ('io/%s.cpout'):format(base_name),
expected_file = ('io/%s.expected'):format(base_name),
binary_file = ("build/%s.run"):format(base_name),
input_file = ("io/%s.cpin"):format(base_name),
output_file = ("io/%s.cpout"):format(base_name),
expected_file = ("io/%s.expected"):format(base_name),
problem_name = base_name,
}
end

View file

@ -1,51 +1,41 @@
local M = {}
local logger = require('cp.log')
local cache = require('cp.cache')
local logger = require("cp.log")
local cache = require("cp.cache")
local function get_plugin_path()
local plugin_path = debug.getinfo(1, 'S').source:sub(2)
return vim.fn.fnamemodify(plugin_path, ':h:h:h')
local plugin_path = debug.getinfo(1, "S").source:sub(2)
return vim.fn.fnamemodify(plugin_path, ":h:h:h")
end
local function ensure_io_directory()
vim.fn.mkdir('io', 'p')
vim.fn.mkdir("io", "p")
end
local function check_internet_connectivity()
local result = vim.system(
{ 'ping', '-c', '1', '-W', '3', '8.8.8.8' },
{ text = true }
):wait()
local result = vim.system({ "ping", "-c", "1", "-W", "3", "8.8.8.8" }, { text = true }):wait()
return result.code == 0
end
local function setup_python_env()
local plugin_path = get_plugin_path()
local venv_dir = plugin_path .. '/.venv'
local venv_dir = plugin_path .. "/.venv"
if vim.fn.executable('uv') == 0 then
if vim.fn.executable("uv") == 0 then
logger.log(
'uv is not installed. Install it to enable problem scraping: https://docs.astral.sh/uv/',
"uv is not installed. Install it to enable problem scraping: https://docs.astral.sh/uv/",
vim.log.levels.WARN
)
return false
end
if vim.fn.isdirectory(venv_dir) == 0 then
logger.log('setting up Python environment for scrapers...')
local result = vim.system(
{ 'uv', 'sync' },
{ cwd = plugin_path, text = true }
)
:wait()
logger.log("setting up Python environment for scrapers...")
local result = vim.system({ "uv", "sync" }, { cwd = plugin_path, text = true }):wait()
if result.code ~= 0 then
logger.log(
'failed to setup Python environment: ' .. result.stderr,
vim.log.levels.ERROR
)
logger.log("failed to setup Python environment: " .. result.stderr, vim.log.levels.ERROR)
return false
end
logger.log('python environment setup complete')
logger.log("python environment setup complete")
end
return true
@ -56,8 +46,8 @@ end
---@return {success: boolean, problems?: table[], error?: string}
function M.scrape_contest_metadata(platform, contest_id)
vim.validate({
platform = { platform, 'string' },
contest_id = { contest_id, 'string' },
platform = { platform, "string" },
contest_id = { contest_id, "string" },
})
cache.load()
@ -73,38 +63,38 @@ function M.scrape_contest_metadata(platform, contest_id)
if not check_internet_connectivity() then
return {
success = false,
error = 'No internet connection available',
error = "No internet connection available",
}
end
if not setup_python_env() then
return {
success = false,
error = 'Python environment setup failed',
error = "Python environment setup failed",
}
end
local plugin_path = get_plugin_path()
local scraper_path = plugin_path .. '/scrapers/' .. platform .. '.py'
local scraper_path = plugin_path .. "/scrapers/" .. platform .. ".py"
local args
if platform == 'cses' then
if platform == "cses" then
args = {
'uv',
'run',
'--directory',
"uv",
"run",
"--directory",
plugin_path,
scraper_path,
'metadata',
"metadata",
}
else
args = {
'uv',
'run',
'--directory',
"uv",
"run",
"--directory",
plugin_path,
scraper_path,
'metadata',
"metadata",
contest_id,
}
end
@ -118,8 +108,7 @@ function M.scrape_contest_metadata(platform, contest_id)
if result.code ~= 0 then
return {
success = false,
error = 'Failed to run metadata scraper: '
.. (result.stderr or 'Unknown error'),
error = "Failed to run metadata scraper: " .. (result.stderr or "Unknown error"),
}
end
@ -127,8 +116,7 @@ function M.scrape_contest_metadata(platform, contest_id)
if not ok then
return {
success = false,
error = 'Failed to parse metadata scraper output: '
.. tostring(data),
error = "Failed to parse metadata scraper output: " .. tostring(data),
}
end
@ -137,9 +125,8 @@ function M.scrape_contest_metadata(platform, contest_id)
end
local problems_list
if platform == 'cses' then
problems_list = data.categories and data.categories['CSES Problem Set']
or {}
if platform == "cses" then
problems_list = data.categories and data.categories["CSES Problem Set"] or {}
else
problems_list = data.problems or {}
end
@ -155,15 +142,12 @@ end
---@return {success: boolean, problem_id: string, test_count?: number, test_cases?: table[], url?: string, error?: string}
function M.scrape_problem(ctx)
vim.validate({
ctx = { ctx, 'table' },
ctx = { ctx, "table" },
})
ensure_io_directory()
if
vim.fn.filereadable(ctx.input_file) == 1
and vim.fn.filereadable(ctx.expected_file) == 1
then
if vim.fn.filereadable(ctx.input_file) == 1 and vim.fn.filereadable(ctx.expected_file) == 1 then
return {
success = true,
problem_id = ctx.problem_name,
@ -175,7 +159,7 @@ function M.scrape_problem(ctx)
return {
success = false,
problem_id = ctx.problem_name,
error = 'No internet connection available',
error = "No internet connection available",
}
end
@ -183,32 +167,32 @@ function M.scrape_problem(ctx)
return {
success = false,
problem_id = ctx.problem_name,
error = 'Python environment setup failed',
error = "Python environment setup failed",
}
end
local plugin_path = get_plugin_path()
local scraper_path = plugin_path .. '/scrapers/' .. ctx.contest .. '.py'
local scraper_path = plugin_path .. "/scrapers/" .. ctx.contest .. ".py"
local args
if ctx.contest == 'cses' then
if ctx.contest == "cses" then
args = {
'uv',
'run',
'--directory',
"uv",
"run",
"--directory",
plugin_path,
scraper_path,
'tests',
"tests",
ctx.contest_id,
}
else
args = {
'uv',
'run',
'--directory',
"uv",
"run",
"--directory",
plugin_path,
scraper_path,
'tests',
"tests",
ctx.contest_id,
ctx.problem_id,
}
@ -224,8 +208,7 @@ function M.scrape_problem(ctx)
return {
success = false,
problem_id = ctx.problem_name,
error = 'Failed to run tests scraper: '
.. (result.stderr or 'Unknown error'),
error = "Failed to run tests scraper: " .. (result.stderr or "Unknown error"),
}
end
@ -234,7 +217,7 @@ function M.scrape_problem(ctx)
return {
success = false,
problem_id = ctx.problem_name,
error = 'Failed to parse tests scraper output: ' .. tostring(data),
error = "Failed to parse tests scraper output: " .. tostring(data),
}
end
@ -243,14 +226,11 @@ function M.scrape_problem(ctx)
end
if data.test_cases and #data.test_cases > 0 then
local combined_input = data.test_cases[1].input:gsub('\r', '')
local combined_output = data.test_cases[1].output:gsub('\r', '')
local combined_input = data.test_cases[1].input:gsub("\r", "")
local combined_output = data.test_cases[1].output:gsub("\r", "")
vim.fn.writefile(vim.split(combined_input, '\n', true), ctx.input_file)
vim.fn.writefile(
vim.split(combined_output, '\n', true),
ctx.expected_file
)
vim.fn.writefile(vim.split(combined_input, "\n", true), ctx.input_file)
vim.fn.writefile(vim.split(combined_output, "\n", true), ctx.expected_file)
end
return {

View file

@ -1,20 +1,16 @@
local M = {}
local logger = require('cp.log')
local logger = require("cp.log")
function M.setup(config)
local ok, ls = pcall(require, 'luasnip')
local ok, ls = pcall(require, "luasnip")
if not ok then
logger.log(
'LuaSnip not available - snippets disabled',
vim.log.levels.INFO
)
logger.log("LuaSnip not available - snippets disabled", vim.log.levels.INFO)
return
end
local s, i, fmt =
ls.snippet, ls.insert_node, require('luasnip.extras.fmt').fmt
local s, i, fmt = ls.snippet, ls.insert_node, require("luasnip.extras.fmt").fmt
local constants = require('cp.constants')
local constants = require("cp.constants")
local filetype_to_language = constants.filetype_to_language
local language_to_filetype = {}
@ -114,17 +110,14 @@ if __name__ == "__main__":
local filetype = constants.canonical_filetypes[language]
for contest, template in pairs(template_set) do
local prefixed_trigger = ('cp.nvim/%s.%s'):format(contest, language)
local prefixed_trigger = ("cp.nvim/%s.%s"):format(contest, language)
if not user_overrides[prefixed_trigger] then
table.insert(
snippets,
s(prefixed_trigger, fmt(template, { i(1) }))
)
table.insert(snippets, s(prefixed_trigger, fmt(template, { i(1) })))
end
end
for trigger, snippet in pairs(user_overrides) do
local prefix_match = trigger:match('^cp%.nvim/[^.]+%.(.+)$')
local prefix_match = trigger:match("^cp%.nvim/[^.]+%.(.+)$")
if prefix_match == language then
table.insert(snippets, snippet)
end

View file

@ -1,6 +1,6 @@
local M = {}
local logger = require('cp.log')
local execute = require('cp.execute')
local logger = require("cp.log")
local execute = require("cp.execute")
local test_panel_state = {
test_cases = {},
@ -16,7 +16,7 @@ local function create_test_case(index, input, expected)
index = index,
input = input,
expected = expected,
status = 'pending',
status = "pending",
actual = nil,
time_ms = nil,
error = nil,
@ -24,10 +24,9 @@ local function create_test_case(index, input, expected)
end
local function parse_test_cases_from_cache(platform, contest_id, problem_id)
local cache = require('cp.cache')
local cache = require("cp.cache")
cache.load()
local cached_test_cases =
cache.get_test_cases(platform, contest_id, problem_id)
local cached_test_cases = cache.get_test_cases(platform, contest_id, problem_id)
if not cached_test_cases or #cached_test_cases == 0 then
return {}
@ -35,41 +34,34 @@ local function parse_test_cases_from_cache(platform, contest_id, problem_id)
local test_cases = {}
for i, test_case in ipairs(cached_test_cases) do
table.insert(
test_cases,
create_test_case(i, test_case.input, test_case.output)
)
table.insert(test_cases, create_test_case(i, test_case.input, test_case.output))
end
return test_cases
end
local function parse_test_cases_from_files(input_file, expected_file)
if
vim.fn.filereadable(input_file) == 0
or vim.fn.filereadable(expected_file) == 0
then
if vim.fn.filereadable(input_file) == 0 or vim.fn.filereadable(expected_file) == 0 then
return {}
end
local input_content = table.concat(vim.fn.readfile(input_file), '\n')
local expected_content = table.concat(vim.fn.readfile(expected_file), '\n')
local input_content = table.concat(vim.fn.readfile(input_file), "\n")
local expected_content = table.concat(vim.fn.readfile(expected_file), "\n")
return { create_test_case(1, input_content, expected_content) }
end
local function run_single_test_case(ctx, contest_config, test_case)
local language = vim.fn.fnamemodify(ctx.source_file, ':e')
local constants = require('cp.constants')
local language_name = constants.filetype_to_language[language]
or contest_config.default_language
local language = vim.fn.fnamemodify(ctx.source_file, ":e")
local constants = require("cp.constants")
local language_name = constants.filetype_to_language[language] or contest_config.default_language
local language_config = contest_config[language_name]
if not language_config then
return {
status = 'fail',
actual = '',
error = 'No language configuration',
status = "fail",
actual = "",
error = "No language configuration",
time_ms = 0,
}
end
@ -79,7 +71,7 @@ local function run_single_test_case(ctx, contest_config, test_case)
for _, arg in ipairs(cmd_template) do
local substituted = arg
for key, value in pairs(substitutions) do
substituted = substituted:gsub('{' .. key .. '}', value)
substituted = substituted:gsub("{" .. key .. "}", value)
end
table.insert(result, substituted)
end
@ -97,29 +89,25 @@ local function run_single_test_case(ctx, contest_config, test_case)
local substitutions = {
source = ctx.source_file,
binary = ctx.binary_file,
version = tostring(language_config.version or ''),
version = tostring(language_config.version or ""),
}
local run_cmd = build_command(
language_config.run,
language_config.executable,
substitutions
)
local run_cmd = build_command(language_config.run, language_config.executable, substitutions)
local start_time = vim.uv.hrtime()
local result = vim.system(run_cmd, {
stdin = test_case.input .. '\n',
stdin = test_case.input .. "\n",
timeout = contest_config.timeout_ms or 2000,
text = true,
}):wait()
local execution_time = (vim.uv.hrtime() - start_time) / 1000000
local actual_output = (result.stdout or ''):gsub('\n$', '')
local expected_output = test_case.expected:gsub('\n$', '')
local actual_output = (result.stdout or ""):gsub("\n$", "")
local expected_output = test_case.expected:gsub("\n$", "")
local matches = actual_output == expected_output
return {
status = result.code == 0 and matches and 'pass' or 'fail',
status = result.code == 0 and matches and "pass" or "fail",
actual = actual_output,
error = result.code ~= 0 and result.stderr or nil,
time_ms = execution_time,
@ -127,21 +115,16 @@ local function run_single_test_case(ctx, contest_config, test_case)
end
function M.load_test_cases(ctx, state)
local test_cases = parse_test_cases_from_cache(
state.platform,
state.contest_id,
state.problem_id
)
local test_cases = parse_test_cases_from_cache(state.platform, state.contest_id, state.problem_id)
if #test_cases == 0 then
test_cases =
parse_test_cases_from_files(ctx.input_file, ctx.expected_file)
test_cases = parse_test_cases_from_files(ctx.input_file, ctx.expected_file)
end
test_panel_state.test_cases = test_cases
test_panel_state.current_index = 1
logger.log(('loaded %d test case(s)'):format(#test_cases))
logger.log(("loaded %d test case(s)"):format(#test_cases))
return #test_cases > 0
end
@ -151,8 +134,8 @@ function M.run_test_case(ctx, contest_config, index)
return false
end
logger.log(('running test case %d'):format(index))
test_case.status = 'running'
logger.log(("running test case %d"):format(index))
test_case.status = "running"
local result = run_single_test_case(ctx, contest_config, test_case)

View file

@ -1,29 +1,25 @@
local M = {}
local function get_git_version()
local plugin_path = debug.getinfo(1, 'S').source:sub(2)
local plugin_root = vim.fn.fnamemodify(plugin_path, ':h:h:h')
local plugin_path = debug.getinfo(1, "S").source:sub(2)
local plugin_root = vim.fn.fnamemodify(plugin_path, ":h:h:h")
local result = vim.system(
{ 'git', 'describe', '--tags', '--always', '--dirty' },
{
local result = vim.system({ "git", "describe", "--tags", "--always", "--dirty" }, {
cwd = plugin_root,
text = true,
}
)
:wait()
}):wait()
if result.code == 0 then
return result.stdout:gsub('\n', '')
return result.stdout:gsub("\n", "")
else
return 'unknown'
return "unknown"
end
end
local function parse_semver(version_string)
local semver = version_string:match('^v?(%d+%.%d+%.%d+)')
local semver = version_string:match("^v?(%d+%.%d+%.%d+)")
if semver then
local major, minor, patch = semver:match('(%d+)%.(%d+)%.(%d+)')
local major, minor, patch = semver:match("(%d+)%.(%d+)%.(%d+)")
return {
full = semver,
major = tonumber(major),

View file

@ -10,14 +10,14 @@
---@field height integer
local M = {}
local constants = require('cp.constants')
local constants = require("cp.constants")
function M.clearcol()
vim.api.nvim_set_option_value('number', false, { scope = 'local' })
vim.api.nvim_set_option_value('relativenumber', false, { scope = 'local' })
vim.api.nvim_set_option_value('statuscolumn', '', { scope = 'local' })
vim.api.nvim_set_option_value('signcolumn', 'no', { scope = 'local' })
vim.api.nvim_set_option_value('foldcolumn', '0', { scope = 'local' })
vim.api.nvim_set_option_value("number", false, { scope = "local" })
vim.api.nvim_set_option_value("relativenumber", false, { scope = "local" })
vim.api.nvim_set_option_value("statuscolumn", "", { scope = "local" })
vim.api.nvim_set_option_value("signcolumn", "no", { scope = "local" })
vim.api.nvim_set_option_value("foldcolumn", "0", { scope = "local" })
end
---@return WindowState
@ -46,8 +46,8 @@ end
---@param tile_fn? fun(source_buf: integer, input_buf: integer, output_buf: integer)
function M.restore_layout(state, tile_fn)
vim.validate({
state = { state, { 'table', 'nil' }, true },
tile_fn = { tile_fn, { 'function', 'nil' }, true },
state = { state, { "table", "nil" }, true },
tile_fn = { tile_fn, { "function", "nil" }, true },
})
if not state then
@ -56,40 +56,32 @@ function M.restore_layout(state, tile_fn)
vim.cmd.diffoff()
local problem_id = vim.fn.expand('%:t:r')
if problem_id == '' then
local problem_id = vim.fn.expand("%:t:r")
if problem_id == "" then
for win, win_state in pairs(state.windows) do
if
vim.api.nvim_win_is_valid(win)
and vim.api.nvim_buf_is_valid(win_state.bufnr)
then
if vim.api.nvim_win_is_valid(win) and vim.api.nvim_buf_is_valid(win_state.bufnr) then
local bufname = vim.api.nvim_buf_get_name(win_state.bufnr)
if
not bufname:match('%.in$')
and not bufname:match('%.out$')
and not bufname:match('%.expected$')
then
problem_id = vim.fn.fnamemodify(bufname, ':t:r')
if not bufname:match("%.in$") and not bufname:match("%.out$") and not bufname:match("%.expected$") then
problem_id = vim.fn.fnamemodify(bufname, ":t:r")
break
end
end
end
end
if problem_id ~= '' then
vim.cmd('silent only')
if problem_id ~= "" then
vim.cmd("silent only")
local base_fp = vim.fn.getcwd()
local input_file = ('%s/io/%s.in'):format(base_fp, problem_id)
local output_file = ('%s/io/%s.out'):format(base_fp, problem_id)
local source_files = vim.fn.glob(problem_id .. '.*')
local input_file = ("%s/io/%s.in"):format(base_fp, problem_id)
local output_file = ("%s/io/%s.out"):format(base_fp, problem_id)
local source_files = vim.fn.glob(problem_id .. ".*")
local source_file
if source_files ~= '' then
local files = vim.split(source_files, '\n')
local valid_extensions =
vim.tbl_keys(constants.filetype_to_language)
if source_files ~= "" then
local files = vim.split(source_files, "\n")
local valid_extensions = vim.tbl_keys(constants.filetype_to_language)
for _, file in ipairs(files) do
local ext = vim.fn.fnamemodify(file, ':e')
local ext = vim.fn.fnamemodify(file, ":e")
if vim.tbl_contains(valid_extensions, ext) then
source_file = file
break
@ -135,22 +127,22 @@ end
---@param output_buf integer
local function default_tile(source_buf, input_buf, output_buf)
vim.validate({
source_buf = { source_buf, 'number' },
input_buf = { input_buf, 'number' },
output_buf = { output_buf, 'number' },
source_buf = { source_buf, "number" },
input_buf = { input_buf, "number" },
output_buf = { output_buf, "number" },
})
vim.api.nvim_set_current_buf(source_buf)
vim.cmd.vsplit()
vim.api.nvim_set_current_buf(output_buf)
vim.bo.filetype = 'cp'
vim.bo.filetype = "cp"
M.clearcol()
vim.cmd(('vertical resize %d'):format(math.floor(vim.o.columns * 0.3)))
vim.cmd(("vertical resize %d"):format(math.floor(vim.o.columns * 0.3)))
vim.cmd.split()
vim.api.nvim_set_current_buf(input_buf)
vim.bo.filetype = 'cp'
vim.bo.filetype = "cp"
M.clearcol()
vim.cmd.wincmd('h')
vim.cmd.wincmd("h")
end
M.default_tile = default_tile

View file

@ -3,56 +3,55 @@ if vim.g.loaded_cp then
end
vim.g.loaded_cp = 1
local constants = require('cp.constants')
local constants = require("cp.constants")
local platforms = constants.PLATFORMS
local actions = constants.ACTIONS
vim.api.nvim_create_user_command('CP', function(opts)
local cp = require('cp')
vim.api.nvim_create_user_command("CP", function(opts)
local cp = require("cp")
cp.handle_command(opts)
end, {
nargs = '*',
desc = 'Competitive programming helper',
nargs = "*",
desc = "Competitive programming helper",
complete = function(ArgLead, CmdLine, _)
local languages = vim.tbl_keys(constants.canonical_filetypes)
if ArgLead:match('^--lang=') then
if ArgLead:match("^--lang=") then
local lang_completions = {}
for _, lang in ipairs(languages) do
table.insert(lang_completions, '--lang=' .. lang)
table.insert(lang_completions, "--lang=" .. lang)
end
return vim.tbl_filter(function(completion)
return completion:find(ArgLead, 1, true) == 1
end, lang_completions)
end
if ArgLead:match('^%-') and not ArgLead:match('^--lang') then
if ArgLead:match("^%-") and not ArgLead:match("^--lang") then
return vim.tbl_filter(function(completion)
return completion:find(ArgLead, 1, true) == 1
end, { '--lang' })
end, { "--lang" })
end
local args = vim.split(vim.trim(CmdLine), '%s+')
local args = vim.split(vim.trim(CmdLine), "%s+")
local num_args = #args
if CmdLine:sub(-1) == ' ' then
if CmdLine:sub(-1) == " " then
num_args = num_args + 1
end
local lang_flag_present = vim.tbl_contains(args, '--lang')
local lang_flag_present = vim.tbl_contains(args, "--lang")
or vim.iter(args):any(function(arg)
return arg:match('^--lang=')
return arg:match("^--lang=")
end)
if num_args == 2 then
local candidates = { '--lang' }
local candidates = { "--lang" }
vim.list_extend(candidates, actions)
local cp = require('cp')
local cp = require("cp")
local context = cp.get_current_context()
if context.platform and context.contest_id then
local cache = require('cp.cache')
local cache = require("cp.cache")
cache.load()
local contest_data =
cache.get_contest_data(context.platform, context.contest_id)
local contest_data = cache.get_contest_data(context.platform, context.contest_id)
if contest_data and contest_data.problems then
for _, problem in ipairs(contest_data.problems) do
table.insert(candidates, problem.id)
@ -64,17 +63,17 @@ end, {
return vim.tbl_filter(function(cmd)
return cmd:find(ArgLead, 1, true) == 1
end, candidates)
elseif args[#args - 1] == '--lang' then
elseif args[#args - 1] == "--lang" then
return vim.tbl_filter(function(lang)
return lang:find(ArgLead, 1, true) == 1
end, languages)
elseif num_args == 4 and not lang_flag_present then
if vim.tbl_contains(platforms, args[2]) then
local cache = require('cp.cache')
local cache = require("cp.cache")
cache.load()
local contest_data = cache.get_contest_data(args[2], args[3])
if contest_data and contest_data.problems then
local candidates = { '--lang' }
local candidates = { "--lang" }
for _, problem in ipairs(contest_data.problems) do
table.insert(candidates, problem.id)
end

View file

@ -1,4 +0,0 @@
quote_style = "AutoPreferSingle"
indent_type = "Spaces"
column_width = 80
collapse_simple_statement = "Never"