Class: Buffer

Inherits:
String
  • Object
show all
Defined in:
lib/vimamsa/buffer_cursor.rb,
lib/vimamsa/buffer.rb,
lib/vimamsa/buffer_changetext.rb

Overview

Operations that change the content of the buffer e.g. insert, delete

Constant Summary collapse

AUTOSAVE_INTERVAL =

seconds between autosave checks

5
@@num_buffers =
0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str = "\n", fname = nil, prefix = "buf") ⇒ Buffer

Returns a new instance of Buffer.



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
# File 'lib/vimamsa/buffer.rb', line 17

def initialize(str = "\n", fname = nil, prefix = "buf")
  debug "Buffer.rb: def initialize"
  super(str)

  update_access_time
  @images = []
  @prefix = prefix
  @audiofiles = []
  @lang = nil
  @id = @@num_buffers
  @@num_buffers += 1
  @version = 0
  @default_mode = vma.kbd.default_mode
  @mode_stack = [@default_mode]
  gui_create_buffer(@id, self)
  debug "NEW BUFFER fn=#{fname} ID:#{@id}"

  # If true, we will create new line after this and paste there
  @paste_lines = false

  @module = nil

  @last_save = @last_asked_from_user = @file_last_cheked = Time.now
  @t_modified = @last_save
  @last_autosave = @last_save
  @autosave_thread = nil

  @crypt = nil
  @update_highlight = true
  @syntax_detect_failed = false
  @is_parsing_syntax = false
  @last_update = Time.now - 100
  @highlights = {}

  set_filename(fname)
  @hl_queue = []
  @line_action_handler = nil
  t1 = Time.now

  set_content(str)
  debug "init time:#{Time.now - t1}"

  # TODO: add \n when chars are added after last \n
  self << "\n" if self[-1] != "\n"
  @current_word = nil
  @active_kbd_mode = nil
  if cnf.lsp.enabled?
    init_lsp
  end
  start_autosave_timer
  return self
end

Instance Attribute Details

#access_timeObject (readonly)

Returns the value of attribute access_time.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def access_time
  @access_time
end

#active_kbd_modeObject

Returns the value of attribute active_kbd_mode.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def active_kbd_mode
  @active_kbd_mode
end

#basenameObject (readonly)

Returns the value of attribute basename.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def basename
  @basename
end

#btObject

Returns the value of attribute bt.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def bt
  @bt
end

#call_funcObject

Returns the value of attribute call_func.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def call_func
  @call_func
end

#cposObject (readonly)

Returns the value of attribute cpos.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def cpos
  @cpos
end

#default_modeObject

Returns the value of attribute default_mode.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def default_mode
  @default_mode
end

#deltasObject (readonly)

Returns the value of attribute deltas.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def deltas
  @deltas
end

#dirnameObject (readonly)

Returns the value of attribute dirname.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def dirname
  @dirname
end

#edit_historyObject (readonly)

Returns the value of attribute edit_history.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def edit_history
  @edit_history
end

#fnameObject (readonly)

Returns the value of attribute fname.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def fname
  @fname
end

#gui_reset_highlightObject

Returns the value of attribute gui_reset_highlight.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def gui_reset_highlight
  @gui_reset_highlight
end

#gui_update_highlightObject

Returns the value of attribute gui_update_highlight.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def gui_update_highlight
  @gui_update_highlight
end

#highlightsObject

Returns the value of attribute highlights.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def highlights
  @highlights
end

#hl_queueObject

Returns the value of attribute hl_queue.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def hl_queue
  @hl_queue
end

#idObject (readonly)

Returns the value of attribute id.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def id
  @id
end

#imagesObject (readonly)

Returns the value of attribute images.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def images
  @images
end

#is_highlightedObject (readonly)

Returns the value of attribute is_highlighted.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def is_highlighted
  @is_highlighted
end

#is_parsing_syntaxObject

Returns the value of attribute is_parsing_syntax.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def is_parsing_syntax
  @is_parsing_syntax
end

#langObject (readonly)

Returns the value of attribute lang.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def lang
  @lang
end

#last_saveObject (readonly)

Returns the value of attribute last_save.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def last_save
  @last_save
end

#line_action_handlerObject

Returns the value of attribute line_action_handler.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def line_action_handler
  @line_action_handler
end

#line_endsObject

Returns the value of attribute line_ends.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def line_ends
  @line_ends
end

#lposObject (readonly)

Returns the value of attribute lpos.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def lpos
  @lpos
end

#marksObject (readonly)

Returns the value of attribute marks.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def marks
  @marks
end

#mode_stackObject

Returns the value of attribute mode_stack.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def mode_stack
  @mode_stack
end

#moduleObject

Returns the value of attribute module.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def module
  @module
end

#paste_linesObject

Returns the value of attribute paste_lines.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def paste_lines
  @paste_lines
end

#pathnameObject (readonly)

Returns the value of attribute pathname.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def pathname
  @pathname
end

#posObject (readonly)

Returns the value of attribute pos.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def pos
  @pos
end

#selection_activeObject (readonly)

Returns the value of attribute selection_active.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def selection_active
  @selection_active
end

#subtitleObject

Returns the value of attribute subtitle.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def subtitle
  @subtitle
end

#syntax_detect_failedObject (readonly)

Returns the value of attribute syntax_detect_failed.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def syntax_detect_failed
  @syntax_detect_failed
end

#syntax_parserObject

Returns the value of attribute syntax_parser.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def syntax_parser
  @syntax_parser
end

#titleObject

Returns the value of attribute title.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def title
  @title
end

#update_highlightObject

Returns the value of attribute update_highlight.



11
12
13
# File 'lib/vimamsa/buffer.rb', line 11

def update_highlight
  @update_highlight
end

#update_hl_endposObject

Returns the value of attribute update_hl_endpos.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def update_hl_endpos
  @update_hl_endpos
end

#update_hl_startposObject

Returns the value of attribute update_hl_startpos.



13
14
15
# File 'lib/vimamsa/buffer.rb', line 13

def update_hl_startpos
  @update_hl_startpos
end

Instance Method Details

#add_audio(afpath, pos) ⇒ Object

Replace char at pos with audio widget for



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/vimamsa/buffer.rb', line 181

def add_audio(afpath, pos)
  return if !is_legal_pos(pos)
  afpath = File.expand_path(afpath)
  return if !File.exist?(afpath)

  vbuf = view.buffer
  itr = vbuf.get_iter_at(:offset => pos)
  itr2 = vbuf.get_iter_at(:offset => pos + 1)
  vbuf.delete(itr, itr2)
  anchor = vbuf.create_child_anchor(itr)

  mf = Gtk::MediaFile.new(afpath)
  mc = Gtk::MediaControls.new(mf)
  # mc = Gtk::MediaControls.new(Gtk::MediaFile.new)
  # Thread.new{mf.play;sleep 0.01; mf.pause}
  @audiofiles << mc

  view.add_child_at_anchor(mc, anchor)
  mc.set_size_request(500, 20)
  mc.set_margin_start(view.gutter_width + 10)

  provider = Gtk::CssProvider.new
  mc.add_css_class("medctr")

  provider.load(data: ".medctr {   background-color:#353535; }")
  mc.style_context.add_provider(provider)

  pp mf.set_prepared(true)
  # pp mf.pause
  pp mf.duration
  pp mf.has_audio?

  # >> Gtk::MediaControls.signals
  # => ["direction-changed", "destroy", "show", "hide", "map", "unmap", "realize", "unrealize", "state-flags-changed", "mnemonic-activate", "move-focus", "keynav-failed", "query-tooltip", "notify"]

  # If this is done too early, the gutter is not yet drawn which
  # will result in wrong position
  if @audiofiles.size == 1
    run_as_idle proc { self.reset_audio_widget_positions }
  end
  $audiof = mf
end

#add_delta(delta, apply = false, auto_update_cpos = false) ⇒ Object

TODO: change to apply=true as default



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
# File 'lib/vimamsa/buffer_changetext.rb', line 7

def add_delta(delta, apply = false, auto_update_cpos = false)
  @t_modified = Time.now
  return if !is_delta_ok(delta)
  if delta[1] == DELETE
    return if delta[0] >= self.size
    # If go over length of buffer
    if delta[0] + delta[2] >= self.size
      delta[2] = self.size - delta[0]
    end
  end

  @edit_version += 1
  @redo_stack = []
  if apply
    delta = run_delta(delta, auto_update_cpos)
  else
    @deltas << delta
  end

  unless @macro_group_active
    if @last_delta_time && (Time.now - @last_delta_time) > cnf.undo.group_threshold!
      new_undo_group
    end
  end
  @current_group << delta
  @last_delta_time = Time.now
  if self[-1] != "\n"
    add_delta([self.size, INSERT, 1, "\n"], true)
  end
  reset_larger_cpos #TODO: correct here?
  refresh_title
end

#add_hl_update(startpos, endpos) ⇒ Object



460
461
462
463
464
465
# File 'lib/vimamsa/buffer.rb', line 460

def add_hl_update(startpos, endpos)
  return if @is_highlighted == false

  debug "@update_hl_endpos = #{endpos}"
  @hl_queue << [startpos, endpos]
end

#add_image(imgpath, pos) ⇒ Object



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

def add_image(imgpath, pos)
  return if !is_legal_pos(pos)

  vbuf = view.buffer
  itr = vbuf.get_iter_at(:offset => pos)
  return if itr&.child_anchor  # anchor already exists here, image already rendered
  itr2 = vbuf.get_iter_at(:offset => pos + 1)
  vbuf.delete(itr, itr2)
  anchor = vbuf.create_child_anchor(itr)

  da = ResizableImage.new(imgpath, view)
  view.add_child_at_anchor(da, anchor)

  da.set_draw_func do |widget, cr|
    da.do_draw(widget, cr)
  end

  da.scale_image

  # vma.gui.handle_image_resize #TODO:gtk4
  @images << { :path => imgpath, :obj => da, :anchor => anchor }

  gui_set_current_buffer(@id) #TODO: needed?
end

#append(c) ⇒ Object



1194
1195
1196
1197
1198
# File 'lib/vimamsa/buffer.rb', line 1194

def append(c)
  pos = self.size - 1
  add_delta([pos, INSERT, c.size, c], true)
  calculate_line_and_column_pos
end

#apply_inverse_delta(d) ⇒ Object



574
575
576
577
578
579
580
# File 'lib/vimamsa/buffer.rb', line 574

def apply_inverse_delta(d)
  if d[1] == DELETE
    run_delta([d[0], INSERT, 0, d[3]])
  elsif d[1] == INSERT
    run_delta([d[0], DELETE, d[3].size])
  end
end

#at_end_of_buffer?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/vimamsa/buffer_cursor.rb', line 25

def at_end_of_buffer?()
  return @pos == self.size
end

#at_end_of_line?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/vimamsa/buffer_cursor.rb', line 21

def at_end_of_line?()
  return (self[@pos] == "\n" or at_end_of_buffer?)
end

#autosaveObject



1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
# File 'lib/vimamsa/buffer.rb', line 1625

def autosave
  return if @fname.nil?
  return if @t_modified <= @last_autosave
  apath = autosave_path
  contents = self.to_s
  Thread.new {
    begin
      File.open(apath, "w+") { |io| io.set_encoding(self.encoding); io.write(contents) }
      @last_autosave = Time.now
      debug "autosaved to #{apath}"
    rescue => ex
      debug "autosave failed: #{ex}"
    end
  }
