-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_line_editor.rb
More file actions
114 lines (99 loc) · 2.67 KB
/
command_line_editor.rb
File metadata and controls
114 lines (99 loc) · 2.67 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
module ImportJS
# This is the implementation of command line integration in Import-JS.
class CommandLineEditor
def initialize(lines, opts)
@lines = lines
@messages = []
@ask_for_selections = []
@selections = opts[:selections] unless opts[:selections].empty?
@word = opts[:word]
@path_to_file = opts[:path_to_file]
end
# @return [String]
def current_word
@word
end
# @return [String?]
def path_to_current_file
@path_to_file
end
# @param file_path [String]
def open_file(file_path)
@goto = file_path
end
attr_reader :goto
# @param str [String]
def message(str)
@messages << str
end
attr_reader :ask_for_selections
# @return [String]
def current_file_content
@lines.join("\n")
end
# @return [String]
def messages
@messages.join("\n")
end
# Reads a line from the file.
#
# Lines are one-indexed, so 1 means the first line in the file.
# @return [String]
def read_line(line_number)
@lines[line_number - 1]
end
# Get the cursor position.
#
# @return [Array(Number, Number)]
def cursor
# not relevant for this editor
[0, 0]
end
# Place the cursor at a specified position.
#
# @param _position_tuple [Array(Number, Number)] the row and column to place
# the cursor at.
def cursor=(_position_tuple)
# no-op
end
# Delete a line.
#
# @param line_number [Number] One-indexed line number.
# 1 is the first line in the file.
def delete_line(line_number)
@lines.delete_at(line_number - 1)
end
# Append a line right after the specified line.
#
# Lines are one-indexed, but you need to support appending to line 0 (add
# content at top of file).
# @param line_number [Number]
def append_line(line_number, str)
@lines.insert(line_number, str)
end
# Count the number of lines in the file.
#
# @return [Number] the number of lines in the file
def count_lines
@lines.length
end
# Ask the user to select something from a list of alternatives.
#
# @param word [String] The word/variable to import
# @param alternatives [Array<String>] A list of alternatives
# @return [Number, nil] the index of the selected alternative, or nil if
# nothing was selected.
def ask_for_selection(word, alternatives)
if @selections
# this is a re-run, where selections have already been made
@selections[word]
else
@ask_for_selections << {
word: word,
alternatives: alternatives,
}
nil
end
end
end
end