Class: Canopus::Editor

Inherits:
Object
  • Object
show all
Includes:
SnippetExpandable
Defined in:
lib/canopus/editor.rb,
sig/canopus.rbs,
sig/snippet.rbs,
sig/workspace_services.rbs

Defined Under Namespace

Modules: SnippetExpandable

Constant Summary collapse

DEFAULT_CLOSING_PAIRS =
{"(" => ")", "[" => "]", "{" => "}", '"' => '"', "'" => "'"}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buffer = Buffer.new, wrap_width: nil, tab_size: 4) ⇒ Editor

Returns a new instance of Editor.

Parameters:

  • buffer (Buffer) (defaults to: Buffer.new)
  • wrap_width: (Integer, nil) (defaults to: nil)
  • tab_size: (Integer) (defaults to: 4)


11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/canopus/editor.rb', line 11

def initialize(buffer = Buffer.new, wrap_width: nil, tab_size: 4)
  @buffer, @next_selection = buffer, 0
  @tab_size, @use_tabs, @auto_pairs, @closing_pairs = tab_size, false, true, DEFAULT_CLOSING_PAIRS
  @display_map = DisplayMap.new(buffer, wrap_width: wrap_width, tab_size: tab_size)
  @scroll_x, @scroll_y, @viewport_rows = 0, 0, 30
  select(0)
  @subscription = buffer.on_edit do |patch|
    @display_map.block_map.blocks.values.each { |block| @display_map.remove_block(block.id) if block.kind == :git_diff }
    previous = @selections
    @selections = @selections.map { |s| Selection.new(s.id, patch.map_offset(s.anchor), patch.map_offset(s.head), s.goal) }.freeze
    notify_selection if @selections != previous
  end
end

Instance Attribute Details

#auto_pairs ⇒ Boolean

Returns the value of attribute auto_pairs.

Returns:

  • (Boolean)


9
10
11
# File 'lib/canopus/editor.rb', line 9

def auto_pairs
  @auto_pairs
end

#buffer ⇒ Buffer (readonly)

Returns the value of attribute buffer.

Returns:



8
9
10
# File 'lib/canopus/editor.rb', line 8

def buffer
  @buffer
end

#closing_pairs ⇒ closing_pairs

Returns the value of attribute closing_pairs.

Returns:



9
10
11
# File 'lib/canopus/editor.rb', line 9

def closing_pairs
  @closing_pairs
end

#composition ⇒ Zaniah::Input::Composition?

Returns the value of attribute composition.

Returns:

  • (Zaniah::Input::Composition, nil)


9
10
11
# File 'lib/canopus/editor.rb', line 9

def composition
  @composition
end

#display_map ⇒ DisplayMap (readonly)

Returns the value of attribute display_map.

Returns:



8
9
10
# File 'lib/canopus/editor.rb', line 8

def display_map
  @display_map
end

#relative_line_numbers ⇒ Boolean?

Returns the value of attribute relative_line_numbers.

Returns:

  • (Boolean, nil)


9
10
11
# File 'lib/canopus/editor.rb', line 9

def relative_line_numbers
  @relative_line_numbers
end

#scroll_x ⇒ Numeric (readonly)

Returns the value of attribute scroll_x.

Returns:

  • (Numeric)


8
9
10
# File 'lib/canopus/editor.rb', line 8

def scroll_x
  @scroll_x
end

#scroll_y ⇒ Numeric (readonly)

Returns the value of attribute scroll_y.

Returns:

  • (Numeric)


8
9
10
# File 'lib/canopus/editor.rb', line 8

def scroll_y
  @scroll_y
end

#selections ⇒ Array[Selection] (readonly)

Returns the value of attribute selections.

Returns:



8
9
10
# File 'lib/canopus/editor.rb', line 8

def selections
  @selections
end

#tab_size ⇒ Integer

Returns the value of attribute tab_size.

Returns:

  • (Integer)


9
10
11
# File 'lib/canopus/editor.rb', line 9

def tab_size
  @tab_size
end

#use_tabs ⇒ Boolean

Returns the value of attribute use_tabs.

Returns:

  • (Boolean)


9
10
11
# File 'lib/canopus/editor.rb', line 9

def use_tabs
  @use_tabs
end

#viewport_rows ⇒ Integer

Returns the value of attribute viewport_rows.

Returns:

  • (Integer)


9
10
11
# File 'lib/canopus/editor.rb', line 9