end

#autosave_pathObject



1618
1619
1620
1621
1622
1623
# File 'lib/vimamsa/buffer.rb', line 1618

def autosave_path
  return nil if @fname.nil?
  dir = File.dirname(@fname)
  base = File.basename(@fname)
  File.join(dir, ".#{base}_vma_autosave")
end

#backupObject



1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
# File 'lib/vimamsa/buffer.rb', line 1707

def backup()
  fname = @fname
  return if !@fname
  spfx = fname.gsub("=", "==").gsub("/", "=:")
  spath = File.expand_path("~/.vimamsa/backup")
  return false if !can_save_to_directory?(spath)
  datetime = DateTime.now().strftime("%d%m%Y:%H%M%S")
  savepath = "#{spath}/#{spfx}_#{datetime}"
  message("Backup buffer #{fname} TO: #{savepath}")
  if is_path_writable(savepath)
    write_contents_to_file(savepath)
  else
    message("PATH NOT WRITABLE: #{savepath}")
  end
end

#calculate_line_and_column_pos(reset = true) ⇒ Object



74
75
76
77
# File 'lib/vimamsa/buffer_cursor.rb', line 74

def calculate_line_and_column_pos(reset = true)
  @lpos, @cpos = get_line_and_col_pos(@pos)
  reset_larger_cpos if reset
end

#calculate_pos_from_cpos_lpos(reset = true) ⇒ Object

Calculate the one dimensional array index based on column and line positions



101
102
103
# File 'lib/vimamsa/buffer_cursor.rb', line 101

def calculate_pos_from_cpos_lpos(reset = true)
  set_line_and_column_pos(nil, nil)
end

#check_autosave_loadObject



1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
# File 'lib/vimamsa/buffer.rb', line 1658

def check_autosave_load
  apath = autosave_path
  return if apath.nil? || !File.exist?(apath)
  if File.read(apath) == self.to_s
    delete_autosave_file
    return
  end
  title = "An autosave file was found for <b>#{File.basename(@fname)}</b>. Load autosave?"
  params = {
    "title" => title,
    "inputs" => {
      "yes_btn"    => { :label => "Load",   :type => :button, :default_focus => true },
      "delete_btn" => { :label => "Delete autosave", :type => :button },
    },
    :callback => proc { |x| load_autosave_callback(x) },
  }
  PopupFormGenerator.new(params).run
end

#check_if_modified_outsideObject



1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
# File 'lib/vimamsa/buffer.rb', line 1590

def check_if_modified_outside
  # Don't check if less than 8 seconds since last checked
  return false if @fname.nil?
  return false if Time.now - 8 < @file_last_cheked
  @file_last_cheked = Time.now
  return false if !File.exist?(@fname)

  file_stat = File.stat(@fname)
  modification_time = file_stat.mtime

  if modification_time > @last_save and @last_asked_from_user < modification_time
    @last_asked_from_user = Time.now
    debug "File modified outside this program."
    params = {}
    params["title"] = "The file has been modified outside this program. Reload from disk? \r #{@fname}"
    params["inputs"] = {}
    params["inputs"]["yes_btn"] = { :label => "Yes", :type => :button, :default_focus => true }
    callback = proc { |x| check_if_modified_outside_callback(x) }
    params[:callback] = callback
    PopupFormGenerator.new(params).run
    return true
  end

  return false
end

#check_if_modified_outside_callback(x) ⇒ Object



1569
1570
1571
1572
1573
1574
# File 'lib/vimamsa/buffer.rb', line 1569

def check_if_modified_outside_callback(x)
  debug "check_if_modified_outside_callback"
  if x["yes_btn"] == "submit"
    revert()
  end
end

#cleanup_deleted_images(deleted_text) ⇒ Object

TODO: review



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/vimamsa/buffer.rb', line 240

def cleanup_deleted_images(deleted_text)
  return if @images.empty?
  return unless deleted_text&.include?("⟦img:")
  deleted_text.scan(/⟦img:(.+?)⟧/) do |match|
    tag_path = match[0]
    abs_path = translate_path(tag_path, self)
    @images.delete_if do |img|
      next false unless img[:path] == abs_path || img[:path] == tag_path
      # img[:obj].destroy unless img[:obj].destroyed?
      # Schedule anchor character deletion after the current delta is done.
      # Using the anchor object lets us find the correct position even if
      # prior edits shifted it.
      anchor = img[:anchor]
      buf_ref = self
      run_as_idle proc {
        next if anchor.nil? || anchor.deleted?
        itr = buf_ref.view.buffer.get_iter_at_child_anchor(anchor)
        next if itr.nil?
        pos = itr.offset
        buf_ref.add_delta([pos, DELETE, 1], true)
        buf_ref.calculate_line_and_column_pos
      }
      true
    end
  end
end

#closeObject



1702
1703
1704
1705
# File 'lib/vimamsa/buffer.rb', line 1702

def close()
  idx = vma.buffers.get_buffer_by_id(@id)
  vma.buffers.close_buffer(idx)
end

#comment_line(op = :comment) ⇒ Object



719
720
721
722
723
724
725
726
727
# File 'lib/vimamsa/buffer.rb', line 719

def comment_line(op = :comment)
  num_lines = get_repeat_num()
  lrange = line_range(@lpos, num_lines)
  if op == :comment
    comment_linerange(lrange)
  elsif op == :uncomment
    uncomment_linerange(lrange)
  end
end

#comment_linerange(r) ⇒ Object



634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/vimamsa/buffer.rb', line 634

def comment_linerange(r)
  com_str = get_com_str()
  lines = self[r].lines
  mod = ""
  lines.each { |line|
    m = line.match(/^(\s*)(\S.*)/)
    if m == nil or m[2].size == 0
      ret = line
    elsif m[2].size > 0
      ret = "#{m[1]}#{com_str} #{m[2]}\n"
    end
    mod << ret
  }
  replace_range(r, mod)
end

#comment_selection(op = :comment) ⇒ Object



687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/vimamsa/buffer.rb', line 687

def comment_selection(op = :comment)
  if visual_mode?
    (startpos, endpos) = get_visual_mode_range2
    first = get_line_start(startpos)
    #      last = get_line_end(endpos)
    last = get_line_end(endpos - 1)
    if op == :comment
      comment_linerange(first..last)
    elsif op == :uncomment
      uncomment_linerange(first..last)
    end
    self.end_visual_mode
  end
end

#complete_current_word(rep) ⇒ Object



205
206
207
208
209
210
211
212
213
214
# File 'lib/vimamsa/buffer_changetext.rb', line 205

def complete_current_word(rep)
  debug "complete_current_word", 2
  p = @pos - 1
  return if !is_legal_pos(p)
  (word, range) = get_word_in_pos(p, boundary: :word)
  debug [word, range].to_s, 2
  endpos = range.begin + rep.size
  replace_range(range, rep)
  set_pos(endpos)
end

#context_menu_itemsObject



1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/vimamsa/buffer.rb', line 1038

def context_menu_items()
  m = []
  if @visual_mode
    seltxt = get_current_selection
    m << ["Copy", self.method("copy_active_selection"), nil]
    m << ["Join lines", self.method("convert_selected_text"), :joinlines]
    # m << ["Sort", self.method("convert_selected_text"), :sortlines]
    m << ["Sort", method("call"), :sortlines]
    m << ["Filter: get numbers", method("call"), :getnums_on_lines]
    m << ["Delete selection", method("call"), :delete_selection]

    # m << ["Search in dictionary", self.method("handle_word"), nil]
    # m << ["Search in google", self.method("handle_word"), nil]
    m << ["Execute in terminal", method("exec_in_terminal"), seltxt]
  else
    (word, wtype) = get_cur_nonwhitespace_word()
    if wtype == :url
      m << ["Open url", self.method("open_url"), word]
    elsif wtype == :linepointer
      m << ["Jump to line", self.method("handle_word"), [word, wtype]]
    elsif wtype == :textfile
      m << ["Open text file", self.method("handle_word"), [word, wtype]]
    elsif wtype == :file
      m << ["Open file (xdg-open)", self.method("handle_word"), [word, wtype]]
    elsif wtype == :hpt_link
      m << ["Jump to file", self.method("handle_word"), [word, wtype]]
    else
      # m << ["TODO", self.method("handle_word"), word]
      m << ["Paste", method("call"), :paste_after]
    end
  end
  return m
end

#continue_selectionObject

Start selection if not already started



1316
1317
1318
# File 'lib/vimamsa/buffer.rb', line 1316

def continue_selection()
  start_selection if !@selection_active
end

#convert_selected_text(converter_id) ⇒ Object



1362
1363
1364
1365
1366
1367
1368
1369
1370
# File 'lib/vimamsa/buffer.rb', line 1362

def convert_selected_text(converter_id)
  return if !@visual_mode
  r = get_visual_mode_range
  txt = self[r]
  txt = $vma.apply_conv(converter_id, txt)
  #TODO: Detect if changed?
  replace_range(r, txt)
  end_visual_mode
end

#copy(range_id) ⇒ Object



752
753
754
755
756
757
758
759
# File 'lib/vimamsa/buffer.rb', line 752

def copy(range_id)
  @paste_lines = false
  debug "range_id: #{range_id}"
  debug range_id.inspect
  range = get_range(range_id)
  debug range.inspect
  vma.clipboard.set(self[range])
end

#copy_active_selection(x = nil) ⇒ Object



1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
# File 'lib/vimamsa/buffer.rb', line 1320

def copy_active_selection(x = nil)
  debug "!COPY SELECTION vm=#{@visual_mode}"
  @paste_lines = false
  return if !@visual_mode

  debug "COPY SELECTION"
  s = self[get_visual_mode_range]
  if x == :append
    debug "APPEND"
    s += "\n" + vma.clipboard.get()
  end

  vma.clipboard.set(s)
  end_visual_mode
  return true
end

#copy_lineObject



1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
# File 'lib/vimamsa/buffer.rb', line 1405

def copy_line()
  vma.kbd.method_handles_repeat = true
  num_lines = 1
  if !vma.kbd.next_command_count.nil? and vma.kbd.next_command_count > 0
    num_lines = vma.kbd.next_command_count
    debug "copy num_lines:#{num_lines}"
  end
  vma.clipboard.set(self[line_range(@lpos, num_lines)])
  @paste_lines = true
end

#cur_nonwhitespace_word_actionObject



1153
1154
1155
1156
1157
1158
# File 'lib/vimamsa/buffer.rb', line 1153

def cur_nonwhitespace_word_action()

  # (word, wtype) = get_cur_nonwhitespace_word()
  wnfo = get_cur_nonwhitespace_word()
  handle_word(wnfo)
end

#current_charObject



601
602
603
# File 'lib/vimamsa/buffer.rb', line 601

def current_char()
  return self[@pos]
end

#current_lineObject



605
606
607
608
# File 'lib/vimamsa/buffer.rb', line 605

def current_line()
  range = line_range(@lpos, 1)
  return self[range]
end

#current_line_rangeObject



729
730
731
732
# File 'lib/vimamsa/buffer.rb', line 729

def current_line_range()
  range = line_range(@lpos, 1)
  return range
