summaryrefslogtreecommitdiff
path: root/lua/99/test/visual_context_bounds_spec.lua
blob: 5b89ad4f893093443f2abb937a7a103bf3f0a380 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
-- luacheck: globals describe it assert after_each
local prompt_settings = require("99.prompt-settings")
local test_utils = require("99.test.test_utils")
local geo = require("99.geo")

local eq = assert.are.same
local Range = geo.Range
local Point = geo.Point

local function make_lines(count, overrides)
  local out = {}
  for i = 1, count do
    out[i] = overrides[i] or string.format("line %04d", i)
  end
  return out
end

local function range_for_line(buffer, row)
  return Range:new(
    buffer,
    Point:from_1_based(row, 1),
    Point:from_1_based(row, 1)
  )
end

local function prompt_context_lines(range)
  local prompt = prompt_settings.prompts.visual_selection(range)
  local context = prompt:match(
    "<SURROUNDING_CONTEXT>\n(.-)\n</SURROUNDING_CONTEXT>"
  )

  assert.is_not_nil(context)
  if context == "" then
    return {}
  end

  return vim.split(context, "\n", { plain = true })
end

describe("visual context", function()
  after_each(function()
    test_utils.clean_files()
  end)

  it("should handle selections at the top of a file", function()
    local buffer = test_utils.create_file(
      make_lines(1000, {
        [1] = "selected line",
        [101] = "last line in context",
        [901] = "line that should not appear",
        [1000] = "bottom of file",
      }),
      "lua",
      1,
      0
    )

    local context = prompt_context_lines(range_for_line(buffer, 1))

    eq(101, #context)
    eq("selected line", context[1])
    eq("last line in context", context[#context])
    assert.is_false(vim.tbl_contains(context, "line that should not appear"))
  end)

  it("should keep context around middle selections", function()
    local buffer = test_utils.create_file(
      make_lines(1000, {
        [400] = "first line in context",
        [500] = "selected line",
        [600] = "last line in context",
      }),
      "lua",
      500,
      0
    )

    local context = prompt_context_lines(range_for_line(buffer, 500))

    eq(201, #context)
    eq("first line in context", context[1])
    eq("selected line", context[101])
    eq("last line in context", context[#context])
  end)

  it("should keep small files whole", function()
    local content = {
      "first available line",
      "selected middle line",
      "last available line",
    }
    local buffer = test_utils.create_file(content, "lua", 2, 0)

    local context = prompt_context_lines(range_for_line(buffer, 2))

    eq(content, context)
  end)
end)