def viewport_rows
  @viewport_rows
end

Class Method Details

.search_pattern(pattern, case_sensitive: true, whole_word: false) ⇒ Regexp

Parameters:

  • pattern (String, Regexp)
  • case_sensitive: (Boolean) (defaults to: true)
  • whole_word: (Boolean) (defaults to: false)

Returns:



348
349
350
351
352
353
# File 'lib/canopus/editor.rb', line 348

def self.search_pattern(pattern, case_sensitive: true, whole_word: false)
  source = pattern.is_a?(Regexp) ? pattern.source : Regexp.escape(pattern)
  source = "\\b(?:#{source})\\b" if whole_word
  flags = (pattern.is_a?(Regexp) ? pattern.options : 0) | (case_sensitive ? 0 : Regexp::IGNORECASE)
  Regexp.new(source, flags, timeout: pattern.is_a?(Regexp) && pattern.timeout || 0.25)
end

Instance Method Details

#add_cursor(direction) ⇒ Array[Selection]?

Parameters:

  • direction (:up, :down)

Returns:

Raises:

  • (ArgumentError)


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/canopus/editor.rb', line 230

def add_cursor(direction)
  raise ArgumentError, "cursor direction must be up or down" unless i[up down].include?(direction)
  edge = @selections.public_send(direction == :up ? :min_by : :max_by) { |selection| @display_map.to_display(selection.head).row }
  point = @display_map.to_display(edge.head)
  row = point.row + (direction == :up ? -1 : 1)
  column = edge.goal || point.column
  offset = nil
  loop do
    return unless row.between?(0, @display_map.row_count - 1)
    unless @display_map.row(row).kind == :text
      row += direction == :up ? -1 : 1
      next
    end
    offset = @display_map.to_buffer(DisplayPoint.new(row, column))
    break unless @selections.any? { |selection| selection.empty? && selection.head == offset }
    row += direction == :up ? -1 : 1
  end

  selection = Selection.new(@next_selection, offset, offset, column)
  @next_selection += 1
  set_selections([*@selections, selection], merge: false)
end

#add_cursors_to_selected_lines(edge) ⇒ Array[Selection]

Parameters:

  • edge (:start, :end)

Returns:

Raises:

  • (ArgumentError)


252
253
254
255
256
257
258
259
260
261
262
# File 'lib/canopus/editor.rb', line 252

def add_cursors_to_selected_lines(edge)
  raise ArgumentError, "line edge must be start or end" unless i[start end].include?(edge)
  selections = selected_rows.map do |row|
    start = @buffer.rope.line_start(row)
    offset = edge == :start ? start : start + @buffer.line(row).bytesize
    selection = Selection.new(@next_selection, offset, offset, nil)
    @next_selection += 1
    selection
  end
  set_selections(selections, merge: false)
end

#choose_snippet ⇒ Boolean

Parameters:

  • value (String, Integer)

Returns:

  • (Boolean)


38
# File 'sig/snippet.rbs', line 38

def choose_snippet: (String | Integer value) -> bool

#clear_snippet ⇒ nil

Returns:

  • (nil)


39
# File 'sig/snippet.rbs', line 39

def clear_snippet: () -> nil

#delete_backward ⇒ Object

Returns:

  • (Object)


113
114
115
116
117
118
119
120
# File 'lib/canopus/editor.rb', line 113

def delete_backward
  before = @selections
  set_selections(@selections.map do |s|
    s.empty? ? Selection.new(s.id, horizontal(s.head, -1), s.head, nil) : s
  end)
  replace_selections("", kind: :backspace, group: true, before_selections: before)
  reveal_cursor
end

#delete_forward ⇒ Object

Returns:

  • (Object)


121
122
123
124
125
126
127
# File 'lib/canopus/editor.rb', line 121

def delete_forward
  before = @selections
  set_selections(@selections.map do |s|
    s.empty? ? Selection.new(s.id, s.head, horizontal(s.head, 1), nil) : s
  end)
  replace_selections("", kind: :delete, group: true, before_selections: before)
end

#dispose ⇒ void

This method returns an undefined value.



24
25
26
27
28
29
30
# File 'lib/canopus/editor.rb', line 24

def dispose
  @subscription.detach
  @selection_listeners&.clear
  @display_map.dispose
  @language_document&.dispose
  clear_snippet
end

#duplicate_lines ⇒ Object

Returns:

  • (Object)