end

#delete(op, x = nil) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/vimamsa/buffer_changetext.rb', line 235

def delete(op, x = nil)
  @paste_lines = false
  # Delete selection
  if op == SELECTION && visual_mode?
    (startpos, endpos) = get_visual_mode_range2
    delete_range(startpos, endpos, x)
    @pos = [@pos, @selection_start].min
    if vma.kbd.get_mode == :visual
      end_visual_mode
    else
      end_selection
    end
    #return

    # Delete current char
  elsif op == CURRENT_CHAR_FORWARD
    return if @pos >= self.size - 1 # May not delete last '\n'
    add_delta([@pos, DELETE, 1], true)

    # Delete current char and then move backward
  elsif op == CURRENT_CHAR_BACKWARD
    add_delta([@pos, DELETE, 1], true)
    @pos -= 1

    # Delete the char before current char and move backward
  elsif op == BACKWARD_CHAR and @pos > 0
    add_delta([@pos - 1, DELETE, 1], true)
    @pos -= 1
  elsif op == FORWARD_CHAR #TODO: ok?
    add_delta([@pos + 1, DELETE, 1], true)
  end
  set_pos(@pos)
  #recalc_line_ends
  calculate_line_and_column_pos
  #need_redraw!
end

#delete2(range_id, mark = nil) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/vimamsa/buffer_changetext.rb', line 221

def delete2(range_id, mark = nil)
  @paste_lines = false
  range = get_range(range_id, mark: mark)
  return false if range == nil
  debug "RANGE"
  debug range.inspect
  debug range.inspect
  debug "------"
  delete_range(range.first, range.last)
  pos = [range.first, @pos].min
  set_pos(pos)
  return true
end

#delete_active_selectionObject

TODO: remove this function



1424
1425
1426
1427
1428
1429
1430
# File 'lib/vimamsa/buffer.rb', line 1424

def delete_active_selection() #TODO: remove this function
  return if !@visual_mode #TODO: this should not happen

  _start, _end = get_visual_mode_range
  vma.clipboard.set(self[_start, _end])
  end_visual_mode
end

#delete_autosave_fileObject



1650
1651
1652
1653
1654
1655
1656
# File 'lib/vimamsa/buffer.rb', line 1650

def delete_autosave_file
  apath = autosave_path
  return if apath.nil?
  File.delete(apath) if File.exist?(apath)
rescue => ex
  debug "delete autosave failed: #{ex}"
end

#delete_lineObject



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/vimamsa/buffer_changetext.rb', line 303

def delete_line()
  vma.kbd.method_handles_repeat = true
  num_lines = 1
  if !vma.kbd.next_command_count.nil? and vma.kbd.next_command_count > 0
    num_lines = vma.kbd.next_command_count
    debug "copy num_lines:#{num_lines}"
  end
  lrange = line_range(@lpos, num_lines)
  s = self[lrange]
  add_delta([lrange.begin, DELETE, lrange.end - lrange.begin + 1], true)
  vma.clipboard.set(s)
  update_pos(lrange.begin)
  @paste_lines = true
  #recalc_line_ends
end

#delete_range(startpos, endpos, x = nil) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/vimamsa/buffer_changetext.rb', line 272

def delete_range(startpos, endpos, x = nil)
  s = self[startpos..endpos]
  if startpos > endpos or s == ""
    return
  end
  if x == :append
    debug "APPEND"
    s += "\n" + vma.clipboard.get()
  end
  vma.clipboard.set(s)
  add_delta([startpos, DELETE, (endpos - startpos + 1)], true)
  #recalc_line_ends
  calculate_line_and_column_pos
end

#detect_file_languageObject



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
# File 'lib/vimamsa/buffer.rb', line 146

def detect_file_language
  @lang = nil
  @lang = "c" if @fname.match(/\.(c|h|cpp)$/)
  @lang = "java" if @fname.match(/\.(java)$/)
  @lang = "ruby" if @fname.match(/\.(rb)$/)
  @lang = "hyperplaintext" if @fname.match(/\.(txt)$/)
  @lang = "php" if @fname.match(/\.(php)$/)
  @lsp = nil

  lm = GtkSource::LanguageManager.new

  lm.set_search_path(lm.search_path << ppath("lang/"))
  lang = lm.guess_language(@fname)
  # lang.get_metadata("line-comment-start")
  # lang.get_metadata("block-comment-start")
  # lang.get_metadata("block-comment-end")
  @lang_nfo = lang
  if !lang.nil? and !lang.id.nil?
    debug "Guessed LANG: #{lang.id}"
    @lang = lang.id
  end
  debug @lang.inspect

  if @lang
    gui_set_file_lang(@id, @lang)
  end
  return @lang
end

#end_selectionObject



1301
1302
1303
1304
1305
1306
1307
# File 'lib/vimamsa/buffer.rb', line 1301

def end_selection()
  # @selection_start = nil
  @selection_active = false
  @visual_mode = false
  #TODO: remove @visual_mode
  # print(caller())
end

#end_visual_modeObject



1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
# File 'lib/vimamsa/buffer.rb', line 1432

def end_visual_mode()
  debug "end_visual_mode, #{vma.kbd.get_mode}, #{visual_mode?}", 2
  return if vma.kbd.get_mode != :visual
  if !visual_mode?
    debug "end_visual_mode, !visual_mode?"
    # TODO: should not happen
  end
  debug "End visual mode"
  end_selection
  vma.kbd.to_previous_mode
  @visual_mode = false
  return true
end

#eval_whole_buf(x = 888) ⇒ Object



1352
1353
1354
1355
1356
1357
1358
1359
1360
# File 'lib/vimamsa/buffer.rb', line 1352

def eval_whole_buf(x = 888)
  s = self.to_s
  begin
    eval(s)
  rescue Exception
    message("Error running eval")
  else
  end
end

#execute_current_line_in_terminal(autoclose = false) ⇒ Object



1200
1201
1202
1203
# File 'lib/vimamsa/buffer.rb', line 1200

def execute_current_line_in_terminal(autoclose = false)
  s = get_current_line
  exec_in_terminal(s, autoclose)
end

#get_com_strObject



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/vimamsa/buffer.rb', line 610

def get_com_str()
  # return nil if @syntax_detect_failed

  com_str = nil
  # if get_file_type() == "c" or get_file_type() == "java"
  # com_str = "//"
  # elsif get_file_type() == "ruby"
  # com_str = "#"
  # else
  # com_str = "//"
  # end

  if !@lang_nfo.nil?
    com_str = @lang_nfo.("line-comment-start")
  end

  # lang.get_metadata("block-comment-start")
  # lang.get_metadata("block-comment-end")

  com_str = "//" if com_str.nil?

  return com_str
end

#get_cur_nonwhitespace_wordObject



1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
# File 'lib/vimamsa/buffer.rb', line 1110

def get_cur_nonwhitespace_word()
  (word, range) = get_word_in_pos(@pos, boundary: :space)
  debug "'WORD: #{word}'"
  # message("Open link #{word}")
  linep = get_file_line_pointer(word)
  debug "linep'#{linep}'"
  if word[0] != "/" and word[0] != "~"
    path = File.expand_path("#{bufs.last_dir}/#{word}")
  else
    path = File.expand_path(word)
  end
  wtype = nil
  if is_url(word)
    wtype = :url
  elsif is_existing_file(path)
    message("PATH:'#{word}'")
    # if vma.can_open_extension?(path)
    if file_is_text_file(path)
      wtype = :textfile
    else
      wtype = :file
    end
    word = path
    # elsif hpt_check_cur_word(word) #TODO: check only
    # debug word
  elsif linep != nil
    wtype = :linepointer
    word = linep
  elsif (bare_linep = resolve_bare_file_line_pointer(word))
    wtype = :linepointer
    word = bare_linep
  elsif m = word.match(/⟦help:(.*)⟧/)
    return [m[1], :help]
  else
    fn = hpt_check_cur_word(word)
    if !fn.nil?
      return [fn, :hpt_link]
    end
  end

  return [word, wtype]
end

#get_current_lineObject



1451
1452
1453
1454
# File 'lib/vimamsa/buffer.rb', line 1451

def get_current_line
  s = self[line_range(@lpos, 1)]
  return s
end

#get_current_selectionObject



1456
1457
1458
1459
# File 'lib/vimamsa/buffer.rb', line 1456

def get_current_selection()
  return "" if !@visual_mode
  return self[get_visual_mode_range]
end

#get_file_typeObject



329
330
331
# File 'lib/vimamsa/buffer.rb', line 329

def get_file_type()
  return @lang
end

#get_line_and_col_pos(pos) ⇒ Object

Calculate the two dimensional column and line positions based on (one dimensional) position in the buffer.



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/vimamsa/buffer_cursor.rb', line 61

def get_line_and_col_pos(pos)
  pos = self.size if pos > self.size
  pos = 0 if pos < 0

  lpos = get_line_pos(pos)

  lpos = @line_ends.size if lpos == nil
  cpos = pos
  cpos -= @line_ends[lpos - 1] + 1 if lpos > 0

  return [lpos, cpos]
end

#get_line_end(pos) ⇒ Object



683
684
685
# File 'lib/vimamsa/buffer.rb', line 683

def get_line_end(pos)
  return @line_ends.select { |x| x > pos }.min
end

#get_line_pos(pos) ⇒ Object

Get the line number of character position



54
55
56
57
# File 'lib/vimamsa/buffer_cursor.rb', line 54

def get_line_pos(pos)
  lpos = @line_ends.bsearch_index { |x, _| x >= pos }
  return lpos
end

#get_line_start(pos) ⇒ Object



650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/vimamsa/buffer.rb', line 650

def get_line_start(pos)

  # Bsearch: https://www.rubydoc.info/stdlib/core/Array#bsearch-instance_method
  # In find-minimum mode (this is a good choice for typical use case), the block must return true or false, and there must be an index i (0 <= i <= ary.size) so that:
  # the block returns false for any element whose index is less than i, and
  # the block returns true for any element whose index is greater than or equal to i.
  # This method returns the i-th element. If i is equal to ary.size, it returns nil.

  # (OLD) slower version:
  # ls = @line_ends.select { |x| x < pos }.max
  a = @line_ends.bsearch_index { |x| x >= pos }

  a = @line_ends[-1] if a == nil
  a = 0 if a == nil
  if a > 0
    a = a - 1
  else
    a = 0
  end
  ls = nil
  ls = @line_ends[a] if a != nil
  # if a != nil and ls != @line_ends[a]
  # debug "NO MATCH @line_ends[a]"
  # end

  if ls == nil
    ls = 0
  else
    ls = ls + 1
  end
  return ls
end

#get_range(range_id, mark: nil) ⇒ Object

Ranges to use in delete or copy operations



841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
# File 'lib/vimamsa/buffer.rb', line 841

