From 689327154703e644db8a17da51a455dbb31faabe Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:06:41 -0400 Subject: [PATCH 01/25] feat(doc): documentation for :CP test --- doc/cp.txt | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/doc/cp.txt b/doc/cp.txt index ad69836..8d8fbb8 100644 --- a/doc/cp.txt +++ b/doc/cp.txt @@ -55,6 +55,10 @@ Action Commands ~ :CP debug Compile with debug flags and run current problem. Includes sanitizers and debug symbols. +:CP test Toggle test panel for individual test case + debugging. Shows per-test results with + vim-native navigation and execution controls. + Navigation Commands ~ :CP next Navigate to next problem in current contest. @@ -235,10 +239,15 @@ Example: Setting up and solving AtCoder contest ABC324 4. Code your solution, then test: > :CP run < -5. If needed, debug: > +5. If test fails, debug individual test cases: > + :CP test +< Navigate with j/k, run specific tests with + Exit test panel with q or :CP test when done + +6. If needed, compile with debug flags: > :CP debug < -6. Move to next problem: > +7. Move to next problem: > :CP next < This automatically sets up problem B @@ -250,6 +259,82 @@ Example: Quick setup for single Codeforces problem > :CP run " Test immediately < +TEST PANEL *cp-test* + +The test panel provides individual test case debugging for competitive +programming problems, particularly useful for Codeforces where multiple +test cases are combined into single input/output files. + +Activation ~ + *:CP-test* +:CP test Toggle test panel on/off. When activated, + replaces current layout with test interface. + Toggle again to restore original layout. + +Interface ~ + +The test panel displays a list of test cases with their status and details +for the currently selected test case: > + + ┌─ Test Cases ───────────────────────────────────────────────┐ + │ 1 ✓ PASS 12ms │ + │ 2 ✗ FAIL 45ms │ + │> 3 ✓ PASS 8ms <-- current selection │ + │ 4 ? PENDING │ + │ │ + │ ── Test 3 ── │ + │ Input: │ Expected: │ Actual: │ + │ 5 3 │ 8 │ 8 │ + │ │ │ │ + │ │ + │ j/k: navigate : toggle : run a: run all │ + └────────────────────────────────────────────────────────────┘ +< + +Test Status Indicators ~ + +✓ PASS Test case passed (green) +✗ FAIL Test case failed (red) +? PENDING Test case not yet executed (yellow) +⟳ RUNNING Test case currently executing (blue) + +Keymaps ~ + *cp-test-keys* +j / Navigate to next test case +k / Navigate to previous test case + Toggle selection of current test case + Run selected test cases +a Run all test cases +r Re-run failed test cases only +c Clear all test results +q / Exit test panel (restore layout) + +Test Case Sources ~ + +Test cases are loaded in priority order: +1. Individual scraped test cases (preferred for Codeforces) +2. Combined input/output files from io/ directory (fallback) + +For Codeforces problems, the plugin attempts to parse individual test +cases from the scraped contest data, enabling precise debugging of +specific test case failures. + +For AtCoder and CSES problems, which typically provide single test +cases, the combined input/output approach is used. + +Execution Details ~ + +Each test case shows: +• Input data provided to your solution +• Expected output from the problem statement +• Actual output produced by your solution +• Execution time in milliseconds +• Error messages (if execution failed) + +Test cases are executed individually using the same compilation and +execution pipeline as |:CP-run|, but with isolated input/output for +precise failure analysis. + FILE STRUCTURE *cp-files* cp.nvim creates the following file structure upon problem setup: From 5d630d9dac39558b33b965310aae461629dc55e6 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:07:00 -0400 Subject: [PATCH 02/25] refactor lang to constants --- lua/cp/constants.lua | 24 +++++++ lua/cp/init.lua | 5 +- lua/cp/snippets.lua | 4 +- lua/cp/test.lua | 163 +++++++++++++++++++++++++++++++++++++++++++ plugin/cp.lua | 8 +-- readme.md | 2 +- 6 files changed, 197 insertions(+), 9 deletions(-) create mode 100644 lua/cp/constants.lua create mode 100644 lua/cp/test.lua diff --git a/lua/cp/constants.lua b/lua/cp/constants.lua new file mode 100644 index 0000000..925982d --- /dev/null +++ b/lua/cp/constants.lua @@ -0,0 +1,24 @@ +local M = {} + +M.PLATFORMS = { "atcoder", "codeforces", "cses" } +M.ACTIONS = { "run", "debug", "test", "next", "prev" } + +M.CPP = "cpp" +M.PYTHON = "python" + +---@type table +M.filetype_to_language = { + cc = M.CPP, + cxx = M.CPP, + cpp = M.CPP, + py = M.PYTHON, + py3 = M.PYTHON, +} + +---@type table +M.canonical_filetypes = { + [M.CPP] = "cpp", + [M.PYTHON] = "python", +} + +return M \ No newline at end of file diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 6190ae9..19fcd65 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -29,8 +29,9 @@ local state = { test_states = {}, } -local platforms = { "atcoder", "codeforces", "cses" } -local actions = { "run", "debug", "next", "prev" } +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 diff --git a/lua/cp/snippets.lua b/lua/cp/snippets.lua index eaadab9..cbd3959 100644 --- a/lua/cp/snippets.lua +++ b/lua/cp/snippets.lua @@ -10,8 +10,8 @@ function M.setup(config) local s, i, fmt = ls.snippet, ls.insert_node, require("luasnip.extras.fmt").fmt - local languages = require("cp.languages") - local filetype_to_language = languages.filetype_to_language + local constants = require("cp.constants") + local filetype_to_language = constants.filetype_to_language local language_to_filetype = {} for ext, lang in pairs(filetype_to_language) do diff --git a/lua/cp/test.lua b/lua/cp/test.lua new file mode 100644 index 0000000..c6bbcbc --- /dev/null +++ b/lua/cp/test.lua @@ -0,0 +1,163 @@ +local M = {} +local logger = require("cp.log") +local execute = require("cp.execute") + +local test_panel_state = { + test_cases = {}, + current_index = 1, + buffer = nil, + namespace = nil, + is_active = false, + saved_layout = nil, +} + +local function create_test_case(index, input, expected) + return { + index = index, + input = input, + expected = expected, + status = "pending", + actual = nil, + time_ms = nil, + error = nil, + } +end + +local function parse_test_cases_from_cache(platform, contest_id, problem_id) + local cache = require("cp.cache") + cache.load() + 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 {} + end + + 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)) + 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 + return {} + end + + 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 languages = require("cp.languages") + local language_name = languages.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", + time_ms = 0, + } + end + + local function substitute_template(cmd_template, substitutions) + local result = {} + for _, arg in ipairs(cmd_template) do + local substituted = arg + for key, value in pairs(substitutions) do + substituted = substituted:gsub("{" .. key .. "}", value) + end + table.insert(result, substituted) + end + return result + end + + local function build_command(cmd_template, executable, substitutions) + local cmd = substitute_template(cmd_template, substitutions) + if executable then + table.insert(cmd, 1, executable) + end + return cmd + end + + local substitutions = { + source = ctx.source_file, + binary = ctx.binary_file, + version = tostring(language_config.version or ""), + } + + 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", + 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 matches = actual_output == expected_output + + return { + 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, + } +end + +function M.load_test_cases(ctx, state) + 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) + end + + test_panel_state.test_cases = test_cases + test_panel_state.current_index = 1 + + logger.log(("loaded %d test case(s)"):format(#test_cases)) + return #test_cases > 0 +end + +function M.run_test_case(ctx, contest_config, index) + local test_case = test_panel_state.test_cases[index] + if not test_case then + return false + end + + logger.log(("running test case %d"):format(index)) + test_case.status = "running" + + local result = run_single_test_case(ctx, contest_config, test_case) + + test_case.status = result.status + test_case.actual = result.actual + test_case.error = result.error + test_case.time_ms = result.time_ms + + return true +end + +function M.run_all_test_cases(ctx, contest_config) + local results = {} + for i, _ in ipairs(test_panel_state.test_cases) do + M.run_test_case(ctx, contest_config, i) + table.insert(results, test_panel_state.test_cases[i]) + end + return results +end + +function M.get_test_panel_state() + return test_panel_state +end + +return M \ No newline at end of file diff --git a/plugin/cp.lua b/plugin/cp.lua index ee9e817..0bab4b9 100644 --- a/plugin/cp.lua +++ b/plugin/cp.lua @@ -3,8 +3,9 @@ if vim.g.loaded_cp then end vim.g.loaded_cp = 1 -local platforms = { "atcoder", "codeforces", "cses" } -local actions = { "run", "debug", "next", "prev" } +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") @@ -13,8 +14,7 @@ end, { nargs = "*", desc = "Competitive programming helper", complete = function(ArgLead, CmdLine, _) - local languages_module = require("cp.languages") - local languages = vim.tbl_keys(languages_module.canonical_filetypes) + local languages = vim.tbl_keys(constants.canonical_filetypes) if ArgLead:match("^--lang=") then local lang_completions = {} diff --git a/readme.md b/readme.md index bbec5a4..6c17b50 100644 --- a/readme.md +++ b/readme.md @@ -69,7 +69,7 @@ follows: - finer-tuned problem limits (i.e. per-problem codeforces time, memory) - better highlighting - test case management -- USACO support - new video with functionality, notify discord members - note that codeforces support is scuffed: https://codeforces.com/blog/entry/146423 - codeforces: use round number & api not the contest id + - problems: api config From c06a0d8a84caa852badc3535e5daefa4b0cc5838 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:08:45 -0400 Subject: [PATCH 03/25] fix: update last of languages references to point to constants file --- lua/cp/execute.lua | 4 ++-- lua/cp/snippets.lua | 2 +- lua/cp/test.lua | 4 ++-- lua/cp/window.lua | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lua/cp/execute.lua b/lua/cp/execute.lua index 78358bc..1b52a71 100644 --- a/lua/cp/execute.lua +++ b/lua/cp/execute.lua @@ -8,8 +8,8 @@ local M = {} local logger = require("cp.log") -local languages = require("cp.languages") -local filetype_to_language = languages.filetype_to_language +local constants = require("cp.constants") +local filetype_to_language = constants.filetype_to_language ---@param source_file string ---@param contest_config table diff --git a/lua/cp/snippets.lua b/lua/cp/snippets.lua index cbd3959..d9805b4 100644 --- a/lua/cp/snippets.lua +++ b/lua/cp/snippets.lua @@ -107,7 +107,7 @@ if __name__ == "__main__": for language, template_set in pairs(template_definitions) do local snippets = {} - local filetype = languages.canonical_filetypes[language] + local filetype = constants.canonical_filetypes[language] for contest, template in pairs(template_set) do local prefixed_trigger = ("cp.nvim/%s.%s"):format(contest, language) diff --git a/lua/cp/test.lua b/lua/cp/test.lua index c6bbcbc..9362381 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -53,8 +53,8 @@ end local function run_single_test_case(ctx, contest_config, test_case) local language = vim.fn.fnamemodify(ctx.source_file, ":e") - local languages = require("cp.languages") - local language_name = languages.filetype_to_language[language] or contest_config.default_language + 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 diff --git a/lua/cp/window.lua b/lua/cp/window.lua index 9431a24..1f6aa42 100644 --- a/lua/cp/window.lua +++ b/lua/cp/window.lua @@ -10,7 +10,7 @@ ---@field height integer local M = {} -local languages = require("cp.languages") +local constants = require("cp.constants") function M.clearcol() vim.api.nvim_set_option_value("number", false, { scope = "local" }) @@ -79,7 +79,7 @@ function M.restore_layout(state, tile_fn) local source_file if source_files ~= "" then local files = vim.split(source_files, "\n") - local valid_extensions = vim.tbl_keys(languages.filetype_to_language) + local valid_extensions = vim.tbl_keys(constants.filetype_to_language) for _, file in ipairs(files) do local ext = vim.fn.fnamemodify(file, ":e") if vim.tbl_contains(valid_extensions, ext) then From fe4cf2b68032a259323ad62cb6bd9e63f97ad4da Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:10:11 -0400 Subject: [PATCH 04/25] feat(ci): use new stylua config --- after/ftplugin/cp.lua | 4 +- after/ftplugin/cpin.lua | 4 +- after/ftplugin/cpout.lua | 4 +- ftdetect/cp.lua | 8 +- lua/cp/cache.lua | 204 +++++------ lua/cp/config.lua | 146 ++++---- lua/cp/constants.lua | 24 +- lua/cp/execute.lua | 395 +++++++++++---------- lua/cp/health.lua | 136 ++++---- lua/cp/init.lua | 729 ++++++++++++++++++++++----------------- lua/cp/languages.lua | 21 -- lua/cp/log.lua | 10 +- lua/cp/problem.lua | 89 ++--- lua/cp/scrape.lua | 370 +++++++++++--------- lua/cp/snippets.lua | 103 +++--- lua/cp/test.lua | 245 +++++++------ lua/cp/version.lua | 48 +-- lua/cp/window.lua | 216 ++++++------ plugin/cp.lua | 149 ++++---- stylua.toml | 4 + 20 files changed, 1581 insertions(+), 1328 deletions(-) delete mode 100644 lua/cp/languages.lua create mode 100644 stylua.toml diff --git a/after/ftplugin/cp.lua b/after/ftplugin/cp.lua index 76a9f86..622ad6a 100644 --- a/after/ftplugin/cp.lua +++ b/after/ftplugin/cp.lua @@ -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 diff --git a/after/ftplugin/cpin.lua b/after/ftplugin/cpin.lua index 76a9f86..622ad6a 100644 --- a/after/ftplugin/cpin.lua +++ b/after/ftplugin/cpin.lua @@ -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 diff --git a/after/ftplugin/cpout.lua b/after/ftplugin/cpout.lua index 857a799..1f4855f 100644 --- a/after/ftplugin/cpout.lua +++ b/after/ftplugin/cpout.lua @@ -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 diff --git a/ftdetect/cp.lua b/ftdetect/cp.lua index 2b6b593..9c1b868 100644 --- a/ftdetect/cp.lua +++ b/ftdetect/cp.lua @@ -1,6 +1,6 @@ vim.filetype.add({ - extension = { - cpin = "cpin", - cpout = "cpout", - }, + extension = { + cpin = 'cpin', + cpout = 'cpout', + }, }) diff --git a/lua/cp/cache.lua b/lua/cp/cache.lua index 516ddb3..20d0dd1 100644 --- a/lua/cp/cache.lua +++ b/lua/cp/cache.lua @@ -18,129 +18,129 @@ 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" }, - }) + vim.validate({ + platform = { platform, 'string' }, + }) - if platform == "cses" then - return os.time() + (30 * 24 * 60 * 60) - end - return nil + if platform == 'cses' then + return os.time() + (30 * 24 * 60 * 60) + end + return nil end ---@param contest_data ContestData ---@param platform string ---@return boolean local function is_cache_valid(contest_data, platform) - vim.validate({ - contest_data = { contest_data, "table" }, - platform = { platform, "string" }, - }) + vim.validate({ + contest_data = { contest_data, 'table' }, + platform = { platform, 'string' }, + }) - if platform ~= "cses" then - return true - end + if platform ~= 'cses' then + return true + end - local expires_at = contest_data.expires_at - if not expires_at then - return false - end + local expires_at = contest_data.expires_at + if not expires_at then + return false + end - return os.time() < expires_at + return os.time() < expires_at end function M.load() - if vim.fn.filereadable(cache_file) == 0 then - cache_data = {} - return - end + if vim.fn.filereadable(cache_file) == 0 then + cache_data = {} + return + end - local content = vim.fn.readfile(cache_file) - if #content == 0 then - cache_data = {} - return - end + local content = vim.fn.readfile(cache_file) + if #content == 0 then + cache_data = {} + return + end - local ok, decoded = pcall(vim.json.decode, table.concat(content, "\n")) - if ok then - cache_data = decoded - else - cache_data = {} - end + local ok, decoded = pcall(vim.json.decode, table.concat(content, '\n')) + if ok then + cache_data = decoded + else + cache_data = {} + end end function M.save() - 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.mkdir(vim.fn.fnamemodify(cache_file, ':h'), 'p') + local encoded = vim.json.encode(cache_data) + vim.fn.writefile(vim.split(encoded, '\n'), cache_file) end ---@param platform string ---@param contest_id string ---@return ContestData? function M.get_contest_data(platform, contest_id) - vim.validate({ - platform = { platform, "string" }, - contest_id = { contest_id, "string" }, - }) + vim.validate({ + platform = { platform, 'string' }, + contest_id = { contest_id, 'string' }, + }) - if not cache_data[platform] then - return nil - end + if not cache_data[platform] then + return nil + end - local contest_data = cache_data[platform][contest_id] - if not contest_data then - return nil - end + local contest_data = cache_data[platform][contest_id] + if not contest_data then + return nil + end - if not is_cache_valid(contest_data, platform) then - return nil - end + if not is_cache_valid(contest_data, platform) then + return nil + end - return contest_data + return contest_data end ---@param platform string ---@param contest_id string ---@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" }, - }) + vim.validate({ + platform = { platform, 'string' }, + contest_id = { contest_id, 'string' }, + problems = { problems, 'table' }, + }) - if not cache_data[platform] then - cache_data[platform] = {} - end + if not cache_data[platform] then + cache_data[platform] = {} + end - cache_data[platform][contest_id] = { - problems = problems, - scraped_at = os.date("%Y-%m-%d"), - expires_at = get_expiry_date(platform), - } + cache_data[platform][contest_id] = { + problems = problems, + scraped_at = os.date('%Y-%m-%d'), + expires_at = get_expiry_date(platform), + } - M.save() + M.save() end ---@param platform string ---@param contest_id string function M.clear_contest_data(platform, contest_id) - vim.validate({ - platform = { platform, "string" }, - contest_id = { contest_id, "string" }, - }) + vim.validate({ + platform = { platform, 'string' }, + contest_id = { contest_id, 'string' }, + }) - if cache_data[platform] and cache_data[platform][contest_id] then - cache_data[platform][contest_id] = nil - M.save() - end + if cache_data[platform] and cache_data[platform][contest_id] then + cache_data[platform][contest_id] = nil + M.save() + end end ---@param platform string @@ -148,17 +148,18 @@ end ---@param problem_id? string ---@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 }, - }) + vim.validate({ + 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 - if not cache_data[platform] or not cache_data[platform][problem_key] then - return nil - end - return cache_data[platform][problem_key].test_cases + 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 + return cache_data[platform][problem_key].test_cases end ---@param platform string @@ -166,24 +167,25 @@ end ---@param problem_id? string ---@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" }, - }) + vim.validate({ + 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 - if not cache_data[platform] then - cache_data[platform] = {} - end - if not cache_data[platform][problem_key] then - cache_data[platform][problem_key] = {} - end + local problem_key = problem_id and (contest_id .. '_' .. problem_id) + or contest_id + if not cache_data[platform] then + cache_data[platform] = {} + end + if not cache_data[platform][problem_key] then + cache_data[platform][problem_key] = {} + end - cache_data[platform][problem_key].test_cases = test_cases - cache_data[platform][problem_key].test_cases_cached_at = os.time() - M.save() + cache_data[platform][problem_key].test_cases = test_cases + cache_data[platform][problem_key].test_cases_cached_at = os.time() + M.save() end return M diff --git a/lua/cp/config.lua b/lua/cp/config.lua index d32e26c..2e696db 100644 --- a/lua/cp/config.lua +++ b/lua/cp/config.lua @@ -48,87 +48,109 @@ ---@field filename? fun(contest: string, contest_id: string, problem_id?: string, config: cp.Config, language?: string): string local M = {} -local languages = require("cp.languages") +local constants = require('cp.constants') ---@type cp.Config M.defaults = { - contests = {}, - snippets = {}, - hooks = { - before_run = nil, - before_debug = nil, - setup_code = nil, - }, - debug = false, - tile = nil, - filename = nil, + contests = {}, + snippets = {}, + hooks = { + before_run = nil, + before_debug = nil, + setup_code = nil, + }, + debug = false, + tile = nil, + filename = nil, } ---@param user_config cp.UserConfig|nil ---@return cp.Config function M.setup(user_config) - vim.validate({ - user_config = { user_config, { "table", "nil" }, true }, - }) + vim.validate({ + 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 }, - }) + 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 }, + }) - if user_config.hooks then - vim.validate({ - before_run = { user_config.hooks.before_run, { "function", "nil" }, true }, - before_debug = { user_config.hooks.before_debug, { "function", "nil" }, true }, - setup_code = { user_config.hooks.setup_code, { "function", "nil" }, true }, - }) - end + if user_config.hooks then + vim.validate({ + before_run = { + user_config.hooks.before_run, + { 'function', 'nil' }, + true, + }, + before_debug = { + user_config.hooks.before_debug, + { 'function', 'nil' }, + true, + }, + setup_code = { + user_config.hooks.setup_code, + { 'function', 'nil' }, + true, + }, + }) + end - 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 - not vim.tbl_contains(vim.tbl_keys(languages.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(languages.filetype_to_language), ", ") - ) - ) - end - end - end - end - end - end + 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 + 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 + ), + ', ' + ) + ) + ) + end + end + end + end + end + end - local config = vim.tbl_deep_extend("force", M.defaults, user_config or {}) - return config + local config = vim.tbl_deep_extend('force', M.defaults, user_config or {}) + return config end ---@param contest_id string ---@param problem_id? string ---@return string local function default_filename(contest_id, problem_id) - vim.validate({ - contest_id = { contest_id, "string" }, - problem_id = { problem_id, { "string", "nil" }, true }, - }) + vim.validate({ + contest_id = { contest_id, 'string' }, + problem_id = { problem_id, { 'string', 'nil' }, true }, + }) - if problem_id then - return problem_id:lower() - else - return contest_id:lower() - end + if problem_id then + return problem_id:lower() + else + return contest_id:lower() + end end M.default_filename = default_filename diff --git a/lua/cp/constants.lua b/lua/cp/constants.lua index 925982d..b33bd6b 100644 --- a/lua/cp/constants.lua +++ b/lua/cp/constants.lua @@ -1,24 +1,24 @@ 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 M.filetype_to_language = { - cc = M.CPP, - cxx = M.CPP, - cpp = M.CPP, - py = M.PYTHON, - py3 = M.PYTHON, + cc = M.CPP, + cxx = M.CPP, + cpp = M.CPP, + py = M.PYTHON, + py3 = M.PYTHON, } ---@type table M.canonical_filetypes = { - [M.CPP] = "cpp", - [M.PYTHON] = "python", + [M.CPP] = 'cpp', + [M.PYTHON] = 'python', } -return M \ No newline at end of file +return M diff --git a/lua/cp/execute.lua b/lua/cp/execute.lua index 1b52a71..0ce0180 100644 --- a/lua/cp/execute.lua +++ b/lua/cp/execute.lua @@ -6,44 +6,47 @@ ---@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 ---@param contest_config table ---@return string local function get_language_from_file(source_file, contest_config) - vim.validate({ - source_file = { source_file, "string" }, - contest_config = { contest_config, "table" }, - }) + vim.validate({ + 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)) - return language + 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 ---@param cmd_template string[] ---@param substitutions table ---@return string[] local function substitute_template(cmd_template, substitutions) - vim.validate({ - cmd_template = { cmd_template, "table" }, - substitutions = { substitutions, "table" }, - }) + vim.validate({ + 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) - end - table.insert(result, substituted) - end - return result + local result = {} + for _, arg in ipairs(cmd_template) do + local substituted = arg + for key, value in pairs(substitutions) do + substituted = substituted:gsub('{' .. key .. '}', value) + end + table.insert(result, substituted) + end + return result end ---@param cmd_template string[] @@ -51,69 +54,76 @@ end ---@param substitutions table ---@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" }, - }) + vim.validate({ + cmd_template = { cmd_template, 'table' }, + executable = { executable, { 'string', 'nil' }, true }, + substitutions = { substitutions, 'table' }, + }) - local cmd = substitute_template(cmd_template, substitutions) - if executable then - table.insert(cmd, 1, executable) - end - return cmd + local cmd = substitute_template(cmd_template, substitutions) + if executable then + table.insert(cmd, 1, executable) + end + return cmd 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 ---@param substitutions table ---@return {code: integer, stderr: string} local function compile_generic(language_config, substitutions) - vim.validate({ - language_config = { language_config, "table" }, - substitutions = { substitutions, "table" }, - }) + vim.validate({ + language_config = { language_config, 'table' }, + substitutions = { substitutions, 'table' }, + }) - if not language_config.compile then - logger.log("no compilation step required") - return { code = 0, stderr = "" } - end + if not language_config.compile then + 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 + 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)) - else - logger.log(("compilation failed (%.1fms): %s"):format(compile_time, result.stderr), vim.log.levels.WARN) - end + if result.code == 0 then + logger.log(('compilation successful (%.1fms)'):format(compile_time)) + else + logger.log( + ('compilation failed (%.1fms): %s'):format( + compile_time, + result.stderr + ), + vim.log.levels.WARN + ) + end - return result + return result end ---@param cmd string[] @@ -121,42 +131,51 @@ end ---@param timeout_ms integer ---@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" }, - }) + vim.validate({ + 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() + local start_time = vim.uv.hrtime() - local result = vim.system(cmd, { - stdin = input_data, - timeout = timeout_ms, - text = true, - }):wait() + local result = vim.system(cmd, { + stdin = input_data, + timeout = timeout_ms, + text = true, + }):wait() - local end_time = vim.uv.hrtime() - local execution_time = (end_time - start_time) / 1000000 + local end_time = vim.uv.hrtime() + local execution_time = (end_time - start_time) / 1000000 - local actual_code = result.code or 0 + 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) - elseif actual_code ~= 0 then - 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)) - end + if result.code == 124 then + 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 + ) + else + logger.log(('execution successful (%.1fms)'):format(execution_time)) + end - return { - stdout = result.stdout or "", - stderr = result.stderr or "", - code = actual_code, - time_ms = execution_time, - timed_out = result.code == 124, - } + return { + stdout = result.stdout or '', + stderr = result.stderr or '', + code = actual_code, + time_ms = execution_time, + timed_out = result.code == 124, + } end ---@param exec_result ExecuteResult @@ -164,104 +183,134 @@ end ---@param is_debug boolean ---@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" }, - }) + vim.validate({ + exec_result = { exec_result, 'table' }, + expected_file = { expected_file, 'string' }, + is_debug = { is_debug, 'boolean' }, + }) - local output_lines = { exec_result.stdout } - local metadata_lines = {} + local output_lines = { exec_result.stdout } + local metadata_lines = {} - if exec_result.timed_out then - 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)) - else - table.insert(metadata_lines, ("[code]: %d"):format(exec_result.code)) - end + if exec_result.timed_out then + 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) + ) + else + 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") + 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') - while #actual_lines > 0 and actual_lines[#actual_lines] == "" do - table.remove(actual_lines) - end + while #actual_lines > 0 and actual_lines[#actual_lines] == '' do + table.remove(actual_lines) + end - local matches = #actual_lines == #expected_content - if matches then - for i, line in ipairs(actual_lines) do - if line ~= expected_content[i] then - matches = false - break - end - end - end + local matches = #actual_lines == #expected_content + if matches then + for i, line in ipairs(actual_lines) do + if line ~= expected_content[i] then + matches = false + break + end + end + end - table.insert(metadata_lines, ("[matches]: %s"):format(matches and "true" or "false")) - end + 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 ---@param contest_config table ---@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" }, - }) + vim.validate({ + ctx = { ctx, 'table' }, + contest_config = { contest_config, 'table' }, + is_debug = { is_debug, 'boolean' }, + }) - ensure_directories() + ensure_directories() - local language = get_language_from_file(ctx.source_file, contest_config) - local language_config = contest_config[language] + local language = get_language_from_file(ctx.source_file, contest_config) + local language_config = contest_config[language] - if not language_config then - vim.fn.writefile({ "Error: No configuration for language: " .. language }, ctx.output_file) - return - end + if not language_config then + vim.fn.writefile( + { 'Error: No configuration for language: ' .. language }, + ctx.output_file + ) + return + end - local substitutions = { - source = ctx.source_file, - binary = ctx.binary_file, - version = tostring(language_config.version), - } + local substitutions = { + source = ctx.source_file, + binary = ctx.binary_file, + version = tostring(language_config.version), + } - 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 - vim.fn.writefile({ compile_result.stderr }, ctx.output_file) - return - end - end + 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 + vim.fn.writefile({ compile_result.stderr }, ctx.output_file) + return + end + end - local input_data = "" - if vim.fn.filereadable(ctx.input_file) == 1 then - input_data = table.concat(vim.fn.readfile(ctx.input_file), "\n") .. "\n" - end + local input_data = '' + if vim.fn.filereadable(ctx.input_file) == 1 then + 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_call(output_buf, function() - vim.cmd.write() - end) - else - vim.fn.writefile(vim.split(formatted_output, "\n"), ctx.output_file) - end + 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_call(output_buf, function() + vim.cmd.write() + end) + else + vim.fn.writefile(vim.split(formatted_output, '\n'), ctx.output_file) + end end return M diff --git a/lua/cp/health.lua b/lua/cp/health.lua index 738e9e2..f117a2d 100644 --- a/lua/cp/health.lua +++ b/lua/cp/health.lua @@ -1,95 +1,101 @@ 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") - else - vim.health.error("cp.nvim requires Neovim 0.10.0+") - end + 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+') + 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() - if result.code == 0 then - 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") - end + local result = vim.system({ 'uv', '--version' }, { text = true }):wait() + if result.code == 0 then + 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' + ) + 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) - else - vim.health.warn("Python virtual environment not set up - run :CP command to initialize") - end + if vim.fn.isdirectory(venv_dir) == 1 then + 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' + ) + 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" } - for _, scraper in ipairs(scrapers) do - local scraper_path = plugin_path .. "/scrapers/" .. scraper - if vim.fn.filereadable(scraper_path) == 1 then - vim.health.ok("Scraper found: " .. scraper) - else - vim.health.error("Missing scraper: " .. scraper) - end - end + local scrapers = { 'atcoder.py', 'codeforces.py', 'cses.py' } + for _, scraper in ipairs(scrapers) do + local scraper_path = plugin_path .. '/scrapers/' .. scraper + if vim.fn.filereadable(scraper_path) == 1 then + vim.health.ok('Scraper found: ' .. scraper) + else + vim.health.error('Missing scraper: ' .. scraper) + end + end end local function check_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) - else - vim.health.info("LuaSnip not available - template expansion will be limited") - end + 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) + else + 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 context = cp.get_current_context() - if context.platform then - local info = context.platform - if context.contest_id then - info = info .. " " .. context.contest_id - if context.problem_id then - info = info .. " " .. context.problem_id - end - end - vim.health.info("Current context: " .. info) - else - vim.health.info("No contest context set") - end + 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 + if context.problem_id then + info = info .. ' ' .. context.problem_id + end + end + vim.health.info('Current context: ' .. info) + else + 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() - check_python_env() - check_scrapers() - check_luasnip() - check_config() + check_nvim_version() + check_uv() + check_python_env() + check_scrapers() + check_luasnip() + check_config() end return M diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 19fcd65..247e0fe 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -1,17 +1,17 @@ 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) - return {} +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 local user_config = {} @@ -20,409 +20,500 @@ logger.set_config(config) local snippets_initialized = false local state = { - platform = nil, - contest_id = nil, - problem_id = nil, - saved_layout = nil, - saved_session = nil, - test_cases = nil, - test_states = {}, + platform = nil, + contest_id = nil, + problem_id = nil, + saved_layout = nil, + saved_session = nil, + test_cases = nil, + 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) - return false - end + if not vim.tbl_contains(platforms, platform) then + 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") - return true + state.platform = platform + vim.fn.mkdir('build', 'p') + vim.fn.mkdir('io', 'p') + return true end ---@param contest_id string ---@param problem_id? string ---@param language? string local function setup_problem(contest_id, problem_id, language) - if not state.platform then - logger.log("no platform set. run :CP first", vim.log.levels.ERROR) - return - end + if not state.platform then + logger.log( + 'no platform set. run :CP 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) - if not metadata_result.success then - logger.log( - "failed to load contest metadata: " .. (metadata_result.error or "unknown error"), - vim.log.levels.WARN - ) - end + 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'), + vim.log.levels.WARN + ) + end - vim.cmd("silent only") + vim.cmd('silent only') - state.contest_id = contest_id - state.problem_id = problem_id + state.contest_id = contest_id + state.problem_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 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) + 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) - 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)) - state.test_cases = scrape_result.test_cases + 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 + ) + 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 + ) + ) + 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) - end - end + if scrape_result.test_cases then + cache.set_test_cases( + state.platform, + contest_id, + problem_id, + scrape_result.test_cases + ) + end + end - vim.cmd.e(scrape_ctx.source_file) + 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 has_luasnip then - local prefixed_trigger = ("cp.nvim/%s.%s"):format(state.platform, language) + 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 + ) - vim.api.nvim_buf_set_lines(0, 0, -1, false, { prefixed_trigger }) - vim.api.nvim_win_set_cursor(0, { 1, #prefixed_trigger }) - vim.cmd.startinsert({ bang = true }) + vim.api.nvim_buf_set_lines(0, 0, -1, false, { prefixed_trigger }) + vim.api.nvim_win_set_cursor(0, { 1, #prefixed_trigger }) + vim.cmd.startinsert({ bang = true }) - vim.schedule(function() - if luasnip.expandable() then - luasnip.expand() - else - 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"):format(state.platform)) - end - end + vim.schedule(function() + if luasnip.expandable() then + luasnip.expand() + else + 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'):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) - end + if config.hooks and config.hooks.setup_code then + config.hooks.setup_code(ctx) + end - local source_buf = vim.api.nvim_get_current_buf() - local input_buf = vim.fn.bufnr(ctx.input_file, true) - local output_buf = vim.fn.bufnr(ctx.output_file, true) + local source_buf = vim.api.nvim_get_current_buf() + local input_buf = vim.fn.bufnr(ctx.input_file, true) + local output_buf = vim.fn.bufnr(ctx.output_file, true) - local tile_fn = config.tile or window.default_tile - tile_fn(source_buf, input_buf, output_buf) + 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) - return nil - end - return filename + local filename = vim.fn.expand('%:t:r') + if filename == '' then + logger.log('no file open', vim.log.levels.ERROR) + return nil + end + return filename end local function run_problem() - local problem_id = get_current_problem() - if not problem_id then - return - end + local problem_id = get_current_problem() + if not problem_id then + 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) - return - end + if not state.platform then + 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 contest_config = config.contests[state.platform] + 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) - end + if config.hooks and config.hooks.before_run then + config.hooks.before_run(ctx) + end - vim.schedule(function() - execute.run_problem(ctx, contest_config, false) - vim.cmd.checktime() - end) + vim.schedule(function() + execute.run_problem(ctx, contest_config, false) + vim.cmd.checktime() + end) end local function debug_problem() - local problem_id = get_current_problem() - if not problem_id then - return - end + local problem_id = get_current_problem() + if not problem_id then + return + end - if not state.platform then - logger.log("no platform set", vim.log.levels.ERROR) - return - end + if not state.platform then + 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 contest_config = config.contests[state.platform] + 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) - end + if config.hooks and config.hooks.before_debug then + config.hooks.before_debug(ctx) + end - vim.schedule(function() - execute.run_problem(ctx, contest_config, true) - vim.cmd.checktime() - end) + vim.schedule(function() + execute.run_problem(ctx, contest_config, true) + vim.cmd.checktime() + end) end ---@param delta number 1 for next, -1 for prev ---@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 first", vim.log.levels.ERROR) - return - end + if not state.platform or not state.contest_id then + logger.log( + 'no contest set. run :CP first', + vim.log.levels.ERROR + ) + return + end - cache.load() - 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) - return - end + cache.load() + 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 + ) + return + end - local problems = contest_data.problems - local current_problem_id + local problems = contest_data.problems + local current_problem_id - if state.platform == "cses" then - current_problem_id = state.contest_id - else - current_problem_id = state.problem_id - end + 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) - return - end + if not current_problem_id then + logger.log('no current problem set', vim.log.levels.ERROR) + return + end - local current_index = nil - for i, prob in ipairs(problems) do - if prob.id == current_problem_id then - current_index = i - break - end - end + local current_index = nil + for i, prob in ipairs(problems) do + if prob.id == current_problem_id then + current_index = i + break + end + end - if not current_index then - logger.log("current problem not found in contest", vim.log.levels.ERROR) - return - end + if not current_index then + logger.log('current problem not found in contest', vim.log.levels.ERROR) + return + end - local new_index = current_index + delta + 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) - return - end + 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 + ) + return + end - local new_problem = problems[new_index] + local new_problem = problems[new_index] - if state.platform == "cses" then - setup_problem(new_problem.id, nil, language) - else - setup_problem(state.contest_id, new_problem.id, language) - end + if state.platform == 'cses' then + setup_problem(new_problem.id, nil, language) + else + setup_problem(state.contest_id, new_problem.id, language) + end end local function parse_command(args) - if #args == 0 then - return { - type = "error", - message = "Usage: :CP [problem] [--lang=] | :CP | :CP ", - } - end + if #args == 0 then + return { + type = 'error', + message = 'Usage: :CP [problem] [--lang=] | :CP | :CP ', + } + end - local language = nil + local language = nil - for i, arg in ipairs(args) do - local lang_match = arg:match("^--lang=(.+)$") - if lang_match then - language = lang_match - elseif arg == "--lang" then - if i + 1 <= #args then - language = args[i + 1] - else - return { type = "error", message = "--lang requires a value" } - end - end - end + for i, arg in ipairs(args) do + local lang_match = arg:match('^--lang=(.+)$') + if lang_match then + language = lang_match + elseif arg == '--lang' then + if i + 1 <= #args then + language = args[i + 1] + else + 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) - end, args) + local filtered_args = vim.tbl_filter(function(arg) + return not (arg:match('^--lang') or arg == language) + end, args) - local first = filtered_args[1] + local first = filtered_args[1] - if vim.tbl_contains(actions, first) then - return { type = "action", action = first, language = language } - end + if vim.tbl_contains(actions, first) then + return { type = 'action', action = first, language = language } + end - if vim.tbl_contains(platforms, first) then - if #filtered_args == 1 then - return { type = "platform_only", platform = first, language = language } - elseif #filtered_args == 2 then - if first == "cses" then - return { type = "cses_problem", platform = first, problem = filtered_args[2], language = language } - else - return { type = "contest_setup", platform = first, contest = filtered_args[2], language = language } - end - elseif #filtered_args == 3 then - return { - type = "full_setup", - platform = first, - contest = filtered_args[2], - problem = filtered_args[3], - language = language, - } - else - return { type = "error", message = "Too many arguments" } - end - end + if vim.tbl_contains(platforms, first) then + if #filtered_args == 1 then + return { + type = 'platform_only', + platform = first, + language = language, + } + elseif #filtered_args == 2 then + if first == 'cses' then + return { + type = 'cses_problem', + platform = first, + problem = filtered_args[2], + language = language, + } + else + return { + type = 'contest_setup', + platform = first, + contest = filtered_args[2], + language = language, + } + end + elseif #filtered_args == 3 then + return { + type = 'full_setup', + platform = first, + contest = filtered_args[2], + problem = filtered_args[3], + language = language, + } + else + 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 } - end + if state.platform and state.contest_id then + 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) + local cmd = parse_command(opts.fargs) - if cmd.type == "error" then - logger.log(cmd.message, vim.log.levels.ERROR) - return - end + 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 - run_problem() - elseif cmd.action == "debug" then - debug_problem() - elseif cmd.action == "next" then - navigate_problem(1, cmd.language) - elseif cmd.action == "prev" then - navigate_problem(-1, cmd.language) - end - return - end + if cmd.type == 'action' then + if cmd.action == 'run' then + run_problem() + elseif cmd.action == 'debug' then + debug_problem() + elseif cmd.action == 'next' then + navigate_problem(1, cmd.language) + elseif cmd.action == 'prev' then + navigate_problem(-1, cmd.language) + end + return + end - if cmd.type == "platform_only" then - set_platform(cmd.platform) - return - end + if cmd.type == 'platform_only' then + set_platform(cmd.platform) + return + end - 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) - if not metadata_result.success then - logger.log( - "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) - ) - end - end - return - end + 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) + if not metadata_result.success then + logger.log( + '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 + ) + ) + end + end + return + end - 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) - if not metadata_result.success then - logger.log( - "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) - ) - end + 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) + if not metadata_result.success then + logger.log( + '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 + ) + ) + end - setup_problem(cmd.contest, cmd.problem, cmd.language) - end - return - end + setup_problem(cmd.contest, cmd.problem, cmd.language) + end + return + end - if cmd.type == "cses_problem" then - if set_platform(cmd.platform) then - 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"), - vim.log.levels.WARN - ) - end - setup_problem(cmd.problem, nil, cmd.language) - end - return - end + if cmd.type == 'cses_problem' then + if set_platform(cmd.platform) then + 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'), + vim.log.levels.WARN + ) + end + setup_problem(cmd.problem, nil, cmd.language) + end + return + end - 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) - end - return - end + 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) + end + return + end end function M.setup(opts) - opts = opts or {} - user_config = opts - config = config_module.setup(user_config) - logger.set_config(config) - if not snippets_initialized then - snippets.setup(config) - snippets_initialized = true - end + opts = opts or {} + user_config = opts + config = config_module.setup(user_config) + logger.set_config(config) + if not snippets_initialized then + snippets.setup(config) + snippets_initialized = true + end end function M.get_current_context() - return { - platform = state.platform, - contest_id = state.contest_id, - problem_id = state.problem_id, - } + return { + platform = state.platform, + contest_id = state.contest_id, + problem_id = state.problem_id, + } end function M.is_initialized() - return true + return true end return M diff --git a/lua/cp/languages.lua b/lua/cp/languages.lua deleted file mode 100644 index 134d312..0000000 --- a/lua/cp/languages.lua +++ /dev/null @@ -1,21 +0,0 @@ -local M = {} - -M.CPP = "cpp" -M.PYTHON = "python" - ----@type table -M.filetype_to_language = { - cc = M.CPP, - cxx = M.CPP, - cpp = M.CPP, - py = M.PYTHON, - py3 = M.PYTHON, -} - ----@type table -M.canonical_filetypes = { - [M.CPP] = "cpp", - [M.PYTHON] = "python", -} - -return M diff --git a/lua/cp/log.lua b/lua/cp/log.lua index 2dc033e..e6fea22 100644 --- a/lua/cp/log.lua +++ b/lua/cp/log.lua @@ -3,14 +3,14 @@ local M = {} local config = nil function M.set_config(user_config) - config = user_config + config = user_config 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) - end + 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) + end end return M diff --git a/lua/cp/problem.lua b/lua/cp/problem.lua index 088b908..8acd59e 100644 --- a/lua/cp/problem.lua +++ b/lua/cp/problem.lua @@ -18,50 +18,61 @@ local M = {} ---@param language? string ---@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 }, - }) + 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 }, + }) - local contest_config = config.contests[contest] - if not contest_config then - error(("No contest config found for '%s'"):format(contest)) - end + local contest_config = config.contests[contest] + if not contest_config then + error(("No contest config found for '%s'"):format(contest)) + end - 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)) - end - if not language_config.extension then - error(("No extension configured for language '%s' in contest '%s'"):format(target_language, contest)) - end + 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 + ) + ) + end + if not language_config.extension then + 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") - else - local default_filename = require("cp.config").default_filename - base_name = default_filename(contest_id, problem_id) - 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') + else + 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), - problem_name = base_name, - } + 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), + problem_name = base_name, + } end return M diff --git a/lua/cp/scrape.lua b/lua/cp/scrape.lua index bf40059..2c784ce 100644 --- a/lua/cp/scrape.lua +++ b/lua/cp/scrape.lua @@ -1,213 +1,265 @@ 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() - return result.code == 0 + 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 plugin_path = get_plugin_path() + local venv_dir = plugin_path .. '/.venv' - if vim.fn.executable("uv") == 0 then - logger.log( - "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.executable('uv') == 0 then + logger.log( + '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() - if result.code ~= 0 then - logger.log("failed to setup Python environment: " .. result.stderr, vim.log.levels.ERROR) - return false - end - logger.log("python environment setup complete") - 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() + if result.code ~= 0 then + logger.log( + 'failed to setup Python environment: ' .. result.stderr, + vim.log.levels.ERROR + ) + return false + end + logger.log('python environment setup complete') + end - return true + return true end ---@param platform string ---@param contest_id string ---@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" }, - }) + vim.validate({ + platform = { platform, 'string' }, + contest_id = { contest_id, 'string' }, + }) - cache.load() + cache.load() - local cached_data = cache.get_contest_data(platform, contest_id) - if cached_data then - return { - success = true, - problems = cached_data.problems, - } - end + local cached_data = cache.get_contest_data(platform, contest_id) + if cached_data then + return { + success = true, + problems = cached_data.problems, + } + end - if not check_internet_connectivity() then - return { - success = false, - error = "No internet connection available", - } - end + if not check_internet_connectivity() then + return { + success = false, + error = 'No internet connection available', + } + end - if not setup_python_env() then - return { - success = false, - error = "Python environment setup failed", - } - end + if not setup_python_env() then + return { + success = false, + error = 'Python environment setup failed', + } + end - local plugin_path = get_plugin_path() - local scraper_path = plugin_path .. "/scrapers/" .. platform .. ".py" + local plugin_path = get_plugin_path() + local scraper_path = plugin_path .. '/scrapers/' .. platform .. '.py' - local args - if platform == "cses" then - args = { "uv", "run", "--directory", plugin_path, scraper_path, "metadata" } - else - args = { "uv", "run", "--directory", plugin_path, scraper_path, "metadata", contest_id } - end + local args + if platform == 'cses' then + args = { + 'uv', + 'run', + '--directory', + plugin_path, + scraper_path, + 'metadata', + } + else + args = { + 'uv', + 'run', + '--directory', + plugin_path, + scraper_path, + 'metadata', + contest_id, + } + end - local result = vim.system(args, { - cwd = plugin_path, - text = true, - timeout = 30000, - }):wait() + local result = vim.system(args, { + cwd = plugin_path, + text = true, + timeout = 30000, + }):wait() - if result.code ~= 0 then - return { - success = false, - error = "Failed to run metadata scraper: " .. (result.stderr or "Unknown error"), - } - end + if result.code ~= 0 then + return { + success = false, + error = 'Failed to run metadata scraper: ' + .. (result.stderr or 'Unknown error'), + } + end - local ok, data = pcall(vim.json.decode, result.stdout) - if not ok then - return { - success = false, - error = "Failed to parse metadata scraper output: " .. tostring(data), - } - end + local ok, data = pcall(vim.json.decode, result.stdout) + if not ok then + return { + success = false, + error = 'Failed to parse metadata scraper output: ' + .. tostring(data), + } + end - if not data.success then - return data - end + if not data.success then + return data + end - local problems_list - if platform == "cses" then - problems_list = data.categories and data.categories["CSES Problem Set"] or {} - else - problems_list = data.problems or {} - end + local problems_list + if platform == 'cses' then + problems_list = data.categories and data.categories['CSES Problem Set'] + or {} + else + problems_list = data.problems or {} + end - cache.set_contest_data(platform, contest_id, problems_list) - return { - success = true, - problems = problems_list, - } + cache.set_contest_data(platform, contest_id, problems_list) + return { + success = true, + problems = problems_list, + } end ---@param ctx ProblemContext ---@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" }, - }) + vim.validate({ + ctx = { ctx, 'table' }, + }) - ensure_io_directory() + ensure_io_directory() - 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, - test_count = 1, - } - end + 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, + test_count = 1, + } + end - if not check_internet_connectivity() then - return { - success = false, - problem_id = ctx.problem_name, - error = "No internet connection available", - } - end + if not check_internet_connectivity() then + return { + success = false, + problem_id = ctx.problem_name, + error = 'No internet connection available', + } + end - if not setup_python_env() then - return { - success = false, - problem_id = ctx.problem_name, - error = "Python environment setup failed", - } - end + if not setup_python_env() then + return { + success = false, + problem_id = ctx.problem_name, + error = 'Python environment setup failed', + } + end - local plugin_path = get_plugin_path() - local scraper_path = plugin_path .. "/scrapers/" .. ctx.contest .. ".py" + local plugin_path = get_plugin_path() + local scraper_path = plugin_path .. '/scrapers/' .. ctx.contest .. '.py' - local args - if ctx.contest == "cses" then - args = { "uv", "run", "--directory", plugin_path, scraper_path, "tests", ctx.contest_id } - else - args = { "uv", "run", "--directory", plugin_path, scraper_path, "tests", ctx.contest_id, ctx.problem_id } - end + local args + if ctx.contest == 'cses' then + args = { + 'uv', + 'run', + '--directory', + plugin_path, + scraper_path, + 'tests', + ctx.contest_id, + } + else + args = { + 'uv', + 'run', + '--directory', + plugin_path, + scraper_path, + 'tests', + ctx.contest_id, + ctx.problem_id, + } + end - local result = vim.system(args, { - cwd = plugin_path, - text = true, - timeout = 30000, - }):wait() + local result = vim.system(args, { + cwd = plugin_path, + text = true, + timeout = 30000, + }):wait() - if result.code ~= 0 then - return { - success = false, - problem_id = ctx.problem_name, - error = "Failed to run tests scraper: " .. (result.stderr or "Unknown error"), - } - end + if result.code ~= 0 then + return { + success = false, + problem_id = ctx.problem_name, + error = 'Failed to run tests scraper: ' + .. (result.stderr or 'Unknown error'), + } + end - local ok, data = pcall(vim.json.decode, result.stdout) - if not ok then - return { - success = false, - problem_id = ctx.problem_name, - error = "Failed to parse tests scraper output: " .. tostring(data), - } - end + local ok, data = pcall(vim.json.decode, result.stdout) + if not ok then + return { + success = false, + problem_id = ctx.problem_name, + error = 'Failed to parse tests scraper output: ' .. tostring(data), + } + end - if not data.success then - return data - end + if not data.success then + return data + 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", "") + 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', '') - 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 + 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 { - success = true, - problem_id = ctx.problem_name, - test_count = data.test_cases and #data.test_cases or 0, - test_cases = data.test_cases, - url = data.url, - } + return { + success = true, + problem_id = ctx.problem_name, + test_count = data.test_cases and #data.test_cases or 0, + test_cases = data.test_cases, + url = data.url, + } end return M diff --git a/lua/cp/snippets.lua b/lua/cp/snippets.lua index d9805b4..4eb90e2 100644 --- a/lua/cp/snippets.lua +++ b/lua/cp/snippets.lua @@ -1,28 +1,32 @@ local M = {} -local logger = require("cp.log") +local logger = require('cp.log') function M.setup(config) - local ok, ls = pcall(require, "luasnip") - if not ok then - logger.log("LuaSnip not available - snippets disabled", vim.log.levels.INFO) - return - end + local ok, ls = pcall(require, 'luasnip') + if not ok then + 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 filetype_to_language = constants.filetype_to_language + local constants = require('cp.constants') + local filetype_to_language = constants.filetype_to_language - local language_to_filetype = {} - for ext, lang in pairs(filetype_to_language) do - if not language_to_filetype[lang] then - language_to_filetype[lang] = ext - end - end + local language_to_filetype = {} + for ext, lang in pairs(filetype_to_language) do + if not language_to_filetype[lang] then + language_to_filetype[lang] = ext + end + end - local template_definitions = { - cpp = { - codeforces = [[#include + local template_definitions = { + cpp = { + codeforces = [[#include using namespace std; @@ -43,7 +47,7 @@ int main() {{ return 0; }}]], - atcoder = [[#include + atcoder = [[#include using namespace std; @@ -68,7 +72,7 @@ int main() {{ return 0; }}]], - cses = [[#include + cses = [[#include using namespace std; @@ -79,10 +83,10 @@ int main() {{ return 0; }}]], - }, + }, - python = { - codeforces = [[def solve(): + python = { + codeforces = [[def solve(): {} if __name__ == "__main__": @@ -90,41 +94,44 @@ if __name__ == "__main__": for _ in range(tc): solve()]], - atcoder = [[def solve(): + atcoder = [[def solve(): {} if __name__ == "__main__": solve()]], - cses = [[{}]], - }, - } + cses = [[{}]], + }, + } - local user_overrides = {} - for _, snippet in ipairs(config.snippets or {}) do - user_overrides[snippet.trigger] = snippet - end + local user_overrides = {} + for _, snippet in ipairs(config.snippets or {}) do + user_overrides[snippet.trigger] = snippet + end - for language, template_set in pairs(template_definitions) do - local snippets = {} - local filetype = constants.canonical_filetypes[language] + for language, template_set in pairs(template_definitions) do + local snippets = {} + local filetype = constants.canonical_filetypes[language] - for contest, template in pairs(template_set) do - 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) }))) - end - end + for contest, template in pairs(template_set) do + 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) })) + ) + end + end - for trigger, snippet in pairs(user_overrides) do - local prefix_match = trigger:match("^cp%.nvim/[^.]+%.(.+)$") - if prefix_match == language then - table.insert(snippets, snippet) - end - end + for trigger, snippet in pairs(user_overrides) do + local prefix_match = trigger:match('^cp%.nvim/[^.]+%.(.+)$') + if prefix_match == language then + table.insert(snippets, snippet) + end + end - ls.add_snippets(filetype, snippets) - end + ls.add_snippets(filetype, snippets) + end end return M diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 9362381..da14e49 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -1,163 +1,180 @@ 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 = {}, - current_index = 1, - buffer = nil, - namespace = nil, - is_active = false, - saved_layout = nil, + test_cases = {}, + current_index = 1, + buffer = nil, + namespace = nil, + is_active = false, + saved_layout = nil, } local function create_test_case(index, input, expected) - return { - index = index, - input = input, - expected = expected, - status = "pending", - actual = nil, - time_ms = nil, - error = nil, - } + return { + index = index, + input = input, + expected = expected, + status = 'pending', + actual = nil, + time_ms = nil, + error = nil, + } end local function parse_test_cases_from_cache(platform, contest_id, problem_id) - local cache = require("cp.cache") - cache.load() - local cached_test_cases = cache.get_test_cases(platform, contest_id, problem_id) + local cache = require('cp.cache') + cache.load() + 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 {} - end + if not cached_test_cases or #cached_test_cases == 0 then + return {} + end - 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)) - end + 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) + ) + end - return test_cases + 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 - return {} - end + 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) } + 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_config = contest_config[language_name] + 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", - time_ms = 0, - } - end + if not language_config then + return { + status = 'fail', + actual = '', + error = 'No language configuration', + time_ms = 0, + } + end - local function substitute_template(cmd_template, substitutions) - local result = {} - for _, arg in ipairs(cmd_template) do - local substituted = arg - for key, value in pairs(substitutions) do - substituted = substituted:gsub("{" .. key .. "}", value) - end - table.insert(result, substituted) - end - return result - end + local function substitute_template(cmd_template, substitutions) + local result = {} + for _, arg in ipairs(cmd_template) do + local substituted = arg + for key, value in pairs(substitutions) do + substituted = substituted:gsub('{' .. key .. '}', value) + end + table.insert(result, substituted) + end + return result + end - local function build_command(cmd_template, executable, substitutions) - local cmd = substitute_template(cmd_template, substitutions) - if executable then - table.insert(cmd, 1, executable) - end - return cmd - end + local function build_command(cmd_template, executable, substitutions) + local cmd = substitute_template(cmd_template, substitutions) + if executable then + table.insert(cmd, 1, executable) + end + return cmd + end - local substitutions = { - source = ctx.source_file, - binary = ctx.binary_file, - version = tostring(language_config.version or ""), - } + local substitutions = { + source = ctx.source_file, + binary = ctx.binary_file, + 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", - timeout = contest_config.timeout_ms or 2000, - text = true, - }):wait() - local execution_time = (vim.uv.hrtime() - start_time) / 1000000 + local start_time = vim.uv.hrtime() + local result = vim.system(run_cmd, { + 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 matches = actual_output == expected_output + 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", - actual = actual_output, - error = result.code ~= 0 and result.stderr or nil, - time_ms = execution_time, - } + return { + 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, + } 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) - end + if #test_cases == 0 then + 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 + test_panel_state.test_cases = test_cases + test_panel_state.current_index = 1 - logger.log(("loaded %d test case(s)"):format(#test_cases)) - return #test_cases > 0 + logger.log(('loaded %d test case(s)'):format(#test_cases)) + return #test_cases > 0 end function M.run_test_case(ctx, contest_config, index) - local test_case = test_panel_state.test_cases[index] - if not test_case then - return false - end + local test_case = test_panel_state.test_cases[index] + if not test_case then + 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) + local result = run_single_test_case(ctx, contest_config, test_case) - test_case.status = result.status - test_case.actual = result.actual - test_case.error = result.error - test_case.time_ms = result.time_ms + test_case.status = result.status + test_case.actual = result.actual + test_case.error = result.error + test_case.time_ms = result.time_ms - return true + return true end function M.run_all_test_cases(ctx, contest_config) - local results = {} - for i, _ in ipairs(test_panel_state.test_cases) do - M.run_test_case(ctx, contest_config, i) - table.insert(results, test_panel_state.test_cases[i]) - end - return results + local results = {} + for i, _ in ipairs(test_panel_state.test_cases) do + M.run_test_case(ctx, contest_config, i) + table.insert(results, test_panel_state.test_cases[i]) + end + return results end function M.get_test_panel_state() - return test_panel_state + return test_panel_state end -return M \ No newline at end of file +return M diff --git a/lua/cp/version.lua b/lua/cp/version.lua index 0cd247d..fc4289c 100644 --- a/lua/cp/version.lua +++ b/lua/cp/version.lua @@ -1,33 +1,37 @@ 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" }, { - cwd = plugin_root, - text = true, - }):wait() + local result = vim.system( + { 'git', 'describe', '--tags', '--always', '--dirty' }, + { + cwd = plugin_root, + text = true, + } + ) + :wait() - if result.code == 0 then - return result.stdout:gsub("\n", "") - else - return "unknown" - end + if result.code == 0 then + return result.stdout:gsub('\n', '') + else + return 'unknown' + end end local function parse_semver(version_string) - local semver = version_string:match("^v?(%d+%.%d+%.%d+)") - if semver then - local major, minor, patch = semver:match("(%d+)%.(%d+)%.(%d+)") - return { - full = semver, - major = tonumber(major), - minor = tonumber(minor), - patch = tonumber(patch), - } - end - return nil + local semver = version_string:match('^v?(%d+%.%d+%.%d+)') + if semver then + local major, minor, patch = semver:match('(%d+)%.(%d+)%.(%d+)') + return { + full = semver, + major = tonumber(major), + minor = tonumber(minor), + patch = tonumber(patch), + } + end + return nil end M.version = get_git_version() diff --git a/lua/cp/window.lua b/lua/cp/window.lua index 1f6aa42..e5efde2 100644 --- a/lua/cp/window.lua +++ b/lua/cp/window.lua @@ -10,139 +10,147 @@ ---@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 function M.save_layout() - local windows = {} - for _, win in ipairs(vim.api.nvim_list_wins()) do - if vim.api.nvim_win_is_valid(win) then - local bufnr = vim.api.nvim_win_get_buf(win) - windows[win] = { - bufnr = bufnr, - view = vim.fn.winsaveview(), - width = vim.api.nvim_win_get_width(win), - height = vim.api.nvim_win_get_height(win), - } - end - end + local windows = {} + for _, win in ipairs(vim.api.nvim_list_wins()) do + if vim.api.nvim_win_is_valid(win) then + local bufnr = vim.api.nvim_win_get_buf(win) + windows[win] = { + bufnr = bufnr, + view = vim.fn.winsaveview(), + width = vim.api.nvim_win_get_width(win), + height = vim.api.nvim_win_get_height(win), + } + end + end - return { - windows = windows, - current_win = vim.api.nvim_get_current_win(), - layout = vim.fn.winrestcmd(), - } + return { + windows = windows, + current_win = vim.api.nvim_get_current_win(), + layout = vim.fn.winrestcmd(), + } end ---@param state? WindowState ---@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 }, - }) + vim.validate({ + state = { state, { 'table', 'nil' }, true }, + tile_fn = { tile_fn, { 'function', 'nil' }, true }, + }) - if not state then - return - end + if not state then + return + end - vim.cmd.diffoff() + vim.cmd.diffoff() - 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 - 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") - break - end - end - end - end + 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 + 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') + 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 source_file - 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") - if vim.tbl_contains(valid_extensions, ext) then - source_file = file - break - end - end - source_file = source_file or files[1] - end + 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 source_file + 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') + if vim.tbl_contains(valid_extensions, ext) then + source_file = file + break + end + end + source_file = source_file or files[1] + end - if not source_file or vim.fn.filereadable(source_file) == 0 then - return - end + if not source_file or vim.fn.filereadable(source_file) == 0 then + return + end - vim.cmd.edit(source_file) - local source_buf = vim.api.nvim_get_current_buf() - local input_buf = vim.fn.bufnr(input_file, true) - local output_buf = vim.fn.bufnr(output_file, true) + vim.cmd.edit(source_file) + local source_buf = vim.api.nvim_get_current_buf() + local input_buf = vim.fn.bufnr(input_file, true) + local output_buf = vim.fn.bufnr(output_file, true) - if tile_fn then - tile_fn(source_buf, input_buf, output_buf) - else - M.default_tile(source_buf, input_buf, output_buf) - end - else - vim.cmd(state.layout) + if tile_fn then + tile_fn(source_buf, input_buf, output_buf) + else + M.default_tile(source_buf, input_buf, output_buf) + end + else + vim.cmd(state.layout) - for win, win_state in pairs(state.windows) do - if vim.api.nvim_win_is_valid(win) then - vim.api.nvim_set_current_win(win) - if vim.api.nvim_get_current_buf() == win_state.bufnr then - vim.fn.winrestview(win_state.view) - end - end - end + for win, win_state in pairs(state.windows) do + if vim.api.nvim_win_is_valid(win) then + vim.api.nvim_set_current_win(win) + if vim.api.nvim_get_current_buf() == win_state.bufnr then + vim.fn.winrestview(win_state.view) + end + end + end - if vim.api.nvim_win_is_valid(state.current_win) then - vim.api.nvim_set_current_win(state.current_win) - end - end + if vim.api.nvim_win_is_valid(state.current_win) then + vim.api.nvim_set_current_win(state.current_win) + end + end end ---@param source_buf integer ---@param input_buf integer ---@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" }, - }) + vim.validate({ + 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" - M.clearcol() - 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" - M.clearcol() - vim.cmd.wincmd("h") + vim.api.nvim_set_current_buf(source_buf) + vim.cmd.vsplit() + vim.api.nvim_set_current_buf(output_buf) + vim.bo.filetype = 'cp' + M.clearcol() + 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' + M.clearcol() + vim.cmd.wincmd('h') end M.default_tile = default_tile diff --git a/plugin/cp.lua b/plugin/cp.lua index 0bab4b9..6bb0987 100644 --- a/plugin/cp.lua +++ b/plugin/cp.lua @@ -1,88 +1,89 @@ if vim.g.loaded_cp then - return + return 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") - cp.handle_command(opts) +vim.api.nvim_create_user_command('CP', function(opts) + local cp = require('cp') + cp.handle_command(opts) end, { - nargs = "*", - desc = "Competitive programming helper", - complete = function(ArgLead, CmdLine, _) - local languages = vim.tbl_keys(constants.canonical_filetypes) + nargs = '*', + desc = 'Competitive programming helper', + complete = function(ArgLead, CmdLine, _) + local languages = vim.tbl_keys(constants.canonical_filetypes) - if ArgLead:match("^--lang=") then - local lang_completions = {} - for _, lang in ipairs(languages) do - 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('^--lang=') then + local lang_completions = {} + for _, lang in ipairs(languages) do + 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 - return vim.tbl_filter(function(completion) - return completion:find(ArgLead, 1, true) == 1 - end, { "--lang" }) - end + 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 - local args = vim.split(vim.trim(CmdLine), "%s+") - local num_args = #args - if CmdLine:sub(-1) == " " then - num_args = num_args + 1 - end + local args = vim.split(vim.trim(CmdLine), '%s+') + local num_args = #args + if CmdLine:sub(-1) == ' ' then + num_args = num_args + 1 + end - local lang_flag_present = vim.tbl_contains(args, "--lang") - or vim.iter(args):any(function(arg) - return arg:match("^--lang=") - end) + local lang_flag_present = vim.tbl_contains(args, '--lang') + or vim.iter(args):any(function(arg) + return arg:match('^--lang=') + end) - if num_args == 2 then - local candidates = { "--lang" } - vim.list_extend(candidates, actions) - local cp = require("cp") - local context = cp.get_current_context() - if context.platform and context.contest_id then - local cache = require("cp.cache") - cache.load() - 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) - end - end - else - vim.list_extend(candidates, platforms) - end - return vim.tbl_filter(function(cmd) - return cmd:find(ArgLead, 1, true) == 1 - end, candidates) - 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") - cache.load() - local contest_data = cache.get_contest_data(args[2], args[3]) - if contest_data and contest_data.problems then - local candidates = { "--lang" } - for _, problem in ipairs(contest_data.problems) do - table.insert(candidates, problem.id) - end - return vim.tbl_filter(function(cmd) - return cmd:find(ArgLead, 1, true) == 1 - end, candidates) - end - end - end - return {} - end, + if num_args == 2 then + local candidates = { '--lang' } + vim.list_extend(candidates, actions) + local cp = require('cp') + local context = cp.get_current_context() + if context.platform and context.contest_id then + local cache = require('cp.cache') + cache.load() + 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) + end + end + else + vim.list_extend(candidates, platforms) + end + return vim.tbl_filter(function(cmd) + return cmd:find(ArgLead, 1, true) == 1 + end, candidates) + 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') + cache.load() + local contest_data = cache.get_contest_data(args[2], args[3]) + if contest_data and contest_data.problems then + local candidates = { '--lang' } + for _, problem in ipairs(contest_data.problems) do + table.insert(candidates, problem.id) + end + return vim.tbl_filter(function(cmd) + return cmd:find(ArgLead, 1, true) == 1 + end, candidates) + end + end + end + return {} + end, }) diff --git a/stylua.toml b/stylua.toml new file mode 100644 index 0000000..dda733b --- /dev/null +++ b/stylua.toml @@ -0,0 +1,4 @@ +quote_style = "AutoPreferSingle" +indent_type = "Spaces" +column_width = 80 +collapse_simple_statement = "Never" From d4fd02499d9ed457a7e011b61d2100cfe1761f4e Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:10:35 -0400 Subject: [PATCH 05/25] fix: revert stylua config --- after/ftplugin/cp.lua | 4 +- after/ftplugin/cpin.lua | 4 +- after/ftplugin/cpout.lua | 4 +- ftdetect/cp.lua | 8 +- lua/cp/cache.lua | 204 ++++++----- lua/cp/config.lua | 158 ++++----- lua/cp/constants.lua | 22 +- lua/cp/execute.lua | 395 +++++++++------------ lua/cp/health.lua | 136 ++++--- lua/cp/init.lua | 743 ++++++++++++++++++--------------------- lua/cp/log.lua | 10 +- lua/cp/problem.lua | 89 ++--- lua/cp/scrape.lua | 402 ++++++++++----------- lua/cp/snippets.lua | 103 +++--- lua/cp/test.lua | 243 ++++++------- lua/cp/version.lua | 48 ++- lua/cp/window.lua | 216 ++++++------ plugin/cp.lua | 149 ++++---- stylua.toml | 4 - 19 files changed, 1363 insertions(+), 1579 deletions(-) delete mode 100644 stylua.toml diff --git a/after/ftplugin/cp.lua b/after/ftplugin/cp.lua index 622ad6a..76a9f86 100644 --- a/after/ftplugin/cp.lua +++ b/after/ftplugin/cp.lua @@ -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 diff --git a/after/ftplugin/cpin.lua b/after/ftplugin/cpin.lua index 622ad6a..76a9f86 100644 --- a/after/ftplugin/cpin.lua +++ b/after/ftplugin/cpin.lua @@ -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 diff --git a/after/ftplugin/cpout.lua b/after/ftplugin/cpout.lua index 1f4855f..857a799 100644 --- a/after/ftplugin/cpout.lua +++ b/after/ftplugin/cpout.lua @@ -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 diff --git a/ftdetect/cp.lua b/ftdetect/cp.lua index 9c1b868..2b6b593 100644 --- a/ftdetect/cp.lua +++ b/ftdetect/cp.lua @@ -1,6 +1,6 @@ vim.filetype.add({ - extension = { - cpin = 'cpin', - cpout = 'cpout', - }, + extension = { + cpin = "cpin", + cpout = "cpout", + }, }) diff --git a/lua/cp/cache.lua b/lua/cp/cache.lua index 20d0dd1..516ddb3 100644 --- a/lua/cp/cache.lua +++ b/lua/cp/cache.lua @@ -18,129 +18,129 @@ 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' }, - }) + vim.validate({ + platform = { platform, "string" }, + }) - if platform == 'cses' then - return os.time() + (30 * 24 * 60 * 60) - end - return nil + if platform == "cses" then + return os.time() + (30 * 24 * 60 * 60) + end + return nil end ---@param contest_data ContestData ---@param platform string ---@return boolean local function is_cache_valid(contest_data, platform) - vim.validate({ - contest_data = { contest_data, 'table' }, - platform = { platform, 'string' }, - }) + vim.validate({ + contest_data = { contest_data, "table" }, + platform = { platform, "string" }, + }) - if platform ~= 'cses' then - return true - end + if platform ~= "cses" then + return true + end - local expires_at = contest_data.expires_at - if not expires_at then - return false - end + local expires_at = contest_data.expires_at + if not expires_at then + return false + end - return os.time() < expires_at + return os.time() < expires_at end function M.load() - if vim.fn.filereadable(cache_file) == 0 then - cache_data = {} - return - end + if vim.fn.filereadable(cache_file) == 0 then + cache_data = {} + return + end - local content = vim.fn.readfile(cache_file) - if #content == 0 then - cache_data = {} - return - end + local content = vim.fn.readfile(cache_file) + if #content == 0 then + cache_data = {} + return + end - local ok, decoded = pcall(vim.json.decode, table.concat(content, '\n')) - if ok then - cache_data = decoded - else - cache_data = {} - end + local ok, decoded = pcall(vim.json.decode, table.concat(content, "\n")) + if ok then + cache_data = decoded + else + cache_data = {} + end end function M.save() - 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.mkdir(vim.fn.fnamemodify(cache_file, ":h"), "p") + local encoded = vim.json.encode(cache_data) + vim.fn.writefile(vim.split(encoded, "\n"), cache_file) end ---@param platform string ---@param contest_id string ---@return ContestData? function M.get_contest_data(platform, contest_id) - vim.validate({ - platform = { platform, 'string' }, - contest_id = { contest_id, 'string' }, - }) + vim.validate({ + platform = { platform, "string" }, + contest_id = { contest_id, "string" }, + }) - if not cache_data[platform] then - return nil - end + if not cache_data[platform] then + return nil + end - local contest_data = cache_data[platform][contest_id] - if not contest_data then - return nil - end + local contest_data = cache_data[platform][contest_id] + if not contest_data then + return nil + end - if not is_cache_valid(contest_data, platform) then - return nil - end + if not is_cache_valid(contest_data, platform) then + return nil + end - return contest_data + return contest_data end ---@param platform string ---@param contest_id string ---@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' }, - }) + vim.validate({ + platform = { platform, "string" }, + contest_id = { contest_id, "string" }, + problems = { problems, "table" }, + }) - if not cache_data[platform] then - cache_data[platform] = {} - end + if not cache_data[platform] then + cache_data[platform] = {} + end - cache_data[platform][contest_id] = { - problems = problems, - scraped_at = os.date('%Y-%m-%d'), - expires_at = get_expiry_date(platform), - } + cache_data[platform][contest_id] = { + problems = problems, + scraped_at = os.date("%Y-%m-%d"), + expires_at = get_expiry_date(platform), + } - M.save() + M.save() end ---@param platform string ---@param contest_id string function M.clear_contest_data(platform, contest_id) - vim.validate({ - platform = { platform, 'string' }, - contest_id = { contest_id, 'string' }, - }) + vim.validate({ + platform = { platform, "string" }, + contest_id = { contest_id, "string" }, + }) - if cache_data[platform] and cache_data[platform][contest_id] then - cache_data[platform][contest_id] = nil - M.save() - end + if cache_data[platform] and cache_data[platform][contest_id] then + cache_data[platform][contest_id] = nil + M.save() + end end ---@param platform string @@ -148,18 +148,17 @@ end ---@param problem_id? string ---@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 }, - }) + vim.validate({ + 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 - if not cache_data[platform] or not cache_data[platform][problem_key] then - return nil - end - return cache_data[platform][problem_key].test_cases + 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 + return cache_data[platform][problem_key].test_cases end ---@param platform string @@ -167,25 +166,24 @@ end ---@param problem_id? string ---@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' }, - }) + vim.validate({ + 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 - if not cache_data[platform] then - cache_data[platform] = {} - end - if not cache_data[platform][problem_key] then - cache_data[platform][problem_key] = {} - end + local problem_key = problem_id and (contest_id .. "_" .. problem_id) or contest_id + if not cache_data[platform] then + cache_data[platform] = {} + end + if not cache_data[platform][problem_key] then + cache_data[platform][problem_key] = {} + end - cache_data[platform][problem_key].test_cases = test_cases - cache_data[platform][problem_key].test_cases_cached_at = os.time() - M.save() + cache_data[platform][problem_key].test_cases = test_cases + cache_data[platform][problem_key].test_cases_cached_at = os.time() + M.save() end return M diff --git a/lua/cp/config.lua b/lua/cp/config.lua index 2e696db..6856db1 100644 --- a/lua/cp/config.lua +++ b/lua/cp/config.lua @@ -48,109 +48,99 @@ ---@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 = { - contests = {}, - snippets = {}, - hooks = { - before_run = nil, - before_debug = nil, - setup_code = nil, - }, - debug = false, - tile = nil, - filename = nil, + contests = {}, + snippets = {}, + hooks = { + before_run = nil, + before_debug = nil, + setup_code = nil, + }, + debug = false, + tile = nil, + filename = nil, } ---@param user_config cp.UserConfig|nil ---@return cp.Config function M.setup(user_config) - vim.validate({ - user_config = { user_config, { 'table', 'nil' }, true }, - }) + vim.validate({ + 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 }, - }) + 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 }, + }) - if user_config.hooks then - vim.validate({ - before_run = { - user_config.hooks.before_run, - { 'function', 'nil' }, - true, - }, - before_debug = { - user_config.hooks.before_debug, - { 'function', 'nil' }, - true, - }, - setup_code = { - user_config.hooks.setup_code, - { 'function', 'nil' }, - true, - }, - }) - end + if user_config.hooks then + vim.validate({ + before_run = { + user_config.hooks.before_run, + { "function", "nil" }, + true, + }, + before_debug = { + user_config.hooks.before_debug, + { "function", "nil" }, + true, + }, + setup_code = { + user_config.hooks.setup_code, + { "function", "nil" }, + true, + }, + }) + end - 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 - 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 - ), - ', ' - ) - ) - ) - end - end - end - end - end - end + 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 + 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), ", ") + ) + ) + end + end + end + end + end + end - local config = vim.tbl_deep_extend('force', M.defaults, user_config or {}) - return config + local config = vim.tbl_deep_extend("force", M.defaults, user_config or {}) + return config end ---@param contest_id string ---@param problem_id? string ---@return string local function default_filename(contest_id, problem_id) - vim.validate({ - contest_id = { contest_id, 'string' }, - problem_id = { problem_id, { 'string', 'nil' }, true }, - }) + vim.validate({ + contest_id = { contest_id, "string" }, + problem_id = { problem_id, { "string", "nil" }, true }, + }) - if problem_id then - return problem_id:lower() - else - return contest_id:lower() - end + if problem_id then + return problem_id:lower() + else + return contest_id:lower() + end end M.default_filename = default_filename diff --git a/lua/cp/constants.lua b/lua/cp/constants.lua index b33bd6b..e397c8f 100644 --- a/lua/cp/constants.lua +++ b/lua/cp/constants.lua @@ -1,24 +1,24 @@ 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 M.filetype_to_language = { - cc = M.CPP, - cxx = M.CPP, - cpp = M.CPP, - py = M.PYTHON, - py3 = M.PYTHON, + cc = M.CPP, + cxx = M.CPP, + cpp = M.CPP, + py = M.PYTHON, + py3 = M.PYTHON, } ---@type table M.canonical_filetypes = { - [M.CPP] = 'cpp', - [M.PYTHON] = 'python', + [M.CPP] = "cpp", + [M.PYTHON] = "python", } return M diff --git a/lua/cp/execute.lua b/lua/cp/execute.lua index 0ce0180..1b52a71 100644 --- a/lua/cp/execute.lua +++ b/lua/cp/execute.lua @@ -6,47 +6,44 @@ ---@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 ---@param contest_config table ---@return string local function get_language_from_file(source_file, contest_config) - vim.validate({ - source_file = { source_file, 'string' }, - contest_config = { contest_config, 'table' }, - }) + vim.validate({ + 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) - ) - return language + 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 ---@param cmd_template string[] ---@param substitutions table ---@return string[] local function substitute_template(cmd_template, substitutions) - vim.validate({ - cmd_template = { cmd_template, 'table' }, - substitutions = { substitutions, 'table' }, - }) + vim.validate({ + 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) - end - table.insert(result, substituted) - end - return result + local result = {} + for _, arg in ipairs(cmd_template) do + local substituted = arg + for key, value in pairs(substitutions) do + substituted = substituted:gsub("{" .. key .. "}", value) + end + table.insert(result, substituted) + end + return result end ---@param cmd_template string[] @@ -54,76 +51,69 @@ end ---@param substitutions table ---@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' }, - }) + vim.validate({ + cmd_template = { cmd_template, "table" }, + executable = { executable, { "string", "nil" }, true }, + substitutions = { substitutions, "table" }, + }) - local cmd = substitute_template(cmd_template, substitutions) - if executable then - table.insert(cmd, 1, executable) - end - return cmd + local cmd = substitute_template(cmd_template, substitutions) + if executable then + table.insert(cmd, 1, executable) + end + return cmd 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 ---@param substitutions table ---@return {code: integer, stderr: string} local function compile_generic(language_config, substitutions) - vim.validate({ - language_config = { language_config, 'table' }, - substitutions = { substitutions, 'table' }, - }) + vim.validate({ + language_config = { language_config, "table" }, + substitutions = { substitutions, "table" }, + }) - if not language_config.compile then - logger.log('no compilation step required') - return { code = 0, stderr = '' } - end + if not language_config.compile then + 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 + 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)) - else - logger.log( - ('compilation failed (%.1fms): %s'):format( - compile_time, - result.stderr - ), - vim.log.levels.WARN - ) - end + if result.code == 0 then + logger.log(("compilation successful (%.1fms)"):format(compile_time)) + else + logger.log(("compilation failed (%.1fms): %s"):format(compile_time, result.stderr), vim.log.levels.WARN) + end - return result + return result end ---@param cmd string[] @@ -131,51 +121,42 @@ end ---@param timeout_ms integer ---@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' }, - }) + vim.validate({ + 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() + local start_time = vim.uv.hrtime() - local result = vim.system(cmd, { - stdin = input_data, - timeout = timeout_ms, - text = true, - }):wait() + local result = vim.system(cmd, { + stdin = input_data, + timeout = timeout_ms, + text = true, + }):wait() - local end_time = vim.uv.hrtime() - local execution_time = (end_time - start_time) / 1000000 + local end_time = vim.uv.hrtime() + local execution_time = (end_time - start_time) / 1000000 - local actual_code = result.code or 0 + 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 - ) - elseif actual_code ~= 0 then - 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)) - end + if result.code == 124 then + 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) + else + logger.log(("execution successful (%.1fms)"):format(execution_time)) + end - return { - stdout = result.stdout or '', - stderr = result.stderr or '', - code = actual_code, - time_ms = execution_time, - timed_out = result.code == 124, - } + return { + stdout = result.stdout or "", + stderr = result.stderr or "", + code = actual_code, + time_ms = execution_time, + timed_out = result.code == 124, + } end ---@param exec_result ExecuteResult @@ -183,134 +164,104 @@ end ---@param is_debug boolean ---@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' }, - }) + vim.validate({ + exec_result = { exec_result, "table" }, + expected_file = { expected_file, "string" }, + is_debug = { is_debug, "boolean" }, + }) - local output_lines = { exec_result.stdout } - local metadata_lines = {} + local output_lines = { exec_result.stdout } + local metadata_lines = {} - if exec_result.timed_out then - 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) - ) - else - table.insert(metadata_lines, ('[code]: %d'):format(exec_result.code)) - end + if exec_result.timed_out then + 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)) + else + 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') + 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") - while #actual_lines > 0 and actual_lines[#actual_lines] == '' do - table.remove(actual_lines) - end + while #actual_lines > 0 and actual_lines[#actual_lines] == "" do + table.remove(actual_lines) + end - local matches = #actual_lines == #expected_content - if matches then - for i, line in ipairs(actual_lines) do - if line ~= expected_content[i] then - matches = false - break - end - end - end + local matches = #actual_lines == #expected_content + if matches then + for i, line in ipairs(actual_lines) do + if line ~= expected_content[i] then + matches = false + break + end + end + end - table.insert( - metadata_lines, - ('[matches]: %s'):format(matches and 'true' or 'false') - ) - end + 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 ---@param contest_config table ---@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' }, - }) + vim.validate({ + ctx = { ctx, "table" }, + contest_config = { contest_config, "table" }, + is_debug = { is_debug, "boolean" }, + }) - ensure_directories() + ensure_directories() - local language = get_language_from_file(ctx.source_file, contest_config) - local language_config = contest_config[language] + local language = get_language_from_file(ctx.source_file, contest_config) + local language_config = contest_config[language] - if not language_config then - vim.fn.writefile( - { 'Error: No configuration for language: ' .. language }, - ctx.output_file - ) - return - end + if not language_config then + vim.fn.writefile({ "Error: No configuration for language: " .. language }, ctx.output_file) + return + end - local substitutions = { - source = ctx.source_file, - binary = ctx.binary_file, - version = tostring(language_config.version), - } + local substitutions = { + source = ctx.source_file, + binary = ctx.binary_file, + version = tostring(language_config.version), + } - 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 - vim.fn.writefile({ compile_result.stderr }, ctx.output_file) - return - end - end + 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 + vim.fn.writefile({ compile_result.stderr }, ctx.output_file) + return + end + end - local input_data = '' - if vim.fn.filereadable(ctx.input_file) == 1 then - input_data = table.concat(vim.fn.readfile(ctx.input_file), '\n') .. '\n' - end + local input_data = "" + if vim.fn.filereadable(ctx.input_file) == 1 then + 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_call(output_buf, function() - vim.cmd.write() - end) - else - vim.fn.writefile(vim.split(formatted_output, '\n'), ctx.output_file) - end + 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_call(output_buf, function() + vim.cmd.write() + end) + else + vim.fn.writefile(vim.split(formatted_output, "\n"), ctx.output_file) + end end return M diff --git a/lua/cp/health.lua b/lua/cp/health.lua index f117a2d..738e9e2 100644 --- a/lua/cp/health.lua +++ b/lua/cp/health.lua @@ -1,101 +1,95 @@ 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') - else - vim.health.error('cp.nvim requires Neovim 0.10.0+') - end + 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+") + 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() - if result.code == 0 then - 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' - ) - end + local result = vim.system({ "uv", "--version" }, { text = true }):wait() + if result.code == 0 then + 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") + 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) - else - vim.health.warn( - 'Python virtual environment not set up - run :CP command to initialize' - ) - end + if vim.fn.isdirectory(venv_dir) == 1 then + 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") + 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' } - for _, scraper in ipairs(scrapers) do - local scraper_path = plugin_path .. '/scrapers/' .. scraper - if vim.fn.filereadable(scraper_path) == 1 then - vim.health.ok('Scraper found: ' .. scraper) - else - vim.health.error('Missing scraper: ' .. scraper) - end - end + local scrapers = { "atcoder.py", "codeforces.py", "cses.py" } + for _, scraper in ipairs(scrapers) do + local scraper_path = plugin_path .. "/scrapers/" .. scraper + if vim.fn.filereadable(scraper_path) == 1 then + vim.health.ok("Scraper found: " .. scraper) + else + vim.health.error("Missing scraper: " .. scraper) + end + end end local function check_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) - else - vim.health.info( - 'LuaSnip not available - template expansion will be limited' - ) - end + 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) + else + 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 context = cp.get_current_context() - if context.platform then - local info = context.platform - if context.contest_id then - info = info .. ' ' .. context.contest_id - if context.problem_id then - info = info .. ' ' .. context.problem_id - end - end - vim.health.info('Current context: ' .. info) - else - vim.health.info('No contest context set') - end + 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 + if context.problem_id then + info = info .. " " .. context.problem_id + end + end + vim.health.info("Current context: " .. info) + else + 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() - check_python_env() - check_scrapers() - check_luasnip() - check_config() + check_nvim_version() + check_uv() + check_python_env() + check_scrapers() + check_luasnip() + check_config() end return M diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 247e0fe..08a6c1a 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -1,17 +1,17 @@ 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) - return {} +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 local user_config = {} @@ -20,500 +20,423 @@ logger.set_config(config) local snippets_initialized = false local state = { - platform = nil, - contest_id = nil, - problem_id = nil, - saved_layout = nil, - saved_session = nil, - test_cases = nil, - test_states = {}, + platform = nil, + contest_id = nil, + problem_id = nil, + saved_layout = nil, + saved_session = nil, + test_cases = nil, + 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 - ) - return false - end + if not vim.tbl_contains(platforms, platform) then + 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') - return true + state.platform = platform + vim.fn.mkdir("build", "p") + vim.fn.mkdir("io", "p") + return true end ---@param contest_id string ---@param problem_id? string ---@param language? string local function setup_problem(contest_id, problem_id, language) - if not state.platform then - logger.log( - 'no platform set. run :CP first', - vim.log.levels.ERROR - ) - return - end + if not state.platform then + logger.log("no platform set. run :CP 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) - if not metadata_result.success then - logger.log( - 'failed to load contest metadata: ' - .. (metadata_result.error or 'unknown error'), - vim.log.levels.WARN - ) - end + 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"), + vim.log.levels.WARN + ) + end - vim.cmd('silent only') + vim.cmd("silent only") - state.contest_id = contest_id - state.problem_id = problem_id + state.contest_id = contest_id + state.problem_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 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) + 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 - ) - 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 - ) - ) - state.test_cases = scrape_result.test_cases + 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) + 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)) + 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 - ) - end - end + if scrape_result.test_cases then + cache.set_test_cases(state.platform, contest_id, problem_id, scrape_result.test_cases) + end + end - vim.cmd.e(scrape_ctx.source_file) + 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 has_luasnip then - local prefixed_trigger = ('cp.nvim/%s.%s'):format( - state.platform, - language - ) + 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) - vim.api.nvim_buf_set_lines(0, 0, -1, false, { prefixed_trigger }) - vim.api.nvim_win_set_cursor(0, { 1, #prefixed_trigger }) - vim.cmd.startinsert({ bang = true }) + vim.api.nvim_buf_set_lines(0, 0, -1, false, { prefixed_trigger }) + vim.api.nvim_win_set_cursor(0, { 1, #prefixed_trigger }) + vim.cmd.startinsert({ bang = true }) - vim.schedule(function() - if luasnip.expandable() then - luasnip.expand() - else - 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'):format(state.platform)) - end - end + vim.schedule(function() + if luasnip.expandable() then + luasnip.expand() + else + 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"):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) - end + if config.hooks and config.hooks.setup_code then + config.hooks.setup_code(ctx) + end - local source_buf = vim.api.nvim_get_current_buf() - local input_buf = vim.fn.bufnr(ctx.input_file, true) - local output_buf = vim.fn.bufnr(ctx.output_file, true) + local source_buf = vim.api.nvim_get_current_buf() + local input_buf = vim.fn.bufnr(ctx.input_file, true) + local output_buf = vim.fn.bufnr(ctx.output_file, true) - local tile_fn = config.tile or window.default_tile - tile_fn(source_buf, input_buf, output_buf) + 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) - return nil - end - return filename + local filename = vim.fn.expand("%:t:r") + if filename == "" then + logger.log("no file open", vim.log.levels.ERROR) + return nil + end + return filename end local function run_problem() - local problem_id = get_current_problem() - if not problem_id then - return - end + local problem_id = get_current_problem() + if not problem_id then + 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) - return - end + if not state.platform then + 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 contest_config = config.contests[state.platform] + 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) - end + if config.hooks and config.hooks.before_run then + config.hooks.before_run(ctx) + end - vim.schedule(function() - execute.run_problem(ctx, contest_config, false) - vim.cmd.checktime() - end) + vim.schedule(function() + execute.run_problem(ctx, contest_config, false) + vim.cmd.checktime() + end) end local function debug_problem() - local problem_id = get_current_problem() - if not problem_id then - return - end + local problem_id = get_current_problem() + if not problem_id then + return + end - if not state.platform then - logger.log('no platform set', vim.log.levels.ERROR) - return - end + if not state.platform then + 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 contest_config = config.contests[state.platform] + 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) - end + if config.hooks and config.hooks.before_debug then + config.hooks.before_debug(ctx) + end - vim.schedule(function() - execute.run_problem(ctx, contest_config, true) - vim.cmd.checktime() - end) + vim.schedule(function() + execute.run_problem(ctx, contest_config, true) + vim.cmd.checktime() + end) end ---@param delta number 1 for next, -1 for prev ---@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 first', - vim.log.levels.ERROR - ) - return - end + if not state.platform or not state.contest_id then + logger.log("no contest set. run :CP first", vim.log.levels.ERROR) + return + end - cache.load() - 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 - ) - return - end + cache.load() + 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) + return + end - local problems = contest_data.problems - local current_problem_id + local problems = contest_data.problems + local current_problem_id - if state.platform == 'cses' then - current_problem_id = state.contest_id - else - current_problem_id = state.problem_id - end + 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) - return - end + if not current_problem_id then + logger.log("no current problem set", vim.log.levels.ERROR) + return + end - local current_index = nil - for i, prob in ipairs(problems) do - if prob.id == current_problem_id then - current_index = i - break - end - end + local current_index = nil + for i, prob in ipairs(problems) do + if prob.id == current_problem_id then + current_index = i + break + end + end - if not current_index then - logger.log('current problem not found in contest', vim.log.levels.ERROR) - return - end + if not current_index then + logger.log("current problem not found in contest", vim.log.levels.ERROR) + return + end - local new_index = current_index + delta + 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 - ) - return - end + 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) + return + end - local new_problem = problems[new_index] + local new_problem = problems[new_index] - if state.platform == 'cses' then - setup_problem(new_problem.id, nil, language) - else - setup_problem(state.contest_id, new_problem.id, language) - end + if state.platform == "cses" then + setup_problem(new_problem.id, nil, language) + else + setup_problem(state.contest_id, new_problem.id, language) + end end local function parse_command(args) - if #args == 0 then - return { - type = 'error', - message = 'Usage: :CP [problem] [--lang=] | :CP | :CP ', - } - end + if #args == 0 then + return { + type = "error", + message = "Usage: :CP [problem] [--lang=] | :CP | :CP ", + } + end - local language = nil + local language = nil - for i, arg in ipairs(args) do - local lang_match = arg:match('^--lang=(.+)$') - if lang_match then - language = lang_match - elseif arg == '--lang' then - if i + 1 <= #args then - language = args[i + 1] - else - return { type = 'error', message = '--lang requires a value' } - end - end - end + for i, arg in ipairs(args) do + local lang_match = arg:match("^--lang=(.+)$") + if lang_match then + language = lang_match + elseif arg == "--lang" then + if i + 1 <= #args then + language = args[i + 1] + else + 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) - end, args) + local filtered_args = vim.tbl_filter(function(arg) + return not (arg:match("^--lang") or arg == language) + end, args) - local first = filtered_args[1] + local first = filtered_args[1] - if vim.tbl_contains(actions, first) then - return { type = 'action', action = first, language = language } - end + if vim.tbl_contains(actions, first) then + return { type = "action", action = first, language = language } + end - if vim.tbl_contains(platforms, first) then - if #filtered_args == 1 then - return { - type = 'platform_only', - platform = first, - language = language, - } - elseif #filtered_args == 2 then - if first == 'cses' then - return { - type = 'cses_problem', - platform = first, - problem = filtered_args[2], - language = language, - } - else - return { - type = 'contest_setup', - platform = first, - contest = filtered_args[2], - language = language, - } - end - elseif #filtered_args == 3 then - return { - type = 'full_setup', - platform = first, - contest = filtered_args[2], - problem = filtered_args[3], - language = language, - } - else - return { type = 'error', message = 'Too many arguments' } - end - end + if vim.tbl_contains(platforms, first) then + if #filtered_args == 1 then + return { + type = "platform_only", + platform = first, + language = language, + } + elseif #filtered_args == 2 then + if first == "cses" then + return { + type = "cses_problem", + platform = first, + problem = filtered_args[2], + language = language, + } + else + return { + type = "contest_setup", + platform = first, + contest = filtered_args[2], + language = language, + } + end + elseif #filtered_args == 3 then + return { + type = "full_setup", + platform = first, + contest = filtered_args[2], + problem = filtered_args[3], + language = language, + } + else + 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 } - end + if state.platform and state.contest_id then + 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) + local cmd = parse_command(opts.fargs) - if cmd.type == 'error' then - logger.log(cmd.message, vim.log.levels.ERROR) - return - end + 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 - run_problem() - elseif cmd.action == 'debug' then - debug_problem() - elseif cmd.action == 'next' then - navigate_problem(1, cmd.language) - elseif cmd.action == 'prev' then - navigate_problem(-1, cmd.language) - end - return - end + if cmd.type == "action" then + if cmd.action == "run" then + run_problem() + elseif cmd.action == "debug" then + debug_problem() + elseif cmd.action == "next" then + navigate_problem(1, cmd.language) + elseif cmd.action == "prev" then + navigate_problem(-1, cmd.language) + end + return + end - if cmd.type == 'platform_only' then - set_platform(cmd.platform) - return - end + if cmd.type == "platform_only" then + set_platform(cmd.platform) + return + end - 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) - if not metadata_result.success then - logger.log( - '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 - ) - ) - end - end - return - end + 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) + if not metadata_result.success then + logger.log( + "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) + ) + end + end + return + end - 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) - if not metadata_result.success then - logger.log( - '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 - ) - ) - end + 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) + if not metadata_result.success then + logger.log( + "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) + ) + end - setup_problem(cmd.contest, cmd.problem, cmd.language) - end - return - end + setup_problem(cmd.contest, cmd.problem, cmd.language) + end + return + end - if cmd.type == 'cses_problem' then - if set_platform(cmd.platform) then - 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'), - vim.log.levels.WARN - ) - end - setup_problem(cmd.problem, nil, cmd.language) - end - return - end + if cmd.type == "cses_problem" then + if set_platform(cmd.platform) then + 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"), + vim.log.levels.WARN + ) + end + setup_problem(cmd.problem, nil, cmd.language) + end + return + end - 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) - end - return - end + 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) + end + return + end end function M.setup(opts) - opts = opts or {} - user_config = opts - config = config_module.setup(user_config) - logger.set_config(config) - if not snippets_initialized then - snippets.setup(config) - snippets_initialized = true - end + opts = opts or {} + user_config = opts + config = config_module.setup(user_config) + logger.set_config(config) + if not snippets_initialized then + snippets.setup(config) + snippets_initialized = true + end end function M.get_current_context() - return { - platform = state.platform, - contest_id = state.contest_id, - problem_id = state.problem_id, - } + return { + platform = state.platform, + contest_id = state.contest_id, + problem_id = state.problem_id, + } end function M.is_initialized() - return true + return true end return M diff --git a/lua/cp/log.lua b/lua/cp/log.lua index e6fea22..2dc033e 100644 --- a/lua/cp/log.lua +++ b/lua/cp/log.lua @@ -3,14 +3,14 @@ local M = {} local config = nil function M.set_config(user_config) - config = user_config + config = user_config 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) - end + 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) + end end return M diff --git a/lua/cp/problem.lua b/lua/cp/problem.lua index 8acd59e..088b908 100644 --- a/lua/cp/problem.lua +++ b/lua/cp/problem.lua @@ -18,61 +18,50 @@ local M = {} ---@param language? string ---@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 }, - }) + 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 }, + }) - local contest_config = config.contests[contest] - if not contest_config then - error(("No contest config found for '%s'"):format(contest)) - end + local contest_config = config.contests[contest] + if not contest_config then + error(("No contest config found for '%s'"):format(contest)) + end - 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 - ) - ) - end - if not language_config.extension then - error( - ("No extension configured for language '%s' in contest '%s'"):format( - target_language, - contest - ) - ) - end + 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)) + end + if not language_config.extension then + 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') - else - local default_filename = require('cp.config').default_filename - base_name = default_filename(contest_id, problem_id) - 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") + else + 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), - problem_name = base_name, - } + 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), + problem_name = base_name, + } end return M diff --git a/lua/cp/scrape.lua b/lua/cp/scrape.lua index 2c784ce..b76b3af 100644 --- a/lua/cp/scrape.lua +++ b/lua/cp/scrape.lua @@ -1,265 +1,245 @@ 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() - return result.code == 0 + 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 plugin_path = get_plugin_path() + local venv_dir = plugin_path .. "/.venv" - if vim.fn.executable('uv') == 0 then - logger.log( - '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.executable("uv") == 0 then + logger.log( + "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() - if result.code ~= 0 then - logger.log( - 'failed to setup Python environment: ' .. result.stderr, - vim.log.levels.ERROR - ) - return false - end - logger.log('python environment setup complete') - 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() + if result.code ~= 0 then + logger.log("failed to setup Python environment: " .. result.stderr, vim.log.levels.ERROR) + return false + end + logger.log("python environment setup complete") + end - return true + return true end ---@param platform string ---@param contest_id string ---@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' }, - }) + vim.validate({ + platform = { platform, "string" }, + contest_id = { contest_id, "string" }, + }) - cache.load() + cache.load() - local cached_data = cache.get_contest_data(platform, contest_id) - if cached_data then - return { - success = true, - problems = cached_data.problems, - } - end + local cached_data = cache.get_contest_data(platform, contest_id) + if cached_data then + return { + success = true, + problems = cached_data.problems, + } + end - if not check_internet_connectivity() then - return { - success = false, - error = 'No internet connection available', - } - end + if not check_internet_connectivity() then + return { + success = false, + error = "No internet connection available", + } + end - if not setup_python_env() then - return { - success = false, - error = 'Python environment setup failed', - } - end + if not setup_python_env() then + return { + success = false, + error = "Python environment setup failed", + } + end - local plugin_path = get_plugin_path() - local scraper_path = plugin_path .. '/scrapers/' .. platform .. '.py' + local plugin_path = get_plugin_path() + local scraper_path = plugin_path .. "/scrapers/" .. platform .. ".py" - local args - if platform == 'cses' then - args = { - 'uv', - 'run', - '--directory', - plugin_path, - scraper_path, - 'metadata', - } - else - args = { - 'uv', - 'run', - '--directory', - plugin_path, - scraper_path, - 'metadata', - contest_id, - } - end + local args + if platform == "cses" then + args = { + "uv", + "run", + "--directory", + plugin_path, + scraper_path, + "metadata", + } + else + args = { + "uv", + "run", + "--directory", + plugin_path, + scraper_path, + "metadata", + contest_id, + } + end - local result = vim.system(args, { - cwd = plugin_path, - text = true, - timeout = 30000, - }):wait() + local result = vim.system(args, { + cwd = plugin_path, + text = true, + timeout = 30000, + }):wait() - if result.code ~= 0 then - return { - success = false, - error = 'Failed to run metadata scraper: ' - .. (result.stderr or 'Unknown error'), - } - end + if result.code ~= 0 then + return { + success = false, + error = "Failed to run metadata scraper: " .. (result.stderr or "Unknown error"), + } + end - local ok, data = pcall(vim.json.decode, result.stdout) - if not ok then - return { - success = false, - error = 'Failed to parse metadata scraper output: ' - .. tostring(data), - } - end + local ok, data = pcall(vim.json.decode, result.stdout) + if not ok then + return { + success = false, + error = "Failed to parse metadata scraper output: " .. tostring(data), + } + end - if not data.success then - return data - end + if not data.success then + return data + end - local problems_list - if platform == 'cses' then - problems_list = data.categories and data.categories['CSES Problem Set'] - or {} - else - problems_list = data.problems or {} - end + local problems_list + if platform == "cses" then + problems_list = data.categories and data.categories["CSES Problem Set"] or {} + else + problems_list = data.problems or {} + end - cache.set_contest_data(platform, contest_id, problems_list) - return { - success = true, - problems = problems_list, - } + cache.set_contest_data(platform, contest_id, problems_list) + return { + success = true, + problems = problems_list, + } end ---@param ctx ProblemContext ---@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' }, - }) + vim.validate({ + ctx = { ctx, "table" }, + }) - ensure_io_directory() + ensure_io_directory() - 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, - test_count = 1, - } - end + 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, + test_count = 1, + } + end - if not check_internet_connectivity() then - return { - success = false, - problem_id = ctx.problem_name, - error = 'No internet connection available', - } - end + if not check_internet_connectivity() then + return { + success = false, + problem_id = ctx.problem_name, + error = "No internet connection available", + } + end - if not setup_python_env() then - return { - success = false, - problem_id = ctx.problem_name, - error = 'Python environment setup failed', - } - end + if not setup_python_env() then + return { + success = false, + problem_id = ctx.problem_name, + error = "Python environment setup failed", + } + end - local plugin_path = get_plugin_path() - local scraper_path = plugin_path .. '/scrapers/' .. ctx.contest .. '.py' + local plugin_path = get_plugin_path() + local scraper_path = plugin_path .. "/scrapers/" .. ctx.contest .. ".py" - local args - if ctx.contest == 'cses' then - args = { - 'uv', - 'run', - '--directory', - plugin_path, - scraper_path, - 'tests', - ctx.contest_id, - } - else - args = { - 'uv', - 'run', - '--directory', - plugin_path, - scraper_path, - 'tests', - ctx.contest_id, - ctx.problem_id, - } - end + local args + if ctx.contest == "cses" then + args = { + "uv", + "run", + "--directory", + plugin_path, + scraper_path, + "tests", + ctx.contest_id, + } + else + args = { + "uv", + "run", + "--directory", + plugin_path, + scraper_path, + "tests", + ctx.contest_id, + ctx.problem_id, + } + end - local result = vim.system(args, { - cwd = plugin_path, - text = true, - timeout = 30000, - }):wait() + local result = vim.system(args, { + cwd = plugin_path, + text = true, + timeout = 30000, + }):wait() - if result.code ~= 0 then - return { - success = false, - problem_id = ctx.problem_name, - error = 'Failed to run tests scraper: ' - .. (result.stderr or 'Unknown error'), - } - end + if result.code ~= 0 then + return { + success = false, + problem_id = ctx.problem_name, + error = "Failed to run tests scraper: " .. (result.stderr or "Unknown error"), + } + end - local ok, data = pcall(vim.json.decode, result.stdout) - if not ok then - return { - success = false, - problem_id = ctx.problem_name, - error = 'Failed to parse tests scraper output: ' .. tostring(data), - } - end + local ok, data = pcall(vim.json.decode, result.stdout) + if not ok then + return { + success = false, + problem_id = ctx.problem_name, + error = "Failed to parse tests scraper output: " .. tostring(data), + } + end - if not data.success then - return data - end + if not data.success then + return data + 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', '') + 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", "") - 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 + 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 { - success = true, - problem_id = ctx.problem_name, - test_count = data.test_cases and #data.test_cases or 0, - test_cases = data.test_cases, - url = data.url, - } + return { + success = true, + problem_id = ctx.problem_name, + test_count = data.test_cases and #data.test_cases or 0, + test_cases = data.test_cases, + url = data.url, + } end return M diff --git a/lua/cp/snippets.lua b/lua/cp/snippets.lua index 4eb90e2..d9805b4 100644 --- a/lua/cp/snippets.lua +++ b/lua/cp/snippets.lua @@ -1,32 +1,28 @@ local M = {} -local logger = require('cp.log') +local logger = require("cp.log") function M.setup(config) - local ok, ls = pcall(require, 'luasnip') - if not ok then - logger.log( - 'LuaSnip not available - snippets disabled', - vim.log.levels.INFO - ) - return - end + local ok, ls = pcall(require, "luasnip") + if not ok then + 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 filetype_to_language = constants.filetype_to_language + local constants = require("cp.constants") + local filetype_to_language = constants.filetype_to_language - local language_to_filetype = {} - for ext, lang in pairs(filetype_to_language) do - if not language_to_filetype[lang] then - language_to_filetype[lang] = ext - end - end + local language_to_filetype = {} + for ext, lang in pairs(filetype_to_language) do + if not language_to_filetype[lang] then + language_to_filetype[lang] = ext + end + end - local template_definitions = { - cpp = { - codeforces = [[#include + local template_definitions = { + cpp = { + codeforces = [[#include using namespace std; @@ -47,7 +43,7 @@ int main() {{ return 0; }}]], - atcoder = [[#include + atcoder = [[#include using namespace std; @@ -72,7 +68,7 @@ int main() {{ return 0; }}]], - cses = [[#include + cses = [[#include using namespace std; @@ -83,10 +79,10 @@ int main() {{ return 0; }}]], - }, + }, - python = { - codeforces = [[def solve(): + python = { + codeforces = [[def solve(): {} if __name__ == "__main__": @@ -94,44 +90,41 @@ if __name__ == "__main__": for _ in range(tc): solve()]], - atcoder = [[def solve(): + atcoder = [[def solve(): {} if __name__ == "__main__": solve()]], - cses = [[{}]], - }, - } + cses = [[{}]], + }, + } - local user_overrides = {} - for _, snippet in ipairs(config.snippets or {}) do - user_overrides[snippet.trigger] = snippet - end + local user_overrides = {} + for _, snippet in ipairs(config.snippets or {}) do + user_overrides[snippet.trigger] = snippet + end - for language, template_set in pairs(template_definitions) do - local snippets = {} - local filetype = constants.canonical_filetypes[language] + for language, template_set in pairs(template_definitions) do + local snippets = {} + local filetype = constants.canonical_filetypes[language] - for contest, template in pairs(template_set) do - 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) })) - ) - end - end + for contest, template in pairs(template_set) do + 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) }))) + end + end - for trigger, snippet in pairs(user_overrides) do - local prefix_match = trigger:match('^cp%.nvim/[^.]+%.(.+)$') - if prefix_match == language then - table.insert(snippets, snippet) - end - end + for trigger, snippet in pairs(user_overrides) do + local prefix_match = trigger:match("^cp%.nvim/[^.]+%.(.+)$") + if prefix_match == language then + table.insert(snippets, snippet) + end + end - ls.add_snippets(filetype, snippets) - end + ls.add_snippets(filetype, snippets) + end end return M diff --git a/lua/cp/test.lua b/lua/cp/test.lua index da14e49..96e8d1a 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -1,180 +1,163 @@ 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 = {}, - current_index = 1, - buffer = nil, - namespace = nil, - is_active = false, - saved_layout = nil, + test_cases = {}, + current_index = 1, + buffer = nil, + namespace = nil, + is_active = false, + saved_layout = nil, } local function create_test_case(index, input, expected) - return { - index = index, - input = input, - expected = expected, - status = 'pending', - actual = nil, - time_ms = nil, - error = nil, - } + return { + index = index, + input = input, + expected = expected, + status = "pending", + actual = nil, + time_ms = nil, + error = nil, + } end local function parse_test_cases_from_cache(platform, contest_id, problem_id) - local cache = require('cp.cache') - cache.load() - local cached_test_cases = - cache.get_test_cases(platform, contest_id, problem_id) + local cache = require("cp.cache") + cache.load() + 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 {} - end + if not cached_test_cases or #cached_test_cases == 0 then + return {} + end - 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) - ) - end + 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)) + end - return test_cases + 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 - return {} - end + 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) } + 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_config = contest_config[language_name] + 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', - time_ms = 0, - } - end + if not language_config then + return { + status = "fail", + actual = "", + error = "No language configuration", + time_ms = 0, + } + end - local function substitute_template(cmd_template, substitutions) - local result = {} - for _, arg in ipairs(cmd_template) do - local substituted = arg - for key, value in pairs(substitutions) do - substituted = substituted:gsub('{' .. key .. '}', value) - end - table.insert(result, substituted) - end - return result - end + local function substitute_template(cmd_template, substitutions) + local result = {} + for _, arg in ipairs(cmd_template) do + local substituted = arg + for key, value in pairs(substitutions) do + substituted = substituted:gsub("{" .. key .. "}", value) + end + table.insert(result, substituted) + end + return result + end - local function build_command(cmd_template, executable, substitutions) - local cmd = substitute_template(cmd_template, substitutions) - if executable then - table.insert(cmd, 1, executable) - end - return cmd - end + local function build_command(cmd_template, executable, substitutions) + local cmd = substitute_template(cmd_template, substitutions) + if executable then + table.insert(cmd, 1, executable) + end + return cmd + end - local substitutions = { - source = ctx.source_file, - binary = ctx.binary_file, - version = tostring(language_config.version or ''), - } + local substitutions = { + source = ctx.source_file, + binary = ctx.binary_file, + 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', - timeout = contest_config.timeout_ms or 2000, - text = true, - }):wait() - local execution_time = (vim.uv.hrtime() - start_time) / 1000000 + local start_time = vim.uv.hrtime() + local result = vim.system(run_cmd, { + 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 matches = actual_output == expected_output + 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', - actual = actual_output, - error = result.code ~= 0 and result.stderr or nil, - time_ms = execution_time, - } + return { + 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, + } 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) - end + if #test_cases == 0 then + 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 + test_panel_state.test_cases = test_cases + test_panel_state.current_index = 1 - logger.log(('loaded %d test case(s)'):format(#test_cases)) - return #test_cases > 0 + logger.log(("loaded %d test case(s)"):format(#test_cases)) + return #test_cases > 0 end function M.run_test_case(ctx, contest_config, index) - local test_case = test_panel_state.test_cases[index] - if not test_case then - return false - end + local test_case = test_panel_state.test_cases[index] + if not test_case then + 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) + local result = run_single_test_case(ctx, contest_config, test_case) - test_case.status = result.status - test_case.actual = result.actual - test_case.error = result.error - test_case.time_ms = result.time_ms + test_case.status = result.status + test_case.actual = result.actual + test_case.error = result.error + test_case.time_ms = result.time_ms - return true + return true end function M.run_all_test_cases(ctx, contest_config) - local results = {} - for i, _ in ipairs(test_panel_state.test_cases) do - M.run_test_case(ctx, contest_config, i) - table.insert(results, test_panel_state.test_cases[i]) - end - return results + local results = {} + for i, _ in ipairs(test_panel_state.test_cases) do + M.run_test_case(ctx, contest_config, i) + table.insert(results, test_panel_state.test_cases[i]) + end + return results end function M.get_test_panel_state() - return test_panel_state + return test_panel_state end return M diff --git a/lua/cp/version.lua b/lua/cp/version.lua index fc4289c..0cd247d 100644 --- a/lua/cp/version.lua +++ b/lua/cp/version.lua @@ -1,37 +1,33 @@ 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' }, - { - cwd = plugin_root, - text = true, - } - ) - :wait() + local result = vim.system({ "git", "describe", "--tags", "--always", "--dirty" }, { + cwd = plugin_root, + text = true, + }):wait() - if result.code == 0 then - return result.stdout:gsub('\n', '') - else - return 'unknown' - end + if result.code == 0 then + return result.stdout:gsub("\n", "") + else + return "unknown" + end end local function parse_semver(version_string) - local semver = version_string:match('^v?(%d+%.%d+%.%d+)') - if semver then - local major, minor, patch = semver:match('(%d+)%.(%d+)%.(%d+)') - return { - full = semver, - major = tonumber(major), - minor = tonumber(minor), - patch = tonumber(patch), - } - end - return nil + local semver = version_string:match("^v?(%d+%.%d+%.%d+)") + if semver then + local major, minor, patch = semver:match("(%d+)%.(%d+)%.(%d+)") + return { + full = semver, + major = tonumber(major), + minor = tonumber(minor), + patch = tonumber(patch), + } + end + return nil end M.version = get_git_version() diff --git a/lua/cp/window.lua b/lua/cp/window.lua index e5efde2..1f6aa42 100644 --- a/lua/cp/window.lua +++ b/lua/cp/window.lua @@ -10,147 +10,139 @@ ---@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 function M.save_layout() - local windows = {} - for _, win in ipairs(vim.api.nvim_list_wins()) do - if vim.api.nvim_win_is_valid(win) then - local bufnr = vim.api.nvim_win_get_buf(win) - windows[win] = { - bufnr = bufnr, - view = vim.fn.winsaveview(), - width = vim.api.nvim_win_get_width(win), - height = vim.api.nvim_win_get_height(win), - } - end - end + local windows = {} + for _, win in ipairs(vim.api.nvim_list_wins()) do + if vim.api.nvim_win_is_valid(win) then + local bufnr = vim.api.nvim_win_get_buf(win) + windows[win] = { + bufnr = bufnr, + view = vim.fn.winsaveview(), + width = vim.api.nvim_win_get_width(win), + height = vim.api.nvim_win_get_height(win), + } + end + end - return { - windows = windows, - current_win = vim.api.nvim_get_current_win(), - layout = vim.fn.winrestcmd(), - } + return { + windows = windows, + current_win = vim.api.nvim_get_current_win(), + layout = vim.fn.winrestcmd(), + } end ---@param state? WindowState ---@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 }, - }) + vim.validate({ + state = { state, { "table", "nil" }, true }, + tile_fn = { tile_fn, { "function", "nil" }, true }, + }) - if not state then - return - end + if not state then + return + end - vim.cmd.diffoff() + vim.cmd.diffoff() - 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 - 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') - break - end - end - end - end + 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 + 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") + 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 source_file - 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') - if vim.tbl_contains(valid_extensions, ext) then - source_file = file - break - end - end - source_file = source_file or files[1] - end + 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 source_file + 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") + if vim.tbl_contains(valid_extensions, ext) then + source_file = file + break + end + end + source_file = source_file or files[1] + end - if not source_file or vim.fn.filereadable(source_file) == 0 then - return - end + if not source_file or vim.fn.filereadable(source_file) == 0 then + return + end - vim.cmd.edit(source_file) - local source_buf = vim.api.nvim_get_current_buf() - local input_buf = vim.fn.bufnr(input_file, true) - local output_buf = vim.fn.bufnr(output_file, true) + vim.cmd.edit(source_file) + local source_buf = vim.api.nvim_get_current_buf() + local input_buf = vim.fn.bufnr(input_file, true) + local output_buf = vim.fn.bufnr(output_file, true) - if tile_fn then - tile_fn(source_buf, input_buf, output_buf) - else - M.default_tile(source_buf, input_buf, output_buf) - end - else - vim.cmd(state.layout) + if tile_fn then + tile_fn(source_buf, input_buf, output_buf) + else + M.default_tile(source_buf, input_buf, output_buf) + end + else + vim.cmd(state.layout) - for win, win_state in pairs(state.windows) do - if vim.api.nvim_win_is_valid(win) then - vim.api.nvim_set_current_win(win) - if vim.api.nvim_get_current_buf() == win_state.bufnr then - vim.fn.winrestview(win_state.view) - end - end - end + for win, win_state in pairs(state.windows) do + if vim.api.nvim_win_is_valid(win) then + vim.api.nvim_set_current_win(win) + if vim.api.nvim_get_current_buf() == win_state.bufnr then + vim.fn.winrestview(win_state.view) + end + end + end - if vim.api.nvim_win_is_valid(state.current_win) then - vim.api.nvim_set_current_win(state.current_win) - end - end + if vim.api.nvim_win_is_valid(state.current_win) then + vim.api.nvim_set_current_win(state.current_win) + end + end end ---@param source_buf integer ---@param input_buf integer ---@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' }, - }) + vim.validate({ + 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' - M.clearcol() - 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' - M.clearcol() - vim.cmd.wincmd('h') + vim.api.nvim_set_current_buf(source_buf) + vim.cmd.vsplit() + vim.api.nvim_set_current_buf(output_buf) + vim.bo.filetype = "cp" + M.clearcol() + 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" + M.clearcol() + vim.cmd.wincmd("h") end M.default_tile = default_tile diff --git a/plugin/cp.lua b/plugin/cp.lua index 6bb0987..0bab4b9 100644 --- a/plugin/cp.lua +++ b/plugin/cp.lua @@ -1,89 +1,88 @@ if vim.g.loaded_cp then - return + return 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') - cp.handle_command(opts) +vim.api.nvim_create_user_command("CP", function(opts) + local cp = require("cp") + cp.handle_command(opts) end, { - nargs = '*', - desc = 'Competitive programming helper', - complete = function(ArgLead, CmdLine, _) - local languages = vim.tbl_keys(constants.canonical_filetypes) + nargs = "*", + desc = "Competitive programming helper", + complete = function(ArgLead, CmdLine, _) + local languages = vim.tbl_keys(constants.canonical_filetypes) - if ArgLead:match('^--lang=') then - local lang_completions = {} - for _, lang in ipairs(languages) do - 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("^--lang=") then + local lang_completions = {} + for _, lang in ipairs(languages) do + 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 - return vim.tbl_filter(function(completion) - return completion:find(ArgLead, 1, true) == 1 - end, { '--lang' }) - end + 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 - local args = vim.split(vim.trim(CmdLine), '%s+') - local num_args = #args - if CmdLine:sub(-1) == ' ' then - num_args = num_args + 1 - end + local args = vim.split(vim.trim(CmdLine), "%s+") + local num_args = #args + if CmdLine:sub(-1) == " " then + num_args = num_args + 1 + end - local lang_flag_present = vim.tbl_contains(args, '--lang') - or vim.iter(args):any(function(arg) - return arg:match('^--lang=') - end) + local lang_flag_present = vim.tbl_contains(args, "--lang") + or vim.iter(args):any(function(arg) + return arg:match("^--lang=") + end) - if num_args == 2 then - local candidates = { '--lang' } - vim.list_extend(candidates, actions) - local cp = require('cp') - local context = cp.get_current_context() - if context.platform and context.contest_id then - local cache = require('cp.cache') - cache.load() - 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) - end - end - else - vim.list_extend(candidates, platforms) - end - return vim.tbl_filter(function(cmd) - return cmd:find(ArgLead, 1, true) == 1 - end, candidates) - 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') - cache.load() - local contest_data = cache.get_contest_data(args[2], args[3]) - if contest_data and contest_data.problems then - local candidates = { '--lang' } - for _, problem in ipairs(contest_data.problems) do - table.insert(candidates, problem.id) - end - return vim.tbl_filter(function(cmd) - return cmd:find(ArgLead, 1, true) == 1 - end, candidates) - end - end - end - return {} - end, + if num_args == 2 then + local candidates = { "--lang" } + vim.list_extend(candidates, actions) + local cp = require("cp") + local context = cp.get_current_context() + if context.platform and context.contest_id then + local cache = require("cp.cache") + cache.load() + 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) + end + end + else + vim.list_extend(candidates, platforms) + end + return vim.tbl_filter(function(cmd) + return cmd:find(ArgLead, 1, true) == 1 + end, candidates) + 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") + cache.load() + local contest_data = cache.get_contest_data(args[2], args[3]) + if contest_data and contest_data.problems then + local candidates = { "--lang" } + for _, problem in ipairs(contest_data.problems) do + table.insert(candidates, problem.id) + end + return vim.tbl_filter(function(cmd) + return cmd:find(ArgLead, 1, true) == 1 + end, candidates) + end + end + end + return {} + end, }) diff --git a/stylua.toml b/stylua.toml deleted file mode 100644 index dda733b..0000000 --- a/stylua.toml +++ /dev/null @@ -1,4 +0,0 @@ -quote_style = "AutoPreferSingle" -indent_type = "Spaces" -column_width = 80 -collapse_simple_statement = "Never" From 0fb247f18b32e696bb046d1c0ed0313f924a2522 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:15:21 -0400 Subject: [PATCH 06/25] fix: cleanup clearcol() manual calls in favor of per-filetype --- after/ftplugin/cptest.lua | 7 ++++++ lua/cp/init.lua | 50 +++++++++++++++++++++++++++++++++++++++ lua/cp/window.lua | 10 -------- 3 files changed, 57 insertions(+), 10 deletions(-) create mode 100644 after/ftplugin/cptest.lua diff --git a/after/ftplugin/cptest.lua b/after/ftplugin/cptest.lua new file mode 100644 index 0000000..89b3317 --- /dev/null +++ b/after/ftplugin/cptest.lua @@ -0,0 +1,7 @@ +vim.opt_local.number = false +vim.opt_local.relativenumber = false +vim.opt_local.statuscolumn = "" +vim.opt_local.signcolumn = "no" +vim.opt_local.foldcolumn = "0" +vim.opt_local.wrap = true +vim.opt_local.linebreak = true \ No newline at end of file diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 08a6c1a..5928ecf 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -27,6 +27,7 @@ local state = { saved_session = nil, test_cases = nil, test_states = {}, + test_panel_active = false, } local constants = require("cp.constants") @@ -193,6 +194,53 @@ local function debug_problem() end) end +local function toggle_test_panel() + if state.test_panel_active then + if state.saved_session then + vim.cmd(("source %s"):format(state.saved_session)) + vim.fn.delete(state.saved_session) + state.saved_session = nil + end + state.test_panel_active = false + logger.log("test panel closed") + return + end + + local problem_id = get_current_problem() + if not problem_id then + return + end + + state.saved_session = vim.fn.tempname() + vim.cmd(("mksession! %s"):format(state.saved_session)) + + vim.cmd("silent only") + + local test_buf = vim.api.nvim_create_buf(false, true) + vim.api.nvim_set_current_buf(test_buf) + vim.bo.filetype = "cptest" + vim.bo.bufhidden = "wipe" + + local test_lines = { + " 1 ✓ PASS 12ms", + " 2 ✗ FAIL 45ms", + "> 3 ✓ PASS 8ms", + " 4 ? PENDING", + "", + "── Test 3 ──", + "Input: │ Expected: │ Actual:", + "5 3 │ 8 │ 8", + "", + "j/k: navigate : toggle : run q: quit", + } + + vim.api.nvim_buf_set_lines(test_buf, 0, -1, false, test_lines) + vim.bo.modifiable = false + + state.test_panel_active = true + logger.log("test panel opened") +end + ---@param delta number 1 for next, -1 for prev ---@param language? string local function navigate_problem(delta, language) @@ -341,6 +389,8 @@ function M.handle_command(opts) run_problem() elseif cmd.action == "debug" then debug_problem() + elseif cmd.action == "test" then + toggle_test_panel() elseif cmd.action == "next" then navigate_problem(1, cmd.language) elseif cmd.action == "prev" then diff --git a/lua/cp/window.lua b/lua/cp/window.lua index 1f6aa42..df549a0 100644 --- a/lua/cp/window.lua +++ b/lua/cp/window.lua @@ -12,14 +12,6 @@ local M = {} 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" }) -end - ---@return WindowState function M.save_layout() local windows = {} @@ -136,12 +128,10 @@ local function default_tile(source_buf, input_buf, output_buf) vim.cmd.vsplit() vim.api.nvim_set_current_buf(output_buf) vim.bo.filetype = "cp" - M.clearcol() 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" - M.clearcol() vim.cmd.wincmd("h") end From c99cf8d4f09ac5c0621acf569c42031eea174383 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:31:26 -0400 Subject: [PATCH 07/25] feat: atcoder scraper update for :CP test --- lua/cp/init.lua | 74 +++++++++++++++++++++++++++++++++++++-------- lua/cp/scrape.lua | 8 ++++- lua/cp/test.lua | 23 ++++++++++++-- plugin/cp.lua | 2 +- scrapers/atcoder.py | 26 ++++++++-------- 5 files changed, 104 insertions(+), 29 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 5928ecf..0a820b7 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -206,11 +206,24 @@ local function toggle_test_panel() return end + if state.platform == "codeforces" then + logger.log("test panel not yet supported for codeforces", vim.log.levels.ERROR) + return + end + local problem_id = get_current_problem() if not problem_id then return end + local ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) + local test_module = require("cp.test") + + if not test_module.load_test_cases(ctx, state) then + logger.log("no test cases found", vim.log.levels.WARN) + return + end + state.saved_session = vim.fn.tempname() vim.cmd(("mksession! %s"):format(state.saved_session)) @@ -221,24 +234,59 @@ local function toggle_test_panel() vim.bo.filetype = "cptest" vim.bo.bufhidden = "wipe" - local test_lines = { - " 1 ✓ PASS 12ms", - " 2 ✗ FAIL 45ms", - "> 3 ✓ PASS 8ms", - " 4 ? PENDING", - "", - "── Test 3 ──", - "Input: │ Expected: │ Actual:", - "5 3 │ 8 │ 8", - "", - "j/k: navigate : toggle : run q: quit", - } + local test_state = test_module.get_test_panel_state() + local test_lines = {} + + for i, test_case in ipairs(test_state.test_cases) do + local status_icon = "?" + local status_text = "PENDING" + + if test_case.status == "pass" then + status_icon = "✓" + status_text = "PASS" + elseif test_case.status == "fail" then + status_icon = "✗" + status_text = "FAIL" + end + + local time_text = test_case.time_ms and string.format("%.0fms", test_case.time_ms) or "" + local prefix = i == test_state.current_index and "> " or " " + + table.insert(test_lines, string.format("%s%d %s %s %s", + prefix, i, status_icon, status_text, time_text)) + end + + table.insert(test_lines, "") + + local current_test = test_state.test_cases[test_state.current_index] + if current_test then + table.insert(test_lines, string.format("── Test %d ──", test_state.current_index)) + table.insert(test_lines, "Input:") + for line in current_test.input:gmatch("[^\n]*") do + table.insert(test_lines, " " .. line) + end + + table.insert(test_lines, "Expected:") + for line in current_test.expected:gmatch("[^\n]*") do + table.insert(test_lines, " " .. line) + end + + if current_test.actual then + table.insert(test_lines, "Actual:") + for line in current_test.actual:gmatch("[^\n]*") do + table.insert(test_lines, " " .. line) + end + end + end + + table.insert(test_lines, "") + table.insert(test_lines, "j/k: navigate : toggle : run q: quit") vim.api.nvim_buf_set_lines(test_buf, 0, -1, false, test_lines) vim.bo.modifiable = false state.test_panel_active = true - logger.log("test panel opened") + logger.log(string.format("test panel opened (%d test cases)", #test_state.test_cases)) end ---@param delta number 1 for next, -1 for prev diff --git a/lua/cp/scrape.lua b/lua/cp/scrape.lua index b76b3af..291a64d 100644 --- a/lua/cp/scrape.lua +++ b/lua/cp/scrape.lua @@ -225,7 +225,13 @@ function M.scrape_problem(ctx) return data end - if data.test_cases and #data.test_cases > 0 then + if data.combined then + local combined_input = data.combined.input:gsub("\r", "") + local combined_output = data.combined.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) + elseif 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", "") diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 96e8d1a..9c77408 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -1,7 +1,24 @@ +---@class TestCase +---@field index number +---@field input string +---@field expected string +---@field status "pending"|"pass"|"fail"|"running" +---@field actual string? +---@field time_ms number? +---@field error string? + +---@class TestPanelState +---@field test_cases TestCase[] +---@field current_index number +---@field buffer number? +---@field namespace number? +---@field is_active boolean +---@field saved_layout table? + local M = {} local logger = require("cp.log") -local execute = require("cp.execute") +---@type TestPanelState local test_panel_state = { test_cases = {}, current_index = 1, @@ -33,8 +50,10 @@ local function parse_test_cases_from_cache(platform, contest_id, problem_id) end 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)) + local index = test_case.index or i + table.insert(test_cases, create_test_case(index, test_case.input, test_case.output)) end return test_cases diff --git a/plugin/cp.lua b/plugin/cp.lua index 0bab4b9..735ff89 100644 --- a/plugin/cp.lua +++ b/plugin/cp.lua @@ -45,10 +45,10 @@ end, { if num_args == 2 then local candidates = { "--lang" } - vim.list_extend(candidates, actions) local cp = require("cp") local context = cp.get_current_context() if context.platform and context.contest_id then + vim.list_extend(candidates, actions) local cache = require("cp.cache") cache.load() local contest_data = cache.get_contest_data(context.platform, context.contest_id) diff --git a/scrapers/atcoder.py b/scrapers/atcoder.py index 63bd3db..70bd184 100644 --- a/scrapers/atcoder.py +++ b/scrapers/atcoder.py @@ -169,24 +169,26 @@ def main() -> None: print(json.dumps(result)) sys.exit(1) - test_cases: list[dict[str, str]] = [] - for input_data, output_data in tests: - test_cases.append({"input": input_data, "output": output_data}) + individual_test_cases: list[dict[str, str]] = [] + for index, (input_data, output_data) in enumerate(tests, 1): + individual_test_cases.append({ + "index": index, + "input": input_data, + "output": output_data + }) - if test_cases: - combined_input: str = ( - str(len(test_cases)) - + "\n" - + "\n".join(tc["input"] for tc in test_cases) - ) - combined_output: str = "\n".join(tc["output"] for tc in test_cases) - test_cases = [{"input": combined_input, "output": combined_output}] + combined_input = "\n".join(tc["input"] for tc in individual_test_cases) + combined_output = "\n".join(tc["output"] for tc in individual_test_cases) result = { "success": True, "problem_id": problem_id, "url": url, - "test_cases": test_cases, + "test_cases": individual_test_cases, + "combined": { + "input": combined_input, + "output": combined_output + } } print(json.dumps(result)) From b128956c045a69ce7aae67cbab51ae988dd88912 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:32:23 -0400 Subject: [PATCH 08/25] fix(ci): format --- after/ftplugin/cptest.lua | 2 +- lua/cp/init.lua | 3 +-- scrapers/atcoder.py | 13 ++++--------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/after/ftplugin/cptest.lua b/after/ftplugin/cptest.lua index 89b3317..166db14 100644 --- a/after/ftplugin/cptest.lua +++ b/after/ftplugin/cptest.lua @@ -4,4 +4,4 @@ vim.opt_local.statuscolumn = "" vim.opt_local.signcolumn = "no" vim.opt_local.foldcolumn = "0" vim.opt_local.wrap = true -vim.opt_local.linebreak = true \ No newline at end of file +vim.opt_local.linebreak = true diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 0a820b7..5599a6a 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -252,8 +252,7 @@ local function toggle_test_panel() local time_text = test_case.time_ms and string.format("%.0fms", test_case.time_ms) or "" local prefix = i == test_state.current_index and "> " or " " - table.insert(test_lines, string.format("%s%d %s %s %s", - prefix, i, status_icon, status_text, time_text)) + table.insert(test_lines, string.format("%s%d %s %s %s", prefix, i, status_icon, status_text, time_text)) end table.insert(test_lines, "") diff --git a/scrapers/atcoder.py b/scrapers/atcoder.py index 70bd184..46d673d 100644 --- a/scrapers/atcoder.py +++ b/scrapers/atcoder.py @@ -171,11 +171,9 @@ def main() -> None: individual_test_cases: list[dict[str, str]] = [] for index, (input_data, output_data) in enumerate(tests, 1): - individual_test_cases.append({ - "index": index, - "input": input_data, - "output": output_data - }) + individual_test_cases.append( + {"index": index, "input": input_data, "output": output_data} + ) combined_input = "\n".join(tc["input"] for tc in individual_test_cases) combined_output = "\n".join(tc["output"] for tc in individual_test_cases) @@ -185,10 +183,7 @@ def main() -> None: "problem_id": problem_id, "url": url, "test_cases": individual_test_cases, - "combined": { - "input": combined_input, - "output": combined_output - } + "combined": {"input": combined_input, "output": combined_output}, } print(json.dumps(result)) From ae83a9cf64e17b7916c584b40c7ce77d3c790664 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:35:27 -0400 Subject: [PATCH 09/25] fix(ci): more luacats annotations --- lua/cp/test.lua | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 9c77408..9933217 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -28,6 +28,10 @@ local test_panel_state = { saved_layout = nil, } +---@param index number +---@param input string +---@param expected string +---@return TestCase local function create_test_case(index, input, expected) return { index = index, @@ -40,6 +44,10 @@ local function create_test_case(index, input, expected) } end +---@param platform string +---@param contest_id string +---@param problem_id string? +---@return TestCase[] local function parse_test_cases_from_cache(platform, contest_id, problem_id) local cache = require("cp.cache") cache.load() @@ -59,6 +67,9 @@ local function parse_test_cases_from_cache(platform, contest_id, problem_id) return test_cases end +---@param input_file string +---@param expected_file string +---@return TestCase[] 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 return {} @@ -70,6 +81,10 @@ local function parse_test_cases_from_files(input_file, expected_file) return { create_test_case(1, input_content, expected_content) } end +---@param ctx table +---@param contest_config table +---@param test_case TestCase +---@return table 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") @@ -133,6 +148,9 @@ local function run_single_test_case(ctx, contest_config, test_case) } end +---@param ctx table +---@param state table +---@return boolean function M.load_test_cases(ctx, state) local test_cases = parse_test_cases_from_cache(state.platform, state.contest_id, state.problem_id) @@ -147,6 +165,10 @@ function M.load_test_cases(ctx, state) return #test_cases > 0 end +---@param ctx table +---@param contest_config table +---@param index number +---@return boolean function M.run_test_case(ctx, contest_config, index) local test_case = test_panel_state.test_cases[index] if not test_case then @@ -166,6 +188,9 @@ function M.run_test_case(ctx, contest_config, index) return true end +---@param ctx table +---@param contest_config table +---@return TestCase[] function M.run_all_test_cases(ctx, contest_config) local results = {} for i, _ in ipairs(test_panel_state.test_cases) do @@ -175,6 +200,7 @@ function M.run_all_test_cases(ctx, contest_config) return results end +---@return TestPanelState function M.get_test_panel_state() return test_panel_state end From ffc35ff2b21afcad3971b56efcf9984c4fa1d62f Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:35:35 -0400 Subject: [PATCH 10/25] fix(ci): more luacats annotations --- lua/cp/test.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 9933217..8bbfa53 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -81,8 +81,8 @@ local function parse_test_cases_from_files(input_file, expected_file) return { create_test_case(1, input_content, expected_content) } end ----@param ctx table ----@param contest_config table +---@param ctx ProblemContext +---@param contest_config ContestConfig ---@param test_case TestCase ---@return table local function run_single_test_case(ctx, contest_config, test_case) From 75cdf3fbaa814389d3a1fd6b3159a1f338cf0620 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:35:35 -0400 Subject: [PATCH 11/25] fix(ci): more luacats annotations --- lua/cp/test.lua | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 8bbfa53..7333dda 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -148,7 +148,7 @@ local function run_single_test_case(ctx, contest_config, test_case) } end ----@param ctx table +---@param ctx ProblemContext ---@param state table ---@return boolean function M.load_test_cases(ctx, state) @@ -165,8 +165,8 @@ function M.load_test_cases(ctx, state) return #test_cases > 0 end ----@param ctx table ----@param contest_config table +---@param ctx ProblemContext +---@param contest_config ContestConfig ---@param index number ---@return boolean function M.run_test_case(ctx, contest_config, index) From dabf7aa660cfeadb2dc5ff231db6abfeaca846f4 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:36:03 -0400 Subject: [PATCH 12/25] more luacats --- lua/cp/test.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 7333dda..5bc546a 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -188,8 +188,8 @@ function M.run_test_case(ctx, contest_config, index) return true end ----@param ctx table ----@param contest_config table +---@param ctx ProblemContext +---@param contest_config ContestConfig ---@return TestCase[] function M.run_all_test_cases(ctx, contest_config) local results = {} From e98ced5fdad21ce03f3a64d809370a6f0ba708ed Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:36:57 -0400 Subject: [PATCH 13/25] fix(ci): correct typing --- lua/cp/cache.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/cp/cache.lua b/lua/cp/cache.lua index 516ddb3..ebf506f 100644 --- a/lua/cp/cache.lua +++ b/lua/cp/cache.lua @@ -5,14 +5,14 @@ ---@field problems Problem[] ---@field scraped_at string ---@field expires_at? number ----@field test_cases? TestCase[] +---@field test_cases? CachedTestCase[] ---@field test_cases_cached_at? number ---@class Problem ---@field id string ---@field name? string ----@class TestCase +---@class CachedTestCase ---@field input string ---@field output string From f53f4bcbe73a98ffbd24e252831a94056803e635 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:37:31 -0400 Subject: [PATCH 14/25] fix(ci): correct typing --- lua/cp/cache.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/cp/cache.lua b/lua/cp/cache.lua index ebf506f..f1f2f8f 100644 --- a/lua/cp/cache.lua +++ b/lua/cp/cache.lua @@ -146,7 +146,7 @@ end ---@param platform string ---@param contest_id string ---@param problem_id? string ----@return TestCase[]? +---@return CachedTestCase[]? function M.get_test_cases(platform, contest_id, problem_id) vim.validate({ platform = { platform, "string" }, @@ -164,7 +164,7 @@ end ---@param platform string ---@param contest_id string ---@param problem_id? string ----@param test_cases TestCase[] +---@param test_cases CachedTestCase[] function M.set_test_cases(platform, contest_id, problem_id, test_cases) vim.validate({ platform = { platform, "string" }, From c16f6576e2f3d11f6bdfddcc985229b27ae0ec37 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:50:17 -0400 Subject: [PATCH 15/25] fix: misc fixes to snippets and the state managemnt --- doc/cp.txt | 2 +- lua/cp/config.lua | 2 +- lua/cp/init.lua | 45 +++++++++++++++++++++++++++++++++++---------- 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/doc/cp.txt b/doc/cp.txt index 8d8fbb8..e28d6b7 100644 --- a/doc/cp.txt +++ b/doc/cp.txt @@ -134,7 +134,7 @@ Optional configuration with lazy.nvim: > • {filename}? (`function`) Custom filename generation function. `function(contest, contest_id, problem_id, config, language)` Should return full filename with extension. - (default: uses problem_id or contest_id) + (default: concats contest_id and problem id) *cp.ContestConfig* diff --git a/lua/cp/config.lua b/lua/cp/config.lua index 6856db1..f9e8abe 100644 --- a/lua/cp/config.lua +++ b/lua/cp/config.lua @@ -137,7 +137,7 @@ local function default_filename(contest_id, problem_id) }) if problem_id then - return problem_id:lower() + return (contest_id .. problem_id):lower() else return contest_id:lower() end diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 5599a6a..2b96418 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -99,7 +99,11 @@ local function setup_problem(contest_id, problem_id, language) 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 constants = require("cp.constants") + local filetype = vim.api.nvim_get_option_value("filetype", { buf = 0 }) + local language_name = constants.filetype_to_language[filetype] + local canonical_language = constants.canonical_filetypes[language_name] or language_name + local prefixed_trigger = ("cp.nvim/%s.%s"):format(state.platform, canonical_language) vim.api.nvim_buf_set_lines(0, 0, -1, false, { prefixed_trigger }) vim.api.nvim_win_set_cursor(0, { 1, #prefixed_trigger }) @@ -234,6 +238,30 @@ local function toggle_test_panel() vim.bo.filetype = "cptest" vim.bo.bufhidden = "wipe" + local function navigate_test(delta) + local test_state = test_module.get_test_panel_state() + local new_index = test_state.current_index + delta + if new_index >= 1 and new_index <= #test_state.test_cases then + test_state.current_index = new_index + toggle_test_panel() + toggle_test_panel() + end + end + + local function run_current_test() + local ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) + local contest_config = config.contests[state.platform] + local test_state = test_module.get_test_panel_state() + test_module.run_test_case(ctx, contest_config, test_state.current_index) + toggle_test_panel() + toggle_test_panel() + end + + vim.keymap.set("n", "j", function() navigate_test(1) end, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "k", function() navigate_test(-1) end, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "", run_current_test, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "q", function() toggle_test_panel() end, { buffer = test_buf, silent = true }) + local test_state = test_module.get_test_panel_state() local test_lines = {} @@ -261,26 +289,23 @@ local function toggle_test_panel() if current_test then table.insert(test_lines, string.format("── Test %d ──", test_state.current_index)) table.insert(test_lines, "Input:") - for line in current_test.input:gmatch("[^\n]*") do - table.insert(test_lines, " " .. line) + for _, line in ipairs(vim.split(current_test.input, "\n", { plain = true, trimempty = true })) do + table.insert(test_lines, line) end table.insert(test_lines, "Expected:") - for line in current_test.expected:gmatch("[^\n]*") do - table.insert(test_lines, " " .. line) + for _, line in ipairs(vim.split(current_test.expected, "\n", { plain = true, trimempty = true })) do + table.insert(test_lines, line) end if current_test.actual then table.insert(test_lines, "Actual:") - for line in current_test.actual:gmatch("[^\n]*") do - table.insert(test_lines, " " .. line) + for _, line in ipairs(vim.split(current_test.actual, "\n", { plain = true, trimempty = true })) do + table.insert(test_lines, line) end end end - table.insert(test_lines, "") - table.insert(test_lines, "j/k: navigate : toggle : run q: quit") - vim.api.nvim_buf_set_lines(test_buf, 0, -1, false, test_lines) vim.bo.modifiable = false From 13d6a9f25143f0012bc16359b431279668f24dd3 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:50:18 -0400 Subject: [PATCH 16/25] fix: misc fixes to snippets and the state managemnt --- lua/cp/init.lua | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 2b96418..34524a8 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -95,12 +95,13 @@ local function setup_problem(contest_id, problem_id, language) end vim.cmd.e(scrape_ctx.source_file) + local source_buf = vim.api.nvim_get_current_buf() - if vim.api.nvim_buf_get_lines(0, 0, -1, true)[1] == "" then + if vim.api.nvim_buf_get_lines(source_buf, 0, -1, true)[1] == "" then local has_luasnip, luasnip = pcall(require, "luasnip") if has_luasnip then local constants = require("cp.constants") - local filetype = vim.api.nvim_get_option_value("filetype", { buf = 0 }) + local filetype = vim.api.nvim_get_option_value("filetype", { buf = source_buf }) local language_name = constants.filetype_to_language[filetype] local canonical_language = constants.canonical_filetypes[language_name] or language_name local prefixed_trigger = ("cp.nvim/%s.%s"):format(state.platform, canonical_language) From 39839ac40d9a56df8d7ad37a82686605b14abf44 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 18:51:04 -0400 Subject: [PATCH 17/25] fix(ci): format --- lua/cp/init.lua | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 34524a8..6ebc35f 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -258,10 +258,16 @@ local function toggle_test_panel() toggle_test_panel() end - vim.keymap.set("n", "j", function() navigate_test(1) end, { buffer = test_buf, silent = true }) - vim.keymap.set("n", "k", function() navigate_test(-1) end, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "j", function() + navigate_test(1) + end, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "k", function() + navigate_test(-1) + end, { buffer = test_buf, silent = true }) vim.keymap.set("n", "", run_current_test, { buffer = test_buf, silent = true }) - vim.keymap.set("n", "q", function() toggle_test_panel() end, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "q", function() + toggle_test_panel() + end, { buffer = test_buf, silent = true }) local test_state = test_module.get_test_panel_state() local test_lines = {} From c0f6727331050da65707721ccdcf834c3094e004 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 20:09:42 -0400 Subject: [PATCH 18/25] fix(ci): some warnings --- lua/cp/cache.lua | 1 + lua/cp/init.lua | 9 ++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lua/cp/cache.lua b/lua/cp/cache.lua index f1f2f8f..a379415 100644 --- a/lua/cp/cache.lua +++ b/lua/cp/cache.lua @@ -13,6 +13,7 @@ ---@field name? string ---@class CachedTestCase +---@field index? number ---@field input string ---@field output string diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 6ebc35f..456a2ff 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -100,7 +100,6 @@ local function setup_problem(contest_id, problem_id, language) if vim.api.nvim_buf_get_lines(source_buf, 0, -1, true)[1] == "" then local has_luasnip, luasnip = pcall(require, "luasnip") if has_luasnip then - local constants = require("cp.constants") local filetype = vim.api.nvim_get_option_value("filetype", { buf = source_buf }) local language_name = constants.filetype_to_language[filetype] local canonical_language = constants.canonical_filetypes[language_name] or language_name @@ -130,12 +129,12 @@ local function setup_problem(contest_id, problem_id, language) config.hooks.setup_code(ctx) end - local source_buf = vim.api.nvim_get_current_buf() + local src_buf = vim.api.nvim_get_current_buf() local input_buf = vim.fn.bufnr(ctx.input_file, true) local output_buf = vim.fn.bufnr(ctx.output_file, true) local tile_fn = config.tile or window.default_tile - tile_fn(source_buf, input_buf, output_buf) + tile_fn(src_buf, input_buf, output_buf) logger.log(("switched to problem %s"):format(ctx.problem_name)) end @@ -250,10 +249,10 @@ local function toggle_test_panel() end local function run_current_test() - local ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) + local test_ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) local contest_config = config.contests[state.platform] local test_state = test_module.get_test_panel_state() - test_module.run_test_case(ctx, contest_config, test_state.current_index) + test_module.run_test_case(test_ctx, contest_config, test_state.current_index) toggle_test_panel() toggle_test_panel() end From 7ad3eef3b716db92980a6f61a6ea4994206fb992 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 20:10:49 -0400 Subject: [PATCH 19/25] fix: rename var --- lua/cp/init.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 456a2ff..c72ad4c 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -249,10 +249,10 @@ local function toggle_test_panel() end local function run_current_test() - local test_ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) + local problem_ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) local contest_config = config.contests[state.platform] local test_state = test_module.get_test_panel_state() - test_module.run_test_case(test_ctx, contest_config, test_state.current_index) + test_module.run_test_case(problem_ctx, contest_config, test_state.current_index) toggle_test_panel() toggle_test_panel() end From d5b3c9a881ba00d3e4a5588bb3d28e04d92b0d38 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 22:39:44 -0400 Subject: [PATCH 20/25] feat: basic test mode runner --- lua/cp/execute.lua | 40 +++++++++++-- lua/cp/init.lua | 137 +++++++++++++++++++++++++++------------------ lua/cp/scrape.lua | 60 +++++++++++++++++--- lua/cp/test.lua | 57 +++++++++++++++++-- readme.md | 2 - 5 files changed, 223 insertions(+), 73 deletions(-) diff --git a/lua/cp/execute.lua b/lua/cp/execute.lua index 1b52a71..d341489 100644 --- a/lua/cp/execute.lua +++ b/lua/cp/execute.lua @@ -89,7 +89,7 @@ end ---@param language_config table ---@param substitutions table ---@return {code: integer, stderr: string} -local function compile_generic(language_config, substitutions) +function M.compile_generic(language_config, substitutions) vim.validate({ language_config = { language_config, "table" }, substitutions = { substitutions, "table" }, @@ -210,8 +210,40 @@ local function format_output(exec_result, expected_file, is_debug) end ---@param ctx ProblemContext ----@param contest_config table ----@param is_debug boolean +---@param contest_config ContestConfig +---@return boolean success +function M.compile_problem(ctx, contest_config) + vim.validate({ + ctx = { ctx, "table" }, + contest_config = { contest_config, "table" }, + }) + + local language = get_language_from_file(ctx.source_file, contest_config) + local language_config = contest_config[language] + + if not language_config then + logger.log("No configuration for language: " .. language, vim.log.levels.ERROR) + return false + end + + local substitutions = { + source = ctx.source_file, + binary = ctx.binary_file, + version = tostring(language_config.version), + } + + if language_config.compile then + local compile_result = M.compile_generic(language_config, substitutions) + if compile_result.code ~= 0 then + logger.log("compilation failed: " .. (compile_result.stderr or "unknown error"), vim.log.levels.ERROR) + return false + end + logger.log("compilation successful") + end + + return true +end + function M.run_problem(ctx, contest_config, is_debug) vim.validate({ ctx = { ctx, "table" }, @@ -237,7 +269,7 @@ function M.run_problem(ctx, contest_config, is_debug) 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) + local compile_result = M.compile_generic(language_config, substitutions) if compile_result.code ~= 0 then vim.fn.writefile({ compile_result.stderr }, ctx.output_file) return diff --git a/lua/cp/init.lua b/lua/cp/init.lua index c72ad4c..eb78916 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -228,6 +228,12 @@ local function toggle_test_panel() return end + local execute = require("cp.execute") + local contest_config = config.contests[state.platform] + if not execute.compile_problem(ctx, contest_config) then + return + end + state.saved_session = vim.fn.tempname() vim.cmd(("mksession! %s"):format(state.saved_session)) @@ -239,8 +245,10 @@ local function toggle_test_panel() vim.bo.bufhidden = "wipe" local function navigate_test(delta) + logger.log(("navigating test by %d"):format(delta)) local test_state = test_module.get_test_panel_state() local new_index = test_state.current_index + delta + logger.log(("current: %d, new: %d, total: %d"):format(test_state.current_index, new_index, #test_state.test_cases)) if new_index >= 1 and new_index <= #test_state.test_cases then test_state.current_index = new_index toggle_test_panel() @@ -248,74 +256,97 @@ local function toggle_test_panel() end end - local function run_current_test() + local function refresh_test_panel() + if not test_buf or not vim.api.nvim_buf_is_valid(test_buf) then + return + end + + local test_state = test_module.get_test_panel_state() + local test_lines = {} + + for i, test_case in ipairs(test_state.test_cases) do + local status_text = string.upper(test_case.status) + if test_case.status == "timeout" then + status_text = "TIMEOUT" + end + local prefix = i == test_state.current_index and "> " or " " + local line = string.format("%s%d %s", prefix, i, status_text) + table.insert(test_lines, line) + end + + if test_state.test_cases[test_state.current_index] then + local current_test = test_state.test_cases[test_state.current_index] + table.insert(test_lines, "") + table.insert(test_lines, string.format("── Test %d ──", test_state.current_index)) + + table.insert(test_lines, "Input:") + for _, line in ipairs(vim.split(current_test.input, "\n", { plain = true, trimempty = true })) do + table.insert(test_lines, line) + end + + table.insert(test_lines, "Expected:") + for _, line in ipairs(vim.split(current_test.expected, "\n", { plain = true, trimempty = true })) do + table.insert(test_lines, line) + end + + if current_test.actual then + table.insert(test_lines, "Actual:") + for _, line in ipairs(vim.split(current_test.actual, "\n", { plain = true, trimempty = true })) do + table.insert(test_lines, line) + end + end + end + + table.insert(test_lines, "") + table.insert(test_lines, "[j/k] Navigate [Enter] Run all tests [q] Close") + + vim.api.nvim_buf_set_lines(test_buf, 0, -1, false, test_lines) + end + + local function navigate_test_case(delta) + local test_state = test_module.get_test_panel_state() + if #test_state.test_cases == 0 then + return + end + + test_state.current_index = test_state.current_index + delta + if test_state.current_index < 1 then + test_state.current_index = #test_state.test_cases + elseif test_state.current_index > #test_state.test_cases then + test_state.current_index = 1 + end + + refresh_test_panel() + end + + local function run_all_tests() local problem_ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) local contest_config = config.contests[state.platform] local test_state = test_module.get_test_panel_state() - test_module.run_test_case(problem_ctx, contest_config, test_state.current_index) - toggle_test_panel() - toggle_test_panel() + + if test_state.test_cases and #test_state.test_cases > 0 then + test_module.run_all_test_cases(problem_ctx, contest_config) + refresh_test_panel() + end end vim.keymap.set("n", "j", function() - navigate_test(1) + navigate_test_case(1) end, { buffer = test_buf, silent = true }) vim.keymap.set("n", "k", function() - navigate_test(-1) + navigate_test_case(-1) + end, { buffer = test_buf, silent = true }) + vim.keymap.set("n", "", function() + run_all_tests() end, { buffer = test_buf, silent = true }) - vim.keymap.set("n", "", run_current_test, { buffer = test_buf, silent = true }) vim.keymap.set("n", "q", function() toggle_test_panel() end, { buffer = test_buf, silent = true }) - local test_state = test_module.get_test_panel_state() - local test_lines = {} - - for i, test_case in ipairs(test_state.test_cases) do - local status_icon = "?" - local status_text = "PENDING" - - if test_case.status == "pass" then - status_icon = "✓" - status_text = "PASS" - elseif test_case.status == "fail" then - status_icon = "✗" - status_text = "FAIL" - end - - local time_text = test_case.time_ms and string.format("%.0fms", test_case.time_ms) or "" - local prefix = i == test_state.current_index and "> " or " " - - table.insert(test_lines, string.format("%s%d %s %s %s", prefix, i, status_icon, status_text, time_text)) - end - - table.insert(test_lines, "") - - local current_test = test_state.test_cases[test_state.current_index] - if current_test then - table.insert(test_lines, string.format("── Test %d ──", test_state.current_index)) - table.insert(test_lines, "Input:") - for _, line in ipairs(vim.split(current_test.input, "\n", { plain = true, trimempty = true })) do - table.insert(test_lines, line) - end - - table.insert(test_lines, "Expected:") - for _, line in ipairs(vim.split(current_test.expected, "\n", { plain = true, trimempty = true })) do - table.insert(test_lines, line) - end - - if current_test.actual then - table.insert(test_lines, "Actual:") - for _, line in ipairs(vim.split(current_test.actual, "\n", { plain = true, trimempty = true })) do - table.insert(test_lines, line) - end - end - end - - vim.api.nvim_buf_set_lines(test_buf, 0, -1, false, test_lines) - vim.bo.modifiable = false + refresh_test_panel() state.test_panel_active = true + local test_state = test_module.get_test_panel_state() logger.log(string.format("test panel opened (%d test cases)", #test_state.test_cases)) end diff --git a/lua/cp/scrape.lua b/lua/cp/scrape.lua index 291a64d..9352a69 100644 --- a/lua/cp/scrape.lua +++ b/lua/cp/scrape.lua @@ -148,10 +148,34 @@ function M.scrape_problem(ctx) ensure_io_directory() if vim.fn.filereadable(ctx.input_file) == 1 and vim.fn.filereadable(ctx.expected_file) == 1 then + local base_name = vim.fn.fnamemodify(ctx.input_file, ":r") + local test_cases = {} + local i = 1 + + while true do + local input_file = base_name .. "." .. i .. ".cpin" + local expected_file = base_name .. "." .. i .. ".cpout" + + if vim.fn.filereadable(input_file) == 1 and vim.fn.filereadable(expected_file) == 1 then + local input_content = table.concat(vim.fn.readfile(input_file), "\n") + local expected_content = table.concat(vim.fn.readfile(expected_file), "\n") + + table.insert(test_cases, { + index = i, + input = input_content, + output = expected_content + }) + i = i + 1 + else + break + end + end + return { success = true, problem_id = ctx.problem_name, - test_count = 1, + test_count = #test_cases, + test_cases = test_cases, } end @@ -204,6 +228,7 @@ function M.scrape_problem(ctx) timeout = 30000, }):wait() + if result.code ~= 0 then return { success = false, @@ -221,24 +246,41 @@ function M.scrape_problem(ctx) } end + if not data.success then return data end - if data.combined then - local combined_input = data.combined.input:gsub("\r", "") - local combined_output = data.combined.output:gsub("\r", "") + if data.test_cases and #data.test_cases > 0 then + local base_name = vim.fn.fnamemodify(ctx.input_file, ":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) - elseif 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", "") + for i, test_case in ipairs(data.test_cases) do + local input_file = base_name .. "." .. i .. ".cpin" + local expected_file = base_name .. "." .. i .. ".cpout" + + local input_content = test_case.input:gsub("\r", "") + local expected_content = test_case.output:gsub("\r", "") + + if ctx.contest == "atcoder" then + input_content = "1\n" .. input_content + end + + vim.fn.writefile(vim.split(input_content, "\n", true), input_file) + vim.fn.writefile(vim.split(expected_content, "\n", true), expected_file) + end + + local combined_input = data.combined and data.combined.input:gsub("\r", "") or table.concat(vim.tbl_map(function(tc) return tc.input end, data.test_cases), "\n") + local combined_output = data.combined and data.combined.output:gsub("\r", "") or table.concat(vim.tbl_map(function(tc) return tc.output end, data.test_cases), "\n") + + if ctx.contest == "atcoder" then + combined_input = tostring(#data.test_cases) .. "\n" .. combined_input + end 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 { success = true, problem_id = ctx.problem_name, diff --git a/lua/cp/test.lua b/lua/cp/test.lua index 5bc546a..8468717 100644 --- a/lua/cp/test.lua +++ b/lua/cp/test.lua @@ -2,10 +2,11 @@ ---@field index number ---@field input string ---@field expected string ----@field status "pending"|"pass"|"fail"|"running" +---@field status "pending"|"pass"|"fail"|"running"|"timeout" ---@field actual string? ---@field time_ms number? ---@field error string? +---@field selected boolean ---@class TestPanelState ---@field test_cases TestCase[] @@ -41,6 +42,7 @@ local function create_test_case(index, input, expected) actual = nil, time_ms = nil, error = nil, + selected = true, } end @@ -75,10 +77,32 @@ local function parse_test_cases_from_files(input_file, expected_file) 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 base_name = vim.fn.fnamemodify(input_file, ":r") + local test_cases = {} + local i = 1 - return { create_test_case(1, input_content, expected_content) } + while true do + local individual_input_file = base_name .. "." .. i .. ".cpin" + local individual_expected_file = base_name .. "." .. i .. ".cpout" + + if vim.fn.filereadable(individual_input_file) == 1 and vim.fn.filereadable(individual_expected_file) == 1 then + local input_content = table.concat(vim.fn.readfile(individual_input_file), "\n") + local expected_content = table.concat(vim.fn.readfile(individual_expected_file), "\n") + + table.insert(test_cases, create_test_case(i, input_content, expected_content)) + i = i + 1 + else + break + end + end + + if #test_cases == 0 then + 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 + + return test_cases end ---@param ctx ProblemContext @@ -126,6 +150,20 @@ local function run_single_test_case(ctx, contest_config, test_case) version = tostring(language_config.version or ""), } + if language_config.compile and vim.fn.filereadable(ctx.binary_file) == 0 then + logger.log("binary not found, compiling first...") + local compile_cmd = substitute_template(language_config.compile, substitutions) + local compile_result = vim.system(compile_cmd, { text = true }):wait() + if compile_result.code ~= 0 then + return { + status = "fail", + actual = "", + error = "Compilation failed: " .. (compile_result.stderr or "Unknown error"), + time_ms = 0, + } + end + end + local run_cmd = build_command(language_config.run, language_config.executable, substitutions) local start_time = vim.uv.hrtime() @@ -140,8 +178,17 @@ local function run_single_test_case(ctx, contest_config, test_case) local expected_output = test_case.expected:gsub("\n$", "") local matches = actual_output == expected_output + local status + if result.code == 143 or result.code == 124 then + status = "timeout" + elseif result.code == 0 and matches then + status = "pass" + else + status = "fail" + end + return { - status = result.code == 0 and matches and "pass" or "fail", + status = status, actual = actual_output, error = result.code ~= 0 and result.stderr or nil, time_ms = execution_time, diff --git a/readme.md b/readme.md index 6c17b50..121fd4b 100644 --- a/readme.md +++ b/readme.md @@ -71,5 +71,3 @@ follows: - test case management - new video with functionality, notify discord members - note that codeforces support is scuffed: https://codeforces.com/blog/entry/146423 -- codeforces: use round number & api not the contest id - - problems: api config From 0951944e8c9739071b72efcbc096174cb54a0cfd Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 22:40:16 -0400 Subject: [PATCH 21/25] feat: format --- lua/cp/init.lua | 4 +++- lua/cp/scrape.lua | 21 +++++++++++++++------ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index eb78916..48315e7 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -248,7 +248,9 @@ local function toggle_test_panel() logger.log(("navigating test by %d"):format(delta)) local test_state = test_module.get_test_panel_state() local new_index = test_state.current_index + delta - logger.log(("current: %d, new: %d, total: %d"):format(test_state.current_index, new_index, #test_state.test_cases)) + logger.log( + ("current: %d, new: %d, total: %d"):format(test_state.current_index, new_index, #test_state.test_cases) + ) if new_index >= 1 and new_index <= #test_state.test_cases then test_state.current_index = new_index toggle_test_panel() diff --git a/lua/cp/scrape.lua b/lua/cp/scrape.lua index 9352a69..5fc6059 100644 --- a/lua/cp/scrape.lua +++ b/lua/cp/scrape.lua @@ -163,7 +163,7 @@ function M.scrape_problem(ctx) table.insert(test_cases, { index = i, input = input_content, - output = expected_content + output = expected_content, }) i = i + 1 else @@ -228,7 +228,6 @@ function M.scrape_problem(ctx) timeout = 30000, }):wait() - if result.code ~= 0 then return { success = false, @@ -246,7 +245,6 @@ function M.scrape_problem(ctx) } end - if not data.success then return data end @@ -269,8 +267,20 @@ function M.scrape_problem(ctx) vim.fn.writefile(vim.split(expected_content, "\n", true), expected_file) end - local combined_input = data.combined and data.combined.input:gsub("\r", "") or table.concat(vim.tbl_map(function(tc) return tc.input end, data.test_cases), "\n") - local combined_output = data.combined and data.combined.output:gsub("\r", "") or table.concat(vim.tbl_map(function(tc) return tc.output end, data.test_cases), "\n") + local combined_input = data.combined and data.combined.input:gsub("\r", "") + or table.concat( + vim.tbl_map(function(tc) + return tc.input + end, data.test_cases), + "\n" + ) + local combined_output = data.combined and data.combined.output:gsub("\r", "") + or table.concat( + vim.tbl_map(function(tc) + return tc.output + end, data.test_cases), + "\n" + ) if ctx.contest == "atcoder" then combined_input = tostring(#data.test_cases) .. "\n" .. combined_input @@ -280,7 +290,6 @@ function M.scrape_problem(ctx) vim.fn.writefile(vim.split(combined_output, "\n", true), ctx.expected_file) end - return { success = true, problem_id = ctx.problem_name, From 0efe3764cab602d972b133e89a905be6f55bc3c6 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 22:43:27 -0400 Subject: [PATCH 22/25] fix(ci): remove shadowed vars --- lua/cp/init.lua | 2 -- 1 file changed, 2 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 48315e7..9c9a764 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -228,7 +228,6 @@ local function toggle_test_panel() return end - local execute = require("cp.execute") local contest_config = config.contests[state.platform] if not execute.compile_problem(ctx, contest_config) then return @@ -323,7 +322,6 @@ local function toggle_test_panel() local function run_all_tests() local problem_ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) - local contest_config = config.contests[state.platform] local test_state = test_module.get_test_panel_state() if test_state.test_cases and #test_state.test_cases > 0 then From 403308324cec71dc8e1103d5250096774be5c881 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 22:44:28 -0400 Subject: [PATCH 23/25] fix: remove unused --- lua/cp/init.lua | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 9c9a764..23b0fdb 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -243,20 +243,6 @@ local function toggle_test_panel() vim.bo.filetype = "cptest" vim.bo.bufhidden = "wipe" - local function navigate_test(delta) - logger.log(("navigating test by %d"):format(delta)) - local test_state = test_module.get_test_panel_state() - local new_index = test_state.current_index + delta - logger.log( - ("current: %d, new: %d, total: %d"):format(test_state.current_index, new_index, #test_state.test_cases) - ) - if new_index >= 1 and new_index <= #test_state.test_cases then - test_state.current_index = new_index - toggle_test_panel() - toggle_test_panel() - end - end - local function refresh_test_panel() if not test_buf or not vim.api.nvim_buf_is_valid(test_buf) then return From 340fde40a6446e9fad91a25be124cee0987b2bb9 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 23:01:59 -0400 Subject: [PATCH 24/25] move compilation and cleanup --- lua/cp/init.lua | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 23b0fdb..8458c22 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -228,10 +228,6 @@ local function toggle_test_panel() return end - local contest_config = config.contests[state.platform] - if not execute.compile_problem(ctx, contest_config) then - return - end state.saved_session = vim.fn.tempname() vim.cmd(("mksession! %s"):format(state.saved_session)) @@ -252,10 +248,7 @@ local function toggle_test_panel() local test_lines = {} for i, test_case in ipairs(test_state.test_cases) do - local status_text = string.upper(test_case.status) - if test_case.status == "timeout" then - status_text = "TIMEOUT" - end + local status_text = test_case.status == "pending" and "?" or string.upper(test_case.status) local prefix = i == test_state.current_index and "> " or " " local line = string.format("%s%d %s", prefix, i, status_text) table.insert(test_lines, line) @@ -308,9 +301,13 @@ local function toggle_test_panel() local function run_all_tests() local problem_ctx = problem.create_context(state.platform, state.contest_id, state.problem_id, config) + local contest_config = config.contests[state.platform] local test_state = test_module.get_test_panel_state() if test_state.test_cases and #test_state.test_cases > 0 then + if not execute.compile_problem(problem_ctx, contest_config) then + return + end test_module.run_all_test_cases(problem_ctx, contest_config) refresh_test_panel() end From b2894e9edf3a8b68cd113895dd600dbdb93374f9 Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Mon, 15 Sep 2025 23:02:30 -0400 Subject: [PATCH 25/25] fix(ci): format --- lua/cp/init.lua | 1 - 1 file changed, 1 deletion(-) diff --git a/lua/cp/init.lua b/lua/cp/init.lua index 8458c22..5fc55b2 100644 --- a/lua/cp/init.lua +++ b/lua/cp/init.lua @@ -228,7 +228,6 @@ local function toggle_test_panel() return end - state.saved_session = vim.fn.tempname() vim.cmd(("mksession! %s"):format(state.saved_session))