293
294
295
296
297
298
299
300
301
302
# File 'lib/canopus/editor.rb', line 293

def duplicate_lines
  rows = selected_rows
  changes = rows.map do |row|
    ending = row + 1 < @buffer.line_count ? @buffer.rope.line_start(row + 1) : @buffer.rope.bytesize
    value = @buffer.line(row) + @buffer.line_ending
    value = @buffer.line_ending + @buffer.line(row) if row == @buffer.line_count - 1
    [ending...ending, value]
  end
  edit(changes, kind: :duplicate)
end

#edit(changes, kind: :edit) ⇒ Array[Selection]?

Apply externally computed edits with the same selection history as typing.

Parameters:

  • changes (Array[[Range[Integer], String]])
  • kind: (Symbol) (defaults to: :edit)

Returns:



401
402
403
404
405
406
407
408
# File 'lib/canopus/editor.rb', line 401

def edit(changes, kind: :edit)
  return if changes.empty?
  after = @buffer.rope.apply_edits(changes)
  patch = Patch.new(@buffer.rope, after, changes)
  selections = @selections.map { |s| Selection.new(s.id, patch.map_offset(s.anchor, bias: :left), patch.map_offset(s.head), nil) }
  @buffer.edit(changes, kind: kind, selections: selections, before_selections: @selections)
  set_selections(selections)
end

#indent(outdent: false) ⇒ Object

Parameters:

  • outdent: (Boolean) (defaults to: false)

Returns:

  • (Object)


263
264
265
266
267
# File 'lib/canopus/editor.rb', line 263