def get_range(range_id, mark: nil)
  range = nil
  if range_id == :to_word_end
    # TODO: better way to make the search than + 150 from current position
    wmarks = get_word_end_marks(@pos, @pos + 150)
    if wmarks.any?
      range = @pos..(wmarks[0])
    end
  elsif range_id == :to_next_word # start of
    wmarks = get_word_start_marks(@pos, @pos + 150)
    if !wmarks[0].nil?
      range = @pos..(wmarks[0] - 1)
      debug range, 2
    else
      range = get_range(:to_word_end)
    end
    # Ripl.start :binding => binding

  elsif range_id == :to_mark
    debug "TO MARK"
    start = @line_ends[@lpos]
    mpos = @marks[mark]
    if !mpos.nil?
      range = start..mpos
    else
      return nil
    end
  elsif range_id == :to_line_end
    debug "TO LINE END"
    range = @pos..(@line_ends[@lpos] - 1)
  elsif range_id == :to_line_start
    debug "TO LINE START: #{@lpos}"

    if @cpos == 0
      range = nil
    else
      if @lpos == 0
        startpos = 0
      else
        startpos = @line_ends[@lpos - 1] + 1
      end
      endpos = @pos - 1
      range = startpos..endpos
    end
    # range = startpos..(@pos - 1)
  else
    crash("INVALID RANGE")
  end
  return range if range == nil
  if range.last < range.first
    range = range.last..range.first
    # range.last = range.first
  end
  if range.first < 0
    # range.first = 0
    range = 0..range.last
  end
  if range.last >= self.size
    # range.last = self.size - 1
    range = range.first..(self.size - 1)
  end
  debug range, 2
  return range
end

#get_repeat_numObject



710
711
712
713
714
715
716
717
# File 'lib/vimamsa/buffer.rb', line 710

def get_repeat_num()
  vma.kbd.method_handles_repeat = true
  repeat_num = 1
  if !vma.kbd.next_command_count.nil? and vma.kbd.next_command_count > 0
    repeat_num = vma.kbd.next_command_count
  end
  return repeat_num
end

#get_short_pathObject



452
453
454
455
456
457
458
# File 'lib/vimamsa/buffer.rb', line 452

def get_short_path()
  fpath = self.fname
  if fpath.size > 50
    fpath = fpath[-50..-1]
  end
  return fpath
end

#get_visual_mode_rangeObject



1461
1462
1463
1464
1465
1466
# File 'lib/vimamsa/buffer.rb', line 1461

def get_visual_mode_range()
  _start = @selection_start || @pos
  _end = @pos
  _start, _end = _end, _start if _start > _end
  return _start..(_end)
end

#get_visual_mode_range2Object



1446
1447
1448
1449
# File 'lib/vimamsa/buffer.rb', line 1446

def get_visual_mode_range2()
  r = get_visual_mode_range
  return [r.begin, r.end]
end

#get_word_end_marks(startpos, endpos) ⇒ Object

Get positions of last characters in words



985
986
987
988
989
990
991
992
993
# File 'lib/vimamsa/buffer.rb', line 985

def get_word_end_marks(startpos, endpos)
  startpos = 0 if startpos < 0
  endpos = self.size if endpos > self.size
  search_str = self[(startpos)..(endpos)]
  return if search_str == nil
  wsmarks = scan_indexes(search_str, /(?<=\p{Word})[^\p{Word}]/)
  wsmarks = wsmarks.collect { |x| x + startpos - 1 }
  return wsmarks
end

#get_word_in_pos(p, boundary: :space) ⇒ Object



1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
# File 'lib/vimamsa/buffer.rb', line 1083

def get_word_in_pos(p, boundary: :space)
  maxws = 200 # max word size
  if boundary == :space
    wem = scan_marks(p, p + maxws, /(?<=\S)\s/, -1)
    wsm = scan_marks(p - maxws, p, /((?<=\s)\S)|^\S/)
    word_start = wsm[-1]
    word_end = wem[0]
  elsif boundary == :word2
    wem = scan_marks(p, p + maxws, /\b/,-1)
    wsm = scan_marks(p - maxws, p, /\b\w/)
    word_start = wsm[-1]
    word_end = wem.select{|x|x>=word_start}[0]
   
  elsif boundary == :word
  #TODO: change name :word. This works only with autocomplete
    wsm = scan_marks(p - maxws, p, /\b\w/)
    word_start = wsm[-1]
    word_end = p
  end

  word_start = p if word_start == nil
  word_end = p if word_end == nil
  word = self[word_start..word_end]

  return [word, (word_start..word_end)]
end

#get_word_start_marks(startpos, endpos) ⇒ Object

Get positions of first characters in words



996
997
998
999
1000
1001
1002
1003
1004
# File 'lib/vimamsa/buffer.rb', line 996

def get_word_start_marks(startpos, endpos)
  startpos = 0 if startpos < 0
  endpos = self.size if endpos > self.size
  search_str = self[(startpos)..(endpos)]
  return if search_str == nil
  wsmarks = scan_indexes(search_str, /(?<=[^\p{Word}])\p{Word}/)
  wsmarks = wsmarks.collect { |x| x + startpos }
  return wsmarks
end

#handle_drag_and_drop(fname) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/vimamsa/buffer.rb', line 315

def handle_drag_and_drop(fname)
  debug "[buffer] Dropped file: #{fname}"
  if is_image_file(fname)
    debug "Dropped image file"
    insert_image_after_current_line(fname)
  elsif file_is_text_file(fname)
    debug "Dropped text file"
    open_new_file(fname)
  else
    debug "Dropped unknown file format"
  end
  # add_image(imgpath, pos)
end

#handle_line_actionObject

Activated when enter/return pressed



1073
1074
1075
1076
1077
1078
1079
1080
1081
# File 'lib/vimamsa/buffer.rb', line 1073

def handle_line_action()
  if line_action_handler.class == Proc or line_action_handler.class == Method
    # Custom handler
    line_action_handler.call(lpos)
  else
    # Generic default action
    cur_nonwhitespace_word_action()
  end
end

#handle_word(wnfo) ⇒ Object



1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
# File 'lib/vimamsa/buffer.rb', line 1016

def handle_word(wnfo)
  word = wnfo[0]
  wtype = wnfo[1]
  if wtype == :url
    open_url(word)
  elsif wtype == :linepointer
    jump_to_file(word[0], word[1], word[2])
  elsif wtype == :textfile
    open_existing_file(word)
  elsif wtype == :file
    open_with_default_program(word)
  elsif wtype == :hpt_link
    open_existing_file(word)
  elsif wtype == :help
    if word == "keybindings"
      call_action(:show_key_bindings)
    end
  else
    #TODO
  end
end

#increment_current_wordObject



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/vimamsa/buffer_changetext.rb', line 189

def increment_current_word()
  debug "increment_current_word", 2
  p = @pos
  return if !is_legal_pos(p)
  (word, range) = get_word_in_pos(p, boundary: :word2)
  if word.match(/(true|false)/i)
    rep = flip_true_false(word)
  else
    num = word.to_i
    num += 1
    rep = num.to_s
  end
  debug [word, range].to_s, 2
  replace_range(range, rep)
end

#indentObject

TODO: rename ot auto-format. separate module? Indents whole buffer using external program



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
# File 'lib/vimamsa/buffer_changetext.rb', line 42

def indent()
  file = Tempfile.new("out")
  infile = Tempfile.new("in")
  file.write(self.to_s)
  file.flush
  bufc = "FOO"

  tmppos = @pos

  message("Auto format #{@fname}")

  ftype = get_file_type()
  if ["chdr", "c", "cpp", "cpphdr"].include?(ftype)

    #C/C++/Java/JavaScript/Objective-C/Protobuf code
    system("clang-format -style='{BasedOnStyle: LLVM, ColumnLimit: 100,  SortIncludes: false}' #{file.path} > #{infile.path}")
    bufc = IO.read(infile.path)
  elsif ftype == "Javascript"
    cmd = "clang-format #{file.path} > #{infile.path}'"
    debug cmd
    system(cmd)
    bufc = IO.read(infile.path)
  elsif ftype == "ruby"
    cmd = "rufo #{file.path}"
    debug cmd
    system(cmd)
    bufc = IO.read(file.path)
  else
    message("No auto-format handler for file of type: #{ftype}")
    return
  end
  self.update_content(bufc)
  center_on_current_line #TODO: needed?
  file.close; file.unlink
  infile.close; infile.unlink
end

#init_encrypted(crypt:, filename:, encrypted:) ⇒ Object



343
344
345
346
347
348
# File 'lib/vimamsa/buffer.rb', line 343

def init_encrypted(crypt:, filename:, encrypted:)
  @crypt = crypt
  @encrypted_str = encrypted
  set_filename(filename)
  gui_set_buffer_contents(@id, self.to_s)
end

#init_lspObject



132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/vimamsa/buffer.rb', line 132

def init_lsp()
  if cnf.lsp.enabled?
    @lsp = LangSrv.get(@lang)

    if @lang == "php"
      # Ripl.start :binding => binding
    end
  end

  if !@lsp.nil?
    @lsp.open_file(@fname, self.to_s)
  end
end

#insert_image_after_current_line(fname) ⇒ Object



333
334
335
336
337
338
339
340
341
342
# File 'lib/vimamsa/buffer_changetext.rb', line 333

def insert_image_after_current_line(fname)
  lr = current_line_range()
  a = "⟦img:#{fname}⟧\n"
  b = " \n"
  txt = a + b
  insert_txt_at(txt, lr.end + 1)
  buf.view.handle_deltas
  imgpos = lr.end + 1 + a.size
  add_image(fname, imgpos)
end

#insert_new_lineObject



1205
1206
1207
1208
1209
1210
# File 'lib/vimamsa/buffer.rb', line 1205

def insert_new_line()
  s = get_current_line
  $hook.call(:insert_new_line, s)
  insert_txt("\n")
  # message("foo")
end

#insert_tabObject



319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/vimamsa/buffer_changetext.rb', line 319

def insert_tab
  convert = cnf.tab.to_spaces_default?
  convert = true if cnf.tab.to_spaces_languages?.include?(@lang)
  convert = false if cnf.tab.to_spaces_not_languages?.include?(@lang)
  tw = cnf.tab.width!
  if convert
    indent_to = (@cpos / tw) * tw + tw
    indentdiff = indent_to - @cpos
    insert_txt(" " * indentdiff)
  else
    insert_txt("\t")
  end
end

#insert_txt(c, mode = BEFORE) ⇒ Object



1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
# File 'lib/vimamsa/buffer.rb', line 1212

def insert_txt(c, mode = BEFORE)
  # start_profiler
  #Sometimes we get ASCII-8BIT although actually UTF-8  "incompatible character encodings: UTF-8 and ASCII-8BIT (Encoding::CompatibilityError)"
  c = c.force_encoding("UTF-8");  #TODO:correct?

  c = "\n" if c == "\r"
  if cnf.indent_based_on_last_line? and c == "\n" and @lpos > 0
    # Indent start of new line based on last line
    last_line = line(@lpos)
    m = /^( +)([^ ]+|$)/.match(last_line)
    if m
      c = c + " " * m[1].size if m
    end

    #if tab indent
    m = /^(\t+)([^\t]+|$)/.match(last_line)
    if m
      c = c + "\t" * m[1].size if m
    end

    # debug m.inspect
  end
  if mode == BEFORE
    insert_pos = @pos
    @pos += c.size
  elsif mode == AFTER
    insert_pos = @pos + 1
  else
    return
  end

  #self.insert(insert_pos,c)
  add_delta([insert_pos, INSERT, c.size, c], true)
  #debug("encoding: #{c.encoding}")
  #debug "c.size: #{c.size}"
  #recalc_line_ends #TODO: optimize?
  calculate_line_and_column_pos
  #need_redraw!
  #@pos += c.size
  # end_profiler
end

#insert_txt_at(c, pos) ⇒ Object



1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/vimamsa/buffer.rb', line 1183

def insert_txt_at(c, pos)
  if c.nil? or pos.nil?
    error("input c=nil || pos=nil")
    return
  end
  c = c.force_encoding("UTF-8");  #TODO:correct?
  c = "\n" if c == "\r"
  add_delta([pos, INSERT, c.size, c], true)
  calculate_line_and_column_pos
end

#is_active?Boolean

Check if this buffer is attached to any windows

Returns:

  • (Boolean)


80
81
82
83
84
85
86
# File 'lib/vimamsa/buffer.rb', line 80

def is_active?
  for k in vma.gui.windows.keys
    next if vma.gui.windows[k][:sw].child.nil?
    return true if vma.gui.windows[k][:sw].child.bufo == self
  end
  return false
end

#is_delta_ok(delta) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/vimamsa/buffer_changetext.rb', line 287

def is_delta_ok(delta)
  ret = true
  pos = delta[0]
  if pos < 0
    ret = false
    debug "pos=#{pos} < 0"
  elsif pos > self.size
    debug "pos=#{pos} > self.size=#{self.size}"
    ret = false
  end
  if ret == false
    # crash("DELTA OK=#{ret}")
  end
  return ret
end


110
111
112
113
114
115
116
117
118
# File 'lib/vimamsa/buffer_cursor.rb', line 110

def is_legal_pos(pos, op = :read)
  return false if pos < 0
  if op == :add
    return false if pos > self.size
  elsif op == :read
    return false if pos >= self.size
  end
  return true
end

#join_linesObject



1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
# File 'lib/vimamsa/buffer.rb', line 1160

def join_lines()
  if @lpos >= @line_ends.size - 1 # Cursor is on last line
    debug("ON LAST LINE")
    return
  else
    # TODO: replace all whitespace between lines with ' '
    jump(END_OF_LINE)
    delete(CURRENT_CHAR_FORWARD)
    #insert_txt(' ',AFTER)
    insert_txt(" ", BEFORE)
  end
end

#jump(target) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/vimamsa/buffer_cursor.rb', line 232

def jump(target)
  if target == START_OF_BUFFER
    set_pos(0)
  end
  if target == END_OF_BUFFER
    set_pos(self.size - 1)
  end
  if target == BEGINNING_OF_LINE
    @cpos = 0
    calculate_pos_from_cpos_lpos
  end
  if target == END_OF_LINE
    @cpos = line(@lpos).size - 1
    calculate_pos_from_cpos_lpos
  end

  if target == FIRST_NON_WHITESPACE
    l = current_line()
    debug l.inspect
    @cpos = line(@lpos).size - 1
    a = scan_indexes(l, /\S/)
    debug a.inspect
    if a.any?
      @cpos = a[0]
    else
      @cpos = 0
    end
    calculate_pos_from_cpos_lpos
  end
end

#jump_to_last_editObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/vimamsa/buffer_cursor.rb', line 120

def jump_to_last_edit()
  return if @edit_pos_history.empty?
  @edit_pos_history_i += 1

  if @edit_pos_history_i > @edit_pos_history.size
    @edit_pos_history_i = 0
  end

  #        if @edit_pos_history.size >= @edit_pos_history_i
  set_pos(@edit_pos_history[-@edit_pos_history_i])
  center_on_current_line
  return true
  #        end
end

#jump_to_line(line_n = 1) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/vimamsa/buffer_cursor.rb', line 263

def jump_to_line(line_n = 1)

  #    $method_handles_repeat = true
  #    if !$next_command_count.nil? and $next_command_count > 0
  #        line_n = $next_command_count
  #        debug "jump to line:#{line_n}"
  #    end
  debug "jump to line:#{line_n}"
  line_n = get_repeat_num() if line_n == 1

  if line_n > @line_ends.size
    debug("lpos too large") #TODO
    return
  end
  if line_n == 1
    set_pos(0)
  else
    set_pos(@line_ends[line_n - 2] + 1)
  end
end

#jump_to_mark(mark_char) ⇒ Object



225
226
227
228
229
230
# File 'lib/vimamsa/buffer_cursor.rb', line 225

def jump_to_mark(mark_char)
  p = @marks[mark_char]
  set_pos(p) if p
  center_on_current_line
  return true
end

#jump_to_next_editObject



135
136
137
138
139
140
141
142
143
# File 'lib/vimamsa/buffer_cursor.rb', line 135

def jump_to_next_edit()
  return if @edit_pos_history.empty?
  @edit_pos_history_i -= 1
  @edit_pos_history_i = @edit_pos_history.size - 1 if @edit_pos_history_i < 0
  debug "@edit_pos_history_i=#{@edit_pos_history_i}"
  set_pos(@edit_pos_history[-@edit_pos_history_i])
  center_on_current_line
  return true
end

#jump_to_next_instance_of_char(char, direction = FORWARD) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/vimamsa/buffer_cursor.rb', line 284

def jump_to_next_instance_of_char(char, direction = FORWARD)
  if direction == FORWARD
    position_of_next_char = self.index(char, @pos + 1)
    if position_of_next_char != nil
      @pos = position_of_next_char
    end
  elsif direction == BACKWARD
    start_search = @pos - 250
    start_search = 0 if start_search < 0
    search_substr = self[start_search..(@pos - 1)]
    _pos = search_substr.reverse.index(char)
    if _pos != nil
      @pos -= (_pos + 1)
    end
  end
  m = method("jump_to_next_instance_of_char")
  set_last_command({ method: m, params: [char, direction] })
  $last_find_command = { char: char, direction: direction }
  set_pos(@pos)
  return true
end

#jump_to_next_instance_of_wordObject



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
# File 'lib/vimamsa/buffer_cursor.rb', line 149

def jump_to_next_instance_of_word()
  if vma.kbd.last_action == vma.kbd.cur_action and @current_word != nil
    # debug "REPEATING *"
  else
    start_search = [@pos - 150, 0].max

    search_str1 = self[start_search..(@pos)]
    wsmarks = scan_indexes(search_str1, /(?<=[^\p{Word}])\p{Word}/)
    a = wsmarks[-1]
    a = 0 if a == nil

    search_str2 = self[(@pos)..(@pos + 150)]
    wemarks = scan_indexes(search_str2, /(?<=\p{Word})[^\p{Word}]/)
    b = wemarks[0]
    word_start = (@pos - search_str1.size + a + 1)
    word_start = 0 if !(word_start >= 0)
    @current_word = self[word_start..(@pos + b - 1)]
  end

  #TODO: search for /[^\p{Word}]WORD[^\p{Word}]/
  position_of_next_word = self.index(@current_word, @pos + 1)
  if position_of_next_word != nil
    set_pos(position_of_next_word)
  else #Search from beginning
    position_of_next_word = self.index(@current_word)
    set_pos(position_of_next_word) if position_of_next_word != nil
  end
  center_on_current_line
  return true
end

#jump_to_pos(new_pos) ⇒ Object



306
307
308
# File 'lib/vimamsa/buffer_cursor.rb', line 306

def jump_to_pos(new_pos)
  set_pos(new_pos)
end

#jump_to_random_posObject



145
146
147
# File 'lib/vimamsa/buffer_cursor.rb', line 145

def jump_to_random_pos()
  set_pos(rand(self.size))
end

#jump_word(direction, wordpos) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/vimamsa/buffer_cursor.rb', line 180

def jump_word(direction, wordpos)
  offset = 0
  if direction == FORWARD
    debug "POS: #{@pos},"
    search_str = self[(@pos)..(@pos + 250)]
    return if search_str == nil
    if wordpos == WORD_START # vim 'w'
      wsmarks = scan_indexes(search_str, /(?<=[^\p{Word}])\p{Word}|\Z/) # \Z = end of string, just before last newline.
      wsmarks2 = scan_indexes(search_str, /\n[ \t]*\n/) # "empty" lines that have whitespace
      wsmarks2 = wsmarks2.collect { |x| x + 1 }
      wsmarks = (wsmarks2 + wsmarks).sort.uniq
      offset = 0
      if wsmarks.any?
        next_pos = @pos + wsmarks[0] + offset
        set_pos(next_pos)
      end
    elsif wordpos == WORD_END
      search_str = self[(@pos + 1)..(@pos + 150)]
      wsmarks = scan_indexes(search_str, /(?<=\p{Word})[^\p{Word}]/)
      offset = -1
      if wsmarks.any?
        next_pos = @pos + 1 + wsmarks[0] + offset
        set_pos(next_pos)
      end
    end
  end
  if direction == BACKWARD #  vim 'b'
    start_search = @pos - 150 #TODO 150 length limit
    start_search = 0 if start_search < 0
    search_str = self[start_search..(@pos - 1)]
    return if search_str == nil
    wsmarks = scan_indexes(search_str,
                           #/(^|(\W)\w|\n)/) #TODO 150 length limit
                           #/^|(?<=[^\p{Word}])\p{Word}|(?<=\n)\n/) #include empty lines?
                           /\A|(?<=[^\p{Word}])\p{Word}/) # Start of string or nonword,word.

    offset = 0

    if wsmarks.any?
      next_pos = start_search + wsmarks.last + offset
      set_pos(next_pos)
    end
  end
end

#line(lpos) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/vimamsa/buffer_cursor.rb', line 3

def line(lpos)
  if @line_ends.size == 0
    return self
  end

  #TODO: implement using line_range()
  if lpos >= @line_ends.size
    debug("lpos too large") #TODO
    return ""
  elsif lpos == @line_ends.size
  end
  start = @line_ends[lpos - 1] + 1 if lpos > 0
  start = 0 if lpos == 0
  _end = @line_ends[lpos]
  debug "start: _#{start}, end: #{_end}"
  return self[start.._end]
end

#line_range(start_line, num_lines, include_last_nl = true) ⇒ Object



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/vimamsa/buffer.rb', line 734

def line_range(start_line, num_lines, include_last_nl = true)
  end_line = start_line + num_lines - 1
  if end_line >= @line_ends.size
    debug("lpos too large") #TODO
    end_line = @line_ends.size - 1
  end
  start = @line_ends[start_line - 1] + 1 if start_line > 0
  start = 0 if start_line == 0
  if include_last_nl
    _End = @line_ends[end_line]
  else
    _End = @line_ends[end_line] - 1
  end
  _End = start if _End < start
  debug "line range: start=#{start}, end=#{_End}"
  return start.._End
end

#list_strObject



70
71
72
73
74
75
76
77
# File 'lib/vimamsa/buffer.rb', line 70

def list_str()
  if @fname.nil?
    x = @title
  else
    x = @fname
  end
  return x
end

#load_autosave_callback(x) ⇒ Object



1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
# File 'lib/vimamsa/buffer.rb', line 1677

def load_autosave_callback(x)
  if x["yes_btn"] == "submit"
    str = read_file("", autosave_path)
    set_content(str)
    @t_modified = Time.now
    refresh_title
    message("Loaded autosave for #{@fname}")
  elsif x["delete_btn"] == "submit"
    delete_autosave_file
    message("Deleted autosave for #{@fname}")
  end
end

#lsp_get_defObject