def indent(outdent: false)
  change_lines(:indent) do |line|
    outdent ? line.sub(/\A(?:\t| {1,#{@tab_size}})/, "") : (@use_tabs ? "\t" : " " * @tab_size) + line
  end
end

#insert_snippet ⇒ Snippet

Parameters:

  • source (String)
  • variables: (Hash[String | Symbol, String?])
  • workspace_root: (String, nil)
  • clipboard: (String, nil)

Returns:



33
# File 'sig/snippet.rbs', line 33

def insert_snippet: (String source, ?variables: Hash[String | Symbol, String?], ?workspace_root: String?, ?clipboard: String?) -> Snippet

#insert_text(text, auto_indent: true, pair: true) ⇒ Object

Parameters:

  • text (String)
  • auto_indent: (Boolean) (defaults to: true)
  • pair: (Boolean) (defaults to: true)

Returns:

  • (Object)

Raises:

  • (ArgumentError)


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/canopus/editor.rb', line 66

def insert_text(text, auto_indent: true, pair: true)
  raise ArgumentError, "text must be UTF-8" unless text.is_a?(String) && text.valid_encoding?
  closer = @closing_pairs[text] if pair && @auto_pairs
  texts = merged_selections(@selections, touching: false).map do |selection|
    if text == "\n" && auto_indent
      indent = language_document.indent_for(selection.start, tab_size: @tab_size, use_tabs: @use_tabs)
      if language_document.definition == Language::PLAIN
        before = @buffer.line(@buffer.rope.point_at(selection.start).row)[0, @buffer.rope.point_at(selection.start).column]
        indent += @use_tabs ? "\t" : " " * @tab_size if before.rstrip.end_with?("{", "[", "(")
      end
      @buffer.line_ending + indent
    elsif closer
      text + @buffer.rope.byteslice(selection.range).to_s + closer
    else
      text
    end
  end
  replace_selections(texts, kind: :typing, group: true, cursor_back: closer ? closer.bytesize : 0)
  reveal_cursor
end

#language=(definition) ⇒ Language::Document

Parameters:

Returns:



32
33
34
35
# File 'lib/canopus/editor.rb', line 32

def language=(definition)
  @language_document&.dispose
  @language_document = Language::Document.new(@buffer, definition: definition)
end

#language_document ⇒ Language::Document

Returns:



31
# File 'lib/canopus/editor.rb', line 31

def language_document = @language_document ||= Language::Document.new(@buffer)

#move(direction, extend: false, count: 1) ⇒ void

This method returns an undefined value.

Parameters:

  • direction (Symbol)
  • extend: (Boolean) (defaults to: false)
  • count: (Integer) (defaults to: 1)


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/canopus/editor.rb', line 143

def move(direction, extend: false, count: 1)
  next_selections = @selections.map do |selection|
    position, goal = selection.head, selection.goal
    if !extend && !selection.empty? && [:left, :right].include?(direction)
      position = direction == :left ? selection.start : selection.end
    else
      count.times do
        point = @display_map.to_display(position)
        row = @display_map.row(point.row)
        case direction
        when :left, :right
          position = horizontal(position, direction == :left ? -1 : 1)
          goal = nil
        when :up, :down, :page_up, :page_down
          goal ||= point.column
          amount = [:page_up, :page_down].include?(direction) ? @viewport_rows : 1
          amount *= -1 if [:up, :page_up].include?(direction)
          target_row = (point.row + amount).clamp(0, @display_map.row_count - 1)
          position = @display_map.to_buffer(DisplayPoint.new(target_row, goal))
        when :line_start
          position = @buffer.rope.respond_to?(:lazy?) ? @buffer.rope.line_start(point.row) : @display_map.to_buffer(DisplayPoint.new(point.row, 0)); goal = nil
        when :line_end
          position = @buffer.rope.respond_to?(:lazy?) ? @buffer.rope.line_end(point.row) : @display_map.to_buffer(DisplayPoint.new(point.row, row.text.length)); goal = nil
        when :file_start then position = 0; goal = nil
        when :file_end then position = @buffer.rope.bytesize; goal = nil
        when :word_left, :word_right
          position = word(position, direction == :word_left ? -1 : 1); goal = nil
        when :paragraph_up, :paragraph_down
          target = point.row
          step = direction == :paragraph_up ? -1 : 1
          loop do
            target += step
            break if target <= 0 || target >= @display_map.row_count - 1 || @display_map.row(target).text.strip.empty?
          end
          position = @display_map.to_buffer(DisplayPoint.new(target.clamp(0, @display_map.row_count - 1), 0))
        else raise ArgumentError, "unknown movement #{direction}"
        end
      end
    end
    Selection.new(selection.id, extend ? selection.anchor : position, position, goal)
  end
  set_selections(next_selections)
  reveal_cursor
end

#move_lines(direction) ⇒ Object

Parameters:

  • direction (Symbol)

Returns:

  • (Object)

Raises:

  • (ArgumentError)


303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/canopus/editor.rb', line 303

def move_lines(direction)
  raise ArgumentError, "line direction must be up or down" unless i[up down].include?(direction)
  first, last = selected_rows.minmax
  step = direction == :up ? -1 : 1
  return if step.negative? ? first.zero? : last + 1 >= @buffer.line_count
  rope = @buffer.rope
  from, to = step.negative? ? [first - 1, last] : [first, last + 1]
  rows, endings = [], []
  (from..to).each do |row|
    text = @buffer.line(row)
    ending = row + 1 < rope.line_count ? rope.line_start(row + 1) : rope.bytesize
    body_end = rope.line_start(row) + text.bytesize
    rows << text
    endings << rope.byteslice(body_end, ending - body_end).to_s
  end
  # Move contents while preserving the separators at each row, including
  # mixed CRLF/LF/Unicode endings and an unterminated final row.
  rows.rotate!(-step)
  start = rope.line_start(from)
  previous_end = from.positive? ? rope.line_start(from - 1) + @buffer.line(from - 1).bytesize : 0
  trailing_cr = from.positive? && rope.byteslice(previous_end, start - previous_end).to_s == "\r"
  replacement = +""
  rows.each_with_index do |text, index|
    ending = endings[index]
    # An empty moved row can put CR beside LF. Keep two logical breaks by
    # expanding that LF to CRLF instead of silently merging the rows.
    replacement << text
    replacement << "\r" if text.empty? && trailing_cr && ending == "\n"
    replacement << ending
    trailing_cr = ending == "\r"
  end
  finish = to + 1 < rope.line_count ? rope.line_start(to + 1) : rope.bytesize
  changes = [[start...finish, replacement]]
  after = rope.apply_edits(changes)
  move = lambda do |offset|
    row = rope.point_at(offset).row
    target = row + step
    next after.bytesize if target >= after.line_count
    column = row > last ? 0 : [offset - rope.line_start(row), after.line(target).bytesize].min
    after.line_start(target) + column
  end
  selections = @selections.map { |selection| Selection.new(selection.id, move.call(selection.anchor), move.call(selection.head), selection.goal) }
  @buffer.edit(changes, kind: :move_lines, selections: selections, before_selections: @selections)
  set_selections(selections)
end

#next_snippet ⇒ Boolean

Returns:

  • (Boolean)


34
# File 'sig/snippet.rbs', line 34

def next_snippet: () -> bool

#on_selection {|arg0| ... } ⇒ Zaniah::Subscription

Yields:

Yield Parameters:

Yield Returns:

  • (void)

Returns:

  • (Zaniah::Subscription)

Raises:

  • (ArgumentError)


46
47
48
49
50
# File 'lib/canopus/editor.rb', line 46

def on_selection(&listener)
  raise ArgumentError, "selection listener required" unless listener
  (@selection_listeners ||= []) << listener
  Zaniah::Subscription.new { @selection_listeners.delete(listener) }
end

#previous_snippet ⇒ Boolean

Returns:

  • (Boolean)


35
# File 'sig/snippet.rbs', line 35

def previous_snippet: () -> bool

#primary ⇒ Selection

Returns:



36
# File 'lib/canopus/editor.rb', line 36

def primary = @selections.last

#rectangle(first, last) ⇒ void

This method returns an undefined value.

Parameters:



220
221
222
223
224
225
226
227
228
229
# File 'lib/canopus/editor.rb', line 220

def rectangle(first, last)
  selections = BlockSelection.new(first, last).filter_map do |anchor, head|
    next unless @display_map.row(anchor.row).kind == :text
    selection = Selection.new(@next_selection, @display_map.to_buffer(anchor), @display_map.to_buffer(head), nil)
    @next_selection += 1
    selection
  end
  return if selections.empty?
  set_selections(selections, merge: false)
end

#redo ⇒ Boolean

Returns:

  • (Boolean)


135
136
137
138
139
140
141
# File 'lib/canopus/editor.rb', line 135

def redo
  clear_snippet
  return false unless @buffer.redo
  set_selections(@buffer.selections, merge: false)
  reveal_cursor
  true
end

#replace_all(pattern, replacement, **options) ⇒ Object

Parameters:

  • pattern (String, Regexp)
  • replacement (String)
  • case_sensitive: (Boolean)
  • whole_word: (Boolean)
  • range: (Range[Integer], nil)

Returns:

  • (Object)


394
395
396
397
398
# File 'lib/canopus/editor.rb', line 394

def replace_all(pattern, replacement, **options)
  changes = replacement_edits(pattern, replacement, **options)
  edit(changes, kind: :replace)
  changes.length
end

#replace_selections(texts, kind: :edit, group: false, cursor_back: 0, before_selections: @selections) ⇒ Array[Selection]

Parameters:

  • texts (String, Array[String])
  • kind: (Symbol) (defaults to: :edit)
  • group: (Boolean) (defaults to: false)
  • cursor_back: (Integer) (defaults to: 0)
  • before_selections: (Array[Selection]) (defaults to: @selections)

Returns:

Raises:

  • (ArgumentError)


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
# File 'lib/canopus/editor.rb', line 87

def replace_selections(texts, kind: :edit, group: false, cursor_back: 0, before_selections: @selections)
  selections = merged_selections(@selections, touching: false)
  if texts.is_a?(Array)
    unless [@selections.length, selections.length].include?(texts.length)
      raise ArgumentError, "one text per selection required"
    end
    if selections.length != @selections.length
      raise ArgumentError, "overlapping selections require the same text" unless texts.uniq.length == 1
      texts = texts.first
    end
  end
  texts = Array.new(selections.length, texts) if texts.is_a?(String)
  raise ArgumentError, "one text per selection required" unless texts.length == selections.length
  changes = selections.zip(texts).map { |selection, text| [selection.range, text] }
  @buffer.selections = before_selections
  delta = 0
  after = selections.zip(texts).map do |selection, text|
    ending = selection.start + delta + text.bytesize - cursor_back
    delta += text.bytesize - (selection.end - selection.start)
    Selection.new(selection.id, ending, ending, nil)
  end
  after = merged_selections(after)
  @buffer.edit(changes, kind: kind, selections: after, before_selections: before_selections, group: group)
  set_selections(after, merge: false)
end

#replacement_edits(pattern, replacement, case_sensitive: true, whole_word: false, range: nil) ⇒ Array[[Range[Integer], String]]

Parameters:

  • pattern (String, Regexp)
  • replacement (String)
  • case_sensitive: (Boolean) (defaults to: true)
  • whole_word: (Boolean) (defaults to: false)
  • range: (Range[Integer], nil) (defaults to: nil)

Returns:

  • (Array[[Range[Integer], String]])


367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/canopus/editor.rb', line 367

def replacement_edits(pattern, replacement, case_sensitive: true, whole_word: false, range: nil)
  regex = self.class.search_pattern(pattern, case_sensitive: case_sensitive, whole_word: whole_word)
  source = range ? @buffer.rope.byteslice(range).to_s : @buffer.text
  base = range ? range.begin : 0
  Canopus.with_regexp_timeout(regex) do
    source.to_enum(:scan, regex).map do
      found = Regexp.last_match
      value = replacement.gsub(/\\(?:([0-9&`'+\\])|k<([^>]*)(>)?)/) do
        escape, name, closing = Regexp.last_match.captures
        if name
          raise RuntimeError, "invalid group name reference format" unless closing
          found[name].to_s
        else
          case escape
          when "0", "&" then found[0]
          when "`" then found.pre_match
          when "'" then found.post_match
          when "+" then found.captures.reverse.find(&:itself).to_s
          when "\\" then "\\"
          else found.names.empty? ? found[escape.to_i].to_s : ""
          end
        end
      end
      [(base + found.bytebegin(0))...(base + found.byteend(0)), value]
    end
  end
end

#reveal_cursor ⇒ Numeric

Returns:

  • (Numeric)


414
415
416
417
418
419
# File 'lib/canopus/editor.rb', line 414

def reveal_cursor
  row = @display_map.to_display(primary.head).row
  @scroll_y = row if row < @scroll_y
  @scroll_y = row - @viewport_rows + 1 if row >= @scroll_y + @viewport_rows
  @scroll_y = [@scroll_y, 0].max
end

#scroll(dx: 0, dy: 0) ⇒ Numeric

Parameters:

  • dx: (Numeric) (defaults to: 0)
  • dy: (Numeric) (defaults to: 0)

Returns:

  • (Numeric)


410
411
412
413
# File 'lib/canopus/editor.rb', line 410

def scroll(dx: 0, dy: 0)
  @scroll_x = [@scroll_x + dx, 0].max
  @scroll_y = (@scroll_y + dy).clamp(0, [@display_map.row_count - @viewport_rows, 0].max)
end

#search(pattern, case_sensitive: true, whole_word: false, range: nil) ⇒ Array[Range[Integer]]

Parameters:

  • pattern (String, Regexp)
  • case_sensitive: (Boolean) (defaults to: true)
  • whole_word: (Boolean) (defaults to: false)
  • range: (Range[Integer], nil) (defaults to: nil)

Returns:

  • (Array[Range[Integer]])


354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/canopus/editor.rb', line 354

def search(pattern, case_sensitive: true, whole_word: false, range: nil)
  regex = self.class.search_pattern(pattern, case_sensitive: case_sensitive, whole_word: whole_word)
  base = range ? range.begin : 0
  source = range ? @buffer.rope.byteslice(range).to_s : @buffer.text
  matches = []
  Canopus.with_regexp_timeout(regex) do
    source.to_enum(:scan, regex).each do
      found = Regexp.last_match
      matches << ((base + found.bytebegin(0))...(base + found.byteend(0)))
    end
  end
  matches
end

#select(first, last = first, add: false) ⇒ self

Parameters:

  • first (Integer)
  • last (Integer) (defaults to: first)
  • add: (Boolean) (defaults to: false)

Returns:

  • (self)


37
38
39
40
41
42
43
44
# File 'lib/canopus/editor.rb', line 37

def select(first, last = first, add: false)
  @buffer.rope.point_at(first)
  @buffer.rope.point_at(last)
  selection = Selection.new(@next_selection, first, last, nil)
  @next_selection += 1
  set_selections(add ? [*@selections, selection] : [selection])
  self
end

#select_all ⇒ self

Returns:

  • (self)


188
# File 'lib/canopus/editor.rb', line 188

def select_all = select(0, @buffer.rope.bytesize)

#select_matches(pattern, **options) ⇒ Array[Range[Integer]]

Parameters:

  • pattern (String, Regexp)
  • case_sensitive: (Boolean)
  • whole_word: (Boolean)
  • range: (Range[Integer], nil)

Returns:

  • (Array[Range[Integer]])


189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/canopus/editor.rb', line 189

def select_matches(pattern, **options)
  matches = search(pattern, **options)
  return matches if matches.empty?
  selections = matches.map do |range|
    selection = Selection.new(@next_selection, range.begin, range.end, nil)
    @next_selection += 1
    selection
  end
  set_selections(selections, merge: false)
  reveal_cursor
  matches
end

#select_next_occurrence(all: false) ⇒ Object

Parameters:

  • all: (Boolean) (defaults to: false)

Returns:

  • (Object)


201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/canopus/editor.rb', line 201

def select_next_occurrence(all: false)
  needle = @buffer.rope.byteslice(primary.range).to_s
  if needle.empty?
    left, right = word(primary.head, -1), word(primary.head, 1)
    select(left, right)
    needle = @buffer.rope.byteslice(primary.range).to_s
  end
  return if needle.empty?
  text = @buffer.text.b
  cursor, matches = 0, []
  while (found = text.index(needle.b, cursor))
    matches << (found...(found + needle.bytesize))
    cursor = found + needle.bytesize
  end
  matches.reject! { |range| @selections.any? { |s| s.start == range.begin && s.end == range.end } }
  matches = [(matches.find { |range| range.begin >= primary.end } || matches.first)].compact unless all
  matches.each { |range| select(range.begin, range.end, add: true) }
end

#set_selections(selections, merge: true) ⇒ Array[Selection]

Parameters:

  • selections (Array[Selection])
  • merge: (Boolean) (defaults to: true)

Returns:



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/canopus/editor.rb', line 52

def set_selections(selections, merge: true)
  previous = @selections
  unless merge
    @selections = ordered_selections(selections).freeze
    @buffer.selections = @selections
    notify_selection if @selections != previous
    return @selections
  end
  @selections = merged_selections(selections).freeze
  @buffer.selections = @selections
  notify_selection if @selections != previous
  @selections
end

#snippet_active? ⇒ Boolean

Returns:

  • (Boolean)


36
# File 'sig/snippet.rbs', line 36

def snippet_active?: () -> bool

#snippet_choices ⇒ Array[String]?

Returns:

  • (Array[String], nil)


37
# File 'sig/snippet.rbs', line 37

def snippet_choices: () -> Array[String]?

#snippet_variables ⇒ Hash[String, String?]

Parameters:

  • workspace_root: (String, nil)
  • clipboard: (String, nil)
  • now: (Time)
  • selection: (Selection)
  • cursor_index: (Integer)

Returns:

  • (Hash[String, String?])


40
# File 'sig/snippet.rbs', line 40

def snippet_variables: (?workspace_root: String?, ?clipboard: String?, ?now: Time, ?selection: Selection, ?cursor_index: Integer) -> Hash[String, String?]

#toggle_comment(prefix: "#", suffix: nil) ⇒ Object

Parameters:

  • prefix: (String) (defaults to: "#")
  • suffix: (String, nil) (defaults to: nil)

Returns:

  • (Object)


268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/canopus/editor.rb', line 268

def toggle_comment(prefix: "#", suffix: nil)
  return if prefix.empty?
  suffix ||= case prefix
  when "/*" then "*/"
  when "<!--" then "-->"
  end
  rows = selected_rows
  uncomment = rows.all? do |row|
    line = @buffer.line(row).strip
    line.start_with?(prefix) && (!suffix || line.end_with?(suffix))
  end
  if suffix && !uncomment && rows.any? { |row| @buffer.line(row).include?(suffix) }
    raise Error, "cannot wrap a line containing the closing comment delimiter #{suffix}"
  end
  change_lines(:comment) do |line|
    if uncomment
      value = line.sub(/\A([ \t]*)#{Regexp.escape(prefix)} ?/, '\1')
      suffix ? value.sub(/ ?#{Regexp.escape(suffix)}([ \t]*)\z/, '\1') : value
    elsif suffix
      line.sub(/\A([ \t]*)(.*?)([ \t]*)\z/) { "#{Regexp.last_match(1)}#{prefix} #{Regexp.last_match(2)} #{suffix}#{Regexp.last_match(3)}" }
    else
      line.sub(/\A([ \t]*)/, "\\1#{prefix} ")
    end
  end
end

#undo ⇒ Boolean

Returns:

  • (Boolean)


128
129
130
131
132
133
134
# File 'lib/canopus/editor.rb', line 128

def undo
  clear_snippet
  return false unless @buffer.undo
  set_selections(@buffer.selections, merge: false)
  reveal_cursor
  true
end