114
115
116
117
118
119
# File 'lib/vimamsa/buffer.rb', line 114

def lsp_get_def()
  if !@lsp.nil?
    fpuri = URI.join("file:///", @fname).to_s
    @lsp.get_definition(fpuri, @lpos, @cpos)
  end
end

#lsp_jump_to_defObject



121
122
123
124
125
126
127
128
129
130
# File 'lib/vimamsa/buffer.rb', line 121

def lsp_jump_to_def()
  message("LSP not activated") if @lsp.nil?
  if !@lsp.nil?
    fpuri = URI.join("file:///", @fname).to_s
    r = @lsp.get_definition(fpuri, @lpos, @cpos)
    if !r.nil?
      jump_to_file(r[0], r[1])
    end
  end
end

#mark_current_position(mark_char) ⇒ Object



980
981
982
# File 'lib/vimamsa/buffer.rb', line 980

def mark_current_position(mark_char)
  @marks[mark_char] = @pos
end

#move(direction) ⇒ Object



910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
# File 'lib/vimamsa/buffer.rb', line 910

def move(direction)
  debug "cpos:#{@cpos} lpos:#{@lpos} @larger_cpos:#{@larger_cpos}"
  if direction == :forward_page
    debug "FORWARD PAGE"
    visible_range = get_visible_area()
    set_pos(visible_range[1])
    top_where_cursor()
  end
  if direction == :backward_page
    debug "backward PAGE"
    visible_range = get_visible_area()
    set_pos(visible_range[0])
    bottom_where_cursor()
  end

  if direction == FORWARD_CHAR
    return if @pos >= self.size - 1
    set_pos(@pos + 1)
  end
  if direction == BACKWARD_CHAR
    set_pos(@pos - 1)
  end
  if direction == FORWARD_LINE
    if @lpos >= @line_ends.size - 1 # Cursor is on last line
      debug("ON LAST LINE")
      return
    else
      @lpos += 1
    end
  end
  if direction == BACKWARD_LINE
    if @lpos == 0 # Cursor is on first line
      return
    else
      @lpos -= 1
    end
  end

  if direction == FORWARD_CHAR or direction == BACKWARD_CHAR
    reset_larger_cpos
  end

  if direction == BACKWARD_LINE or direction == FORWARD_LINE
    if @lpos > 0
      new_pos = @line_ends[@lpos - 1] - 1
    else
      new_pos = 0
    end

    _line = self.line(@lpos)
    if @cpos > (_line.size - 1)
      debug("$cpos too large: #{@cpos} #{@lpos}")
      if @larger_cpos < @cpos
        @larger_cpos = @cpos
      end
      @cpos = line(@lpos).size - 1
    end

    if @larger_cpos > @cpos and @larger_cpos < (_line.size)
      @cpos = @larger_cpos
    elsif @larger_cpos > @cpos and @larger_cpos >= (_line.size)
      @cpos = line(@lpos).size - 1
    end

    #new_pos += @cpos
    #@pos = new_pos
    calculate_pos_from_cpos_lpos(false)
  end
end

#need_redraw!Object



1285
1286
1287
# File 'lib/vimamsa/buffer.rb', line 1285

def need_redraw!
  @need_redraw = true
end

#need_redraw?Boolean

Returns:

  • (Boolean)


1289
1290
1291
# File 'lib/vimamsa/buffer.rb', line 1289

def need_redraw?
  return @need_redraw
end

#new_undo_groupObject

Flush @current_group into @edit_history and start a new group. Called on mode changes, macro boundaries, and time threshold.



567
568
569
570
571
572
# File 'lib/vimamsa/buffer.rb', line 567

def new_undo_group
  if @current_group.any?
    @edit_history << @current_group
    @current_group = []
  end
end

#paste(at = AFTER, register = nil) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/vimamsa/buffer_changetext.rb', line 175

def paste(at = AFTER, register = nil)
  # Macro's don't work with asynchronous call using GTK
  # TODO: implement as synchronous?
  # Use internal clipboard
  if vma.macro.running_macro
    text = vma.clipboard.get()
    paste_finish(text, at, register)
  else
    # Get clipboard using GUI
    paste_start(at, register)
  end
  return true
end

#paste_finish(text, at, register, overwrite: false) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/vimamsa/buffer_changetext.rb', line 117

def paste_finish(text, at, register, overwrite: false)
  debug "PASTE: #{text}"

  # If we did not put this text to clipboard
  if text != vma.clipboard[-1]
    @paste_lines = false
  end

  text = sanitize_input(text)

  vma.clipboard << text

  return if text == ""

  cursor_at_start = cnf.paste.cursor_at_start!

  if overwrite && !@paste_lines
    # Delete as many chars forward as we are about to insert, stopping before newline
    line_end = current_line_range.last - 1  # position of last char before \n
    n = [text.size, [line_end - @pos + 1, 0].max].min
    add_delta([@pos, DELETE, n], true) if n > 0
    insert_txt_at(text, @pos)
    set_pos(cursor_at_start ? @pos : @pos + text.size - 1)
  elsif @paste_lines
    debug "PASTE LINES"
    if at == BEFORE
      l = current_line_range()
      insert_txt_at(text, l.begin)
      set_pos(l.begin)
    else
      put_to_new_next_line(text)
      set_pos(@pos) if cursor_at_start
    end
  else
    debug "PASTE !LINES"
    if at_end_of_buffer? or at_end_of_line? or at == BEFORE
      pos = @pos
    else
      pos = @pos + 1
    end
    insert_txt_at(text, pos)
    set_pos(cursor_at_start ? pos : pos + text.size)
  end
  set_pos(@pos)
  vma.buf.view.after_action # redraw
  @clipboard_paste_running = false
end

#paste_over(at = AFTER, register = nil) ⇒ Object



165
166
167
168
169
170
171
172
173
# File 'lib/vimamsa/buffer_changetext.rb', line 165

def paste_over(at = AFTER, register = nil)
  if vma.macro.running_macro
    text = vma.clipboard.get()
    paste_finish(text, at, register, overwrite: true)
  else
    paste_start(at, register, overwrite: true)
  end
  return true
end

#paste_start(at, register, overwrite: false) ⇒ Object

Start asynchronous read of system clipboard



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/vimamsa/buffer_changetext.rb', line 97

def paste_start(at, register, overwrite: false)
  @clipboard_paste_running = true

  # if true or running_wayland? and !GLib::Version::or_later?(2, 79, 0)
    # return paste_start_xclip(at, register)
  # end

  clipboard = vma.gui.window.display.clipboard
  clipboard.read_text_async do |_clipboard, result|
    begin
      text = clipboard.read_text_finish(result)
    rescue Gio::IOError::NotSupported
      debug Gio::IOError::NotSupported
    else
      paste_finish(text, at, register, overwrite: overwrite)
    end
  end
  return nil
end

#paste_start_xclip(at, register) ⇒ Object



87
88
89
90
91
92
93
94
# File 'lib/vimamsa/buffer_changetext.rb', line 87

def paste_start_xclip(at, register)
  @clipboard_paste_running = true
  Thread.new {
    text = `xclip -selection c -o`
    GLib::Idle.add { paste_finish(text, at, register); false }
  }
  return nil
end

#put_file_path_to_clipboardObject



1416
1417
1418
# File 'lib/vimamsa/buffer.rb', line 1416

def put_file_path_to_clipboard
  vma.clipboard.set(self.fname)
end

#put_file_ref_to_clipboardObject



1420
1421
1422
# File 'lib/vimamsa/buffer.rb', line 1420

def put_file_ref_to_clipboard
  vma.clipboard.set(self.fname + ":#{@lpos}")
end

#put_to_new_next_line(txt) ⇒ Object

Create a new line after current line and insert text on that line



80
81
82
83
84
# File 'lib/vimamsa/buffer_changetext.rb', line 80

def put_to_new_next_line(txt)
  l = current_line_range()
  insert_txt_at(txt, l.end + 1)
  set_pos(l.end + 1)
end

#recalc_line_endsObject



761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/vimamsa/buffer.rb', line 761

def recalc_line_ends()
  t1 = Time.now
  leo = @line_ends.clone
  @line_ends = scan_indexes(self, /\n/)
  if @line_ends == leo
    debug "No change to line ends"
  else
    debug "CHANGES to line ends"
  end

  debug "Scan line_end time: #{Time.now - t1}"
  #debug @line_ends
end

#redoObject



592
593
594
595
596
597
598
599
# File 'lib/vimamsa/buffer.rb', line 592

def redo()
  return if @redo_stack.empty?
  group = @redo_stack.pop
  group.each { |d| run_delta(d) }
  @edit_history << group
  set_pos(group.last[0])
  calculate_line_and_column_pos
end

#refresh_cursorObject



29
30
31
# File 'lib/vimamsa/buffer_cursor.rb', line 29

def refresh_cursor
  self.view.set_cursor_pos(@pos)
end

#refresh_titleObject



1582
1583
1584
1585
1586
1587
1588
# File 'lib/vimamsa/buffer.rb', line 1582

def refresh_title
  if vma.buf == self
    pfx = ""
    pfx = "+ " if vma.buf.unsaved_changes?
    gui_set_window_title(pfx + vma.buf.title, vma.buf.subtitle)
  end
end

#replace_range(range, text) ⇒ Object



216
217
218
219
# File 'lib/vimamsa/buffer_changetext.rb', line 216

def replace_range(range, text)
  delete_range(range.first, range.last)
  insert_txt_at(text, range.begin)
end

#replace_with_char(char) ⇒ Object



1173
1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/vimamsa/buffer.rb', line 1173

def replace_with_char(char)
  debug "self_pos:'#{self[@pos]}'"
  return if self[@pos] == "\n"
  d1 = [@pos, DELETE, 1]
  d2 = [@pos, INSERT, 1, char]
  add_delta(d1, true)
  add_delta(d2, true)
  debug "DELTAS:#{self.deltas.inspect} "
end

#reset_audio_widget_positionsObject

TODO: remove?



225
226
227
228
229
230
231
232
# File 'lib/vimamsa/buffer.rb', line 225

def reset_audio_widget_positions
  debug "reset_audio_widget_positions", 2
  for mc in @audiofiles
    mc.set_size_request(500, 20)
    mc.set_margin_start(view.gutter_width + 10)
  end
  return false
end

#reset_larger_cposObject



906
907
908
# File 'lib/vimamsa/buffer.rb', line 906

def reset_larger_cpos()
  @larger_cpos = @cpos
end

#restore_kbd_modeObject

Restore the previous keyboard mode specific to this buffer



103
104
105
# File 'lib/vimamsa/buffer.rb', line 103

def restore_kbd_mode
  vma.kbd.set_mode_stack(@mode_stack.clone)
end

#revertObject



333
334
335
336
337
338
339
340
341
# File 'lib/vimamsa/buffer.rb', line 333

def revert()
  return if !@fname
  return if !File.exist?(@fname)
  message("Revert buffer #{@fname}")
  str = read_file("", @fname)
  self.set_content(str)
  @last_save = Time.now
  refresh_title
end

#run_delta(delta, auto_update_cpos = false) ⇒ Object



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/vimamsa/buffer.rb', line 467

def run_delta(delta, auto_update_cpos = false)
  # auto_update_cpos: In some cases position of cursor should be updated automatically based on change to buffer (delta). In other cases this is handled by the action that creates the delta.

  # delta[0]: char position
  # delta[1]: INSERT or DELETE
  # delta[2]: number of chars affected
  # delta[3]: text to add in case of insert

  @version += 1
  if cnf.btree.experimental?
    @bt.handle_delta(Delta.new(delta[0], delta[1], delta[2], delta[3]))
  end

  if !@lsp.nil?
    dc = delta.clone
    dc[3] = "" if dc[3].nil?
    dc[4] = get_line_and_col_pos(delta[0])
    dc[5] = get_line_and_col_pos(delta[0] + delta[2])
    @lsp.handle_delta(dc, @fname, @version)
  end
  pos = delta[0]
  if @edit_pos_history.any? and (@edit_pos_history.last - pos).abs <= 2
    @edit_pos_history.pop
  end

  lsp = get_line_start(pos)

  if @edit_pos_history[-1] != lsp
    @edit_pos_history << lsp
  end
  @edit_pos_history_i = 0

  if delta[1] == DELETE
    delta[3] = self.slice!(delta[0], delta[2])
    cleanup_deleted_images(delta[3])
    @deltas << delta
    update_index(pos, -delta[2])
    update_line_ends(pos, -delta[2], delta[3])
    update_highlights(pos, -delta[2], delta[3])
    update_cursor_pos(pos, -delta[2]) if auto_update_cpos

    @update_hl_startpos = pos - delta[2]
    @update_hl_endpos = pos
    add_hl_update(@update_hl_startpos, @update_hl_endpos)
  elsif delta[1] == INSERT
    self.insert(delta[0], delta[3])
    @deltas << delta
    debug [pos, +delta[2]].inspect
    update_index(pos, +delta[2])
    update_cursor_pos(pos, +delta[2]) if auto_update_cpos
    update_line_ends(pos, +delta[2], delta[3])
    update_highlights(pos, +delta[2], delta[3])

    @update_hl_startpos = pos
    @update_hl_endpos = pos + delta[2]
    add_hl_update(@update_hl_startpos, @update_hl_endpos)

    if delta[3]&.include?("⟦img:")
      buf_ref = self
      run_as_idle proc { hpt_scan_images(buf_ref) }
    end
  end
  debug("DELTA=#{delta.inspect}", 2)
  # sanity_check_line_ends #TODO: enable with debug mode
  #highlight_c()

  @update_highlight = true

  return delta
end

#sanity_check_line_endsObject



775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/vimamsa/buffer.rb', line 775

def sanity_check_line_ends()
  leo = @line_ends.clone
  @line_ends = scan_indexes(self, /\n/)
  if @line_ends == leo
    debug "No change to line ends"
  else
    debug "CHANGES to line ends"
    debug leo.inspect
    debug @line_ends.inspect
    crash("CHANGES to line ends")
  end
end

#sanitycheck_btreeObject



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/vimamsa/buffer.rb', line 350

def sanitycheck_btree()
  # lines = self.split("\n")

  lines = self.scan(/([^\n]*\n)/).flatten

  i = 0
  ok = true
  @bt.each_line { |r|
    if lines[i] != r #or true
      debug "NO MATCH FOR LINE:"
      debug "i=#{i}["
      # debug "[orig]pos=#{leaf.pos} |#{leaf.data}|"
      # debug "spos=#{spos} nchar=#{leaf.nchar} epos=#{epos} a[]=\nr=|#{r}|"
      debug "fromtree:|#{r}|"
      debug "frombuf:|#{lines[i]}"
      debug "]"
      ok = false
    end
    i += 1
  }

  debug "BT: NO ERRORS" if ok
  debug "BT: ERRORS" if !ok
end

#saveObject



1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
# File 'lib/vimamsa/buffer.rb', line 1690

def save()
  check_if_modified_outside #TODO
  if !@fname
    save_as()
    return
  end
  message("Saving file #{@fname}")
  write_contents_to_file(@fname)
  delete_autosave_file
  hook.call(:file_saved, self)
end

#save_asObject



1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
# File 'lib/vimamsa/buffer.rb', line 1481

def save_as()
  debug "save_as"
  savepath = ""

  # If current file has fname, save to that fname
  # Else search for previously opened files and save to the directory of
  # the last viewed file that has a filename
  # selffers[$buffer_history.reverse[1]].fname

  if @fname
    savepath = File.dirname(@fname)
  else
    savepath = buflist.get_last_dir
  end
  gui_file_saveas(savepath)
  # calls back to file_saveas
end

#save_as_callback(fpath, confirmed = false) ⇒ Object



1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
# File 'lib/vimamsa/buffer.rb', line 1505

def save_as_callback(fpath, confirmed = false)
  # The check if file exists is handled by Gtk::FileChooserDialog in GTK4
  # Keeping this code from GTK3 in case want to do this manually at some point
  # if !confirmed
  # @unconfirmed_path = fpath
  # if File.exist?(fpath) and File.file?(fpath)
  # params = {}
  # params["title"] = "The file already exists, overwrite? \r #{fpath}"
  # params["inputs"] = {}
  # params["inputs"]["yes_btn"] = { :label => "Yes", :type => :button, :default_focus => true }
  # callback = proc { |x| save_as_check_callback(x) }
  # params[:callback] = callback
  # PopupFormGenerator.new(params).run
  # return
  # elsif File.exist?(fpath) #and File.directory?(fpath)
  # params = {}
  # params["title"] = "Can't write to the destination.\r #{fpath}"
  # params["inputs"] = {}
  # params["inputs"]["ok_btn"] = { :label => "Ok", :type => :button, :default_focus => true }
  # PopupFormGenerator.new(params).run
  # return
  # end
  # end

  set_filename(fpath)
  save()
  gui_set_window_title(@title, @subtitle) #TODO: if not active buffer?
end

#save_as_check_callback(vals) ⇒ Object



1499
1500
1501
1502
1503
# File 'lib/vimamsa/buffer.rb', line 1499

def save_as_check_callback(vals)
  if vals["yes_btn"] == "submit"
    save_as_callback(@unconfirmed_path, true)
  end
end

#scan_all_wordsObject



234
235
236
237
# File 'lib/vimamsa/buffer.rb', line 234

def scan_all_words
  words = self.scan(/\b\w+\b/).uniq
  return words
end

#scan_marks(startpos, endpos, regstr, offset = 0) ⇒ Object



1006
1007
1008
1009
1010
1011
1012
1013
1014
# File 'lib/vimamsa/buffer.rb', line 1006

def scan_marks(startpos, endpos, regstr, offset = 0)
  startpos = 0 if startpos < 0
  endpos = self.size if endpos > self.size
  search_str = self[(startpos)..(endpos)]
  return if search_str == nil
  marks = scan_indexes(search_str, regstr)
  marks = marks.collect { |x| x + startpos + offset }
  return marks
end

#selection_active?Boolean

Returns:

  • (Boolean)


1297
1298
1299
# File 'lib/vimamsa/buffer.rb', line 1297

def selection_active?
  @selection_active
end

#selection_startObject



1468
1469
1470
1471
# File 'lib/vimamsa/buffer.rb', line 1468

def selection_start()
  return -1 if !@visual_mode
  return @selection_start if @visual_mode
end

#set_activeObject

This function is to be called whenever keyboard events start affecting this buffer e.g. switching between buffers, opening a new (this) file



94
95
96
97
98
99
100
# File 'lib/vimamsa/buffer.rb', line 94

def set_active
  debug "def set_active", 2
  if vma.kbd.get_scope != :editor
    # If current keyboard mode is not an editor wide mode spanning multiple buffers(e.g. browsing)
    restore_kbd_mode
  end
end

#set_content(str) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/vimamsa/buffer.rb', line 375

def set_content(str)
  @encrypted_str = nil
  @gui_update_highlight = true
  @ftype = nil

  if (str[-1] != "\n")
    str << "\n"
  end

  self.replace(str)
  @line_ends = scan_indexes(self, /\n/)
  words = scan_all_words
  Autocomplete.add_words(words)

  if cnf.btree.experimental?
    @bt = BufferTree.new(self)
    if cnf.debug?
      sanitycheck_btree()
    end
  end

  @last_update = Time.now - 10
  debug("line_ends")
  @marks = Hash.new
  @basename = ""
  @pathname = Pathname.new(fname) if @fname
  @basename = @pathname.basename if @fname
  @pos = 0 # Position in whole file
  @cpos = 0 # Column position on current line
  @lpos = 0 # Number of current line
  @edit_version = 0 # +1 for every buffer modification
  @larger_cpos = 0 # Store @cpos when move up/down to shorter line than @cpos
  @need_redraw = 1
  @call_func = nil
  @deltas = []
  @edit_history = []   # Array of groups: [[delta, ...], ...]
  @current_group = []  # In-progress undo group
  @last_delta_time = nil
  @macro_group_active = false
  @redo_stack = []
  @edit_pos_history = []
  @edit_pos_history_i = 0
  # @highlights = {}
  @highlights.delete_if { |x| true }

  @syntax_parser = nil

  @is_highlighted = false
  @update_highlight = true
  @update_hl_startpos = 0 #TODO
  @update_hl_endpos = self.size - 1

  gui_set_buffer_contents(@id, self.to_s)
  @images = [] #TODO: if reload
  hpt_scan_images(self)

  # add_hl_update(@update_hl_startpos, @update_hl_endpos)
end

#set_encrypted(password) ⇒ Object



292
293
294
295
# File 'lib/vimamsa/buffer.rb', line 292

def set_encrypted(password)
  @crypt = Encrypt.new(password)
  message("Set buffer encrypted")
end

#set_executableObject



107
108
109
110
111
112
# File 'lib/vimamsa/buffer.rb', line 107

def set_executable
  if File.exist?(@fname)
    FileUtils.chmod("+x", @fname)
    message("Set executable: #{@fname}")
  end
end

#set_filename(filename) ⇒ Object



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/vimamsa/buffer.rb', line 434

def set_filename(filename)
  debug "set_filename(filename) #{filename}"
  @fname = filename
  @title = "*#{@prefix}-#{@id}*"
  return if @fname.nil?
  @pathname = Pathname.new(fname) if @fname
  @basename = @pathname.basename if @fname

  @title = File.basename(@fname)
  @dirname = File.dirname(@fname)
  userhome = File.expand_path("~")
  @subtitle = @fname.gsub(/^#{userhome}/, "~")
  vma.buffers.last_dir = @dirname

  detect_file_language
  gui_set_window_title(@title, @subtitle)
end

#set_line_and_column_pos(lpos, cpos, _reset_larger_cpos = true) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/vimamsa/buffer_cursor.rb', line 79

def set_line_and_column_pos(lpos, cpos, _reset_larger_cpos = true)
  @lpos = lpos if !lpos.nil?
  @cpos = cpos if !cpos.nil?
  if @lpos > 0
    new_pos = @line_ends[@lpos - 1] + 1
  else
    new_pos = 0
  end

  if @cpos > (line(@lpos).size - 1)
    debug("$cpos too large: #{@cpos} #{@lpos}")
    if @larger_cpos < @cpos
      @larger_cpos = @cpos
    end
    @cpos = line(@lpos).size - 1
  end
  new_pos += @cpos
  set_pos(new_pos)
  reset_larger_cpos if _reset_larger_cpos
end

#set_line_style(op) ⇒ Object



1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
# File 'lib/vimamsa/buffer.rb', line 1386

def set_line_style(op)
  lrange = line_range(@lpos, 1, false)
  txt = self[lrange]
  # txt = "◼ " + txt if op == :heading
  txt = "" + txt + "" if op == :bold
  txt = "" + txt + "" if op == :title
  txt.gsub!(//, "") if op == :clear
  txt.gsub!(/[❙◼⟦⟧⦁]/, "") if op == :clear or [:h1, :h2, :h3, :h4].include?(op)

  if [:h1, :h2, :h3, :h4].include?(op)
    txt.strip!
    txt = "" + txt if op == :h1
    txt = "◼◼ " + txt if op == :h2
    txt = "◼◼◼ " + txt if op == :h3
    txt = "◼◼◼◼ " + txt if op == :h4
  end
  replace_range(lrange, txt)
end

#set_pos(new_pos) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/vimamsa/buffer_cursor.rb', line 33

def set_pos(new_pos)
  # If user interacts with the buffer, we consider that the buffer has been accessed
  # And navigation has ended
  if new_pos != @pos
    update_access_time
    bufs.reset_navigation
  end
  if new_pos >= self.size
    @pos = self.size - 1 # TODO:??right side of last char
  elsif new_pos >= 0
    @pos = new_pos
  end

  self.view.set_cursor_pos(pos)
  # gui_set_cursor_pos(@id, @pos)
  calculate_line_and_column_pos

  check_if_modified_outside
end

#set_redrawedObject



1293
1294
1295
# File 'lib/vimamsa/buffer.rb', line 1293

def set_redrawed
  @need_redraw = false
end

#set_unencryptedObject



297
298
299
# File 'lib/vimamsa/buffer.rb', line 297

def set_unencrypted()
  @crypt = nil
end

#start_autosave_timerObject



1641
1642
1643
1644
1645
1646
1647
1648
# File 'lib/vimamsa/buffer.rb', line 1641

def start_autosave_timer
  @autosave_thread = Thread.new {
    loop do
      sleep AUTOSAVE_INTERVAL
      autosave
    end
  }
end

#start_selectionObject



1309
1310
1311
1312
1313
# File 'lib/vimamsa/buffer.rb', line 1309

def start_selection()
  @selection_start = @pos
  @selection_active = true
  @visual_mode = true #TODO: change use of @visual_mode into @selection_active
end

#style_transform(op) ⇒ Object



1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
# File 'lib/vimamsa/buffer.rb', line 1372

def style_transform(op)
  return if !@visual_mode
  r = get_visual_mode_range
  #TODO: if txt[-1]=="\n"
  txt = self[r]
  txt = "" + txt + "" if op == :bold
  txt = "" + txt + "" if op == :link
  txt = "" + txt + "" if op == :title
  txt.gsub!(/[❙◼⟦⟧⦁]/, "") if op == :clear

  replace_range(r, txt)
  end_visual_mode
end

#transform_selection(op) ⇒ Object



1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
# File 'lib/vimamsa/buffer.rb', line 1337

def transform_selection(op)
  return if !@visual_mode
  r = get_visual_mode_range
  txt = self[r]
  txt.upcase! if op == :upcase
  txt.downcase! if op == :downcase
  txt.gsub!(/\w+/, &:capitalize) if op == :capitalize
  txt.swapcase! if op == :swapcase
  txt.reverse! if op == :reverse
  txt = to_camel_case(txt) if op == :camelcase

  replace_range(r, txt)
  end_visual_mode
end

#uncomment_linerange(r) ⇒ Object



702
703
704
705
706
707
708
# File 'lib/vimamsa/buffer.rb', line 702

def uncomment_linerange(r)
  com_str = get_com_str()
  #r=self.line_range(self.lpos, 2)
  lines = self[r].split(/(\n)/).each_slice(2).map { |x| x[0] }
  mod = lines.collect { |x| x.sub(/^(\s*)(#{com_str}\s?)/, '\1') + "\n" }.join()
  replace_range(r, mod)
end

#undoObject



582
583
584
585
586
587
588
589
590
# File 'lib/vimamsa/buffer.rb', line 582

def undo()
  new_undo_group  # flush any in-progress group first
  return if @edit_history.empty?
  group = @edit_history.pop
  @redo_stack << group
  group.reverse_each { |d| apply_inverse_delta(d) }
  set_pos(group.first[0])
  calculate_line_and_column_pos
end

#unindentObject



301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/vimamsa/buffer.rb', line 301

def unindent
  debug("unindent", 2)
  cnf.tab.width!.times {
    p = @pos - 1
    if p >= 0
      if self[p] == " "
        delete(BACKWARD_CHAR)
      end
    else
      break
    end
  }
end

#unsaved_changes?Boolean

Returns:

  • (Boolean)


1576
1577
1578
1579
1580
# File 'lib/vimamsa/buffer.rb', line 1576

def unsaved_changes?
  pp [@t_modified, @last_save]
  return true if @t_modified > @last_save
  return false
end

#update_access_timeObject



88
89
90
# File 'lib/vimamsa/buffer.rb', line 88

def update_access_time
  @access_time = Time.now
end

#update_bufpos_on_change(positions, xpos, changeamount) ⇒ Object



788
789
790
791
792
793
794
795
796
797
# File 'lib/vimamsa/buffer.rb', line 788

def update_bufpos_on_change(positions, xpos, changeamount)
  # debug "xpos=#{xpos} changeamount=#{changeamount}"
  positions.collect { |x|
    r = nil
    r = x if x < xpos
    r = x + changeamount if changeamount < 0 && x + changeamount >= xpos
    r = x + changeamount if changeamount > 0 && x >= xpos
    r
  }
end

#update_content(newstr) ⇒ Object

Update buffer contents to newstr Change by taking diff of old/new content



1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
# File 'lib/vimamsa/buffer.rb', line 1256

def update_content(newstr)
  diff = Differ.diff_by_char(newstr, self.to_s)

  da = diff.get_raw_array

  pos = 0
  posA = 0
  posB = 0
  deltas = []

  for x in da
    if x.class == String
      posA += x.size
      posB += x.size
    elsif x.class == Differ::Change
      if x.insert?
        deltas << [posB, INSERT, x.insert.size, x.insert.clone]
        posB += x.insert.size
      elsif x.delete?
        posA += x.delete.size
        deltas << [posB, DELETE, x.delete.size]
      end
    end
  end
  for d in deltas
    add_delta(d, true, true)
  end
end

#update_cursor_pos(pos, changeamount) ⇒ Object

Update cursor position after change in buffer contents. e.g. after processing with external command like indenter



540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/vimamsa/buffer.rb', line 540

def update_cursor_pos(pos, changeamount)
  if @pos > pos + 1 && changeamount > 0
    # @pos is after addition
    set_pos(@pos + changeamount)
  elsif @pos > pos && changeamount < 0 && @pos < pos - changeamount
    # @pos is between removal
    set_pos(pos)
  elsif @pos > pos && changeamount < 0 && @pos >= pos - changeamount
    # @pos is after removal
    set_pos(@pos + changeamount)
  end
end

#update_highlights(pos, changeamount, changestr) ⇒ Object



799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/vimamsa/buffer.rb', line 799

def update_highlights(pos, changeamount, changestr)
  return if !self.is_highlighted
  lpos, cpos = get_line_and_col_pos(pos)
  if @highlights and @highlights[lpos]
    hl = @highlights[lpos]
    hls = hl.collect { |x| x[0] } # highlight range start
    hle = hl.collect { |x| x[1] } # highlight range end
    hls2 = update_bufpos_on_change(hls, cpos, changeamount)
    hle2 = update_bufpos_on_change(hle, cpos, changeamount)
    hlnew = []
    for i in hle.size.times
      if hls2[i] != nil and hle2[i] != nil
        hlnew << [hls2[i], hle2[i], hl[i][2]]
      end
    end
    @highlights[lpos] = hlnew
  end
end

#update_index(pos, changeamount) ⇒ Object



553
554
555
556
557
558
559
560
561
562
563
# File 'lib/vimamsa/buffer.rb', line 553

def update_index(pos, changeamount)
  # debug "pos #{pos}, changeamount #{changeamount}, @pos #{@pos}"
  @edit_pos_history.collect! { |x| r = x if x <= pos; r = x + changeamount if x > pos; r }
  # TODO: handle between removal case
  for k in @marks.keys
    #            debug "change(?): pos=#{pos}, k=#{k}, #{@marks[k]}, #{changeamount}"
    if @marks[k] > pos
      @marks[k] = @marks[k] + changeamount
    end
  end
end

#update_line_ends(pos, changeamount, changestr) ⇒ Object



818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
# File 'lib/vimamsa/buffer.rb', line 818

def update_line_ends(pos, changeamount, changestr)
  if changeamount > -1
    changeamount = changestr.size
    i_nl = scan_indexes(changestr, /\n/)
    i_nl.collect! { |x| x + pos }
  end
  #    debug "change:#{changeamount}"
  #TODO: this is the bottle neck in insert_txt action
  @line_ends.collect! { |x|
    r = nil
    r = x if x < pos
    r = x + changeamount if changeamount < 0 && x + changeamount >= pos
    r = x + changeamount if changeamount > 0 && x >= pos
    r
  }.compact!

  if changeamount > -1 && i_nl.size > 0
    @line_ends.concat(i_nl)
    @line_ends.sort!
  end
end

#update_pos(pos) ⇒ Object



105
106
107
108
# File 'lib/vimamsa/buffer_cursor.rb', line 105

def update_pos(pos)
  @pos = pos
  calculate_line_and_column_pos
end

#valueObject



1477
1478
1479
# File 'lib/vimamsa/buffer.rb', line 1477

def value()
  return self.to_s
end

#viewObject



175
176
177
178
# File 'lib/vimamsa/buffer.rb', line 175

def view()
  # Get the VSourceView < GtkSource::View object corresponding to this buffer
  return vma.gui.buffers[@id]
end

#visual_mode?Boolean

Returns:

  • (Boolean)


1473
1474
1475
# File 'lib/vimamsa/buffer.rb', line 1473

def visual_mode?()
  return @visual_mode
end

#write_contents_to_file(fpath) ⇒ Object



1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
# File 'lib/vimamsa/buffer.rb', line 1534

def write_contents_to_file(fpath)
  if @crypt != nil
    mode = "wb+"
    contents = "VMACRYPT001" + @crypt.encrypt(self.to_s)
  else
    mode = "w+"
    contents = self.to_s
  end

  Thread.new {
    begin
      io = File.open(fpath, mode)
      io.set_encoding(self.encoding)
      io.write(contents)
      io.close
    rescue Encoding::UndefinedConversionError => ex
      puts "Encoding::UndefinedConversionError"
      # this might happen when trying to save UTF-8 as US-ASCII
      # so just warn, try to save as UTF-8 instead.
      warn("Saving as UTF-8 because of: #{ex.class}: #{ex}")
      io.rewind

      io.set_encoding(Encoding::UTF_8)
      io.write(contents)
    rescue Errno::EACCES => ex
      message("File #{fpath} not writeable")
      #TODO: show message box
    end
    @last_save = Time.now
    refresh_title
    debug "file saved on #{@last_save}"
    sleep 3
  }
end