Class: Macro

Inherits:
Object
  • Object
show all
Defined in:
lib/vimamsa/macro.rb

Constant Summary collapse

NAMED_MACROS_FILE =
"named_macros.json"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMacro

Returns a new instance of Macro.



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/vimamsa/macro.rb', line 31

def initialize()
  @recording = false
  @current_recording = []
  @current_name = nil
  @last_macro = "a"
  @running_macro = false

  @recorded_macros = vma.marshal_load("macros", {})
  @named_macros = load_named_macros
  vma.hook.register(:shutdown, self.method("save"))
end

Instance Attribute Details

#last_macroObject

Returns the value of attribute last_macro.



27
28
29
# File 'lib/vimamsa/macro.rb', line 27

def last_macro
  @last_macro
end

#named_macrosObject

Returns the value of attribute named_macros.



27
28
29
# File 'lib/vimamsa/macro.rb', line 27

def named_macros
  @named_macros
end

#recorded_macrosObject

Returns the value of attribute recorded_macros.



27
28
29
# File 'lib/vimamsa/macro.rb', line 27

def recorded_macros
  @recorded_macros
end

#recordingObject

Returns the value of attribute recording.



27
28
29
# File 'lib/vimamsa/macro.rb', line 27

def recording
  @recording
end

#running_macroObject (readonly)

Returns the value of attribute running_macro.



26
27
28
# File 'lib/vimamsa/macro.rb', line 26

def running_macro
  @running_macro
end

Instance Method Details

#delete_named_macro(name) ⇒ Object



101
102
103
104
105
# File 'lib/vimamsa/macro.rb', line 101

def delete_named_macro(name)
  @named_macros.delete(name)
  save_named_macros
  message("Macro '#{name}' deleted")
end

#dump_last_macroObject



207
208
209
210
211
# File 'lib/vimamsa/macro.rb', line 207

def dump_last_macro()
  puts "======MACRO START======="
  puts @recorded_macros[@last_macro].inspect
  puts "======MACRO END========="
end

#end_recordingObject



125
126
127
128
129
130
131
132
133
134
135
# File 'lib/vimamsa/macro.rb', line 125

def end_recording()
  if @recording == true
    @recorded_macros[@current_name] = @current_recording
    @last_macro = @current_name
    @current_name = @current_recording = nil
    @recording = false
    message("Stop recording macro [#{@last_macro}]")
  else
    message("Not recording macro")
  end
end

#find_macro_guiObject



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/vimamsa/macro.rb', line 83

def find_macro_gui()
  l = vma.macro.named_macros.keys.sort.collect { |x| [x, 0] }
  $macro_search_list = l
  $select_keys = ["h", "l", "f", "d", "s", "a", "g", "z"]

  delete_cb = proc { |name, refresh|
    Gui.confirm("Delete macro '#{name}'?", proc {
      vma.macro.delete_named_macro(name)
      refresh.call
    })
  }

  gui_select_update_window(l, $select_keys.collect { |x| x.upcase },
                           "gui_find_macro_select_callback",
                           "gui_find_macro_update_callback",
                           { delete_callback: delete_cb })
end

#gui_name_macroObject



77
78
79
80
81
# File 'lib/vimamsa/macro.rb', line 77

def gui_name_macro()
  callback = self.method("name_macro")
  # gui_one_input_action("Grep", "Search:", "grep", "grep_cur_buffer")
  gui_one_input_action("Name last macro", "Name:", "Set", callback)
end

#is_recordingObject



137
138
139
# File 'lib/vimamsa/macro.rb', line 137

def is_recording
  return @recording
end

#load_named_macrosObject

Load named macros from JSON. Falls back to Marshal data from older versions.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/vimamsa/macro.rb', line 56

def load_named_macros
  require "json"
  path = named_macros_path
  if File.exist?(path)
    data = JSON.parse(File.read(path))
    # JSON keys are always strings; action lists are arrays of strings — correct types
    return data
  end
  # Fallback: migrate from old Marshal-based storage
  vma.marshal_load("named_macros", {})
rescue => e
  error("Failed to load named macros: #{e}")
  {}
end

#name_macro(name, id = nil) ⇒ Object



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

def name_macro(name, id = nil)
  debug "NAME MACRO #{name}"
  id = @last_macro if id.nil?
  @named_macros[name] = @recorded_macros[id].clone
  save_named_macros
  message("Macro '#{name}' saved")
end

#named_macros_pathObject



43
44
45
# File 'lib/vimamsa/macro.rb', line 43

def named_macros_path
  get_dot_path(NAMED_MACROS_FILE)
end

#overwrite_current_action(eval_str) ⇒ Object

Allow method to specify the macro action instead of recording from keyboard input



152
153
154
155
156
# File 'lib/vimamsa/macro.rb', line 152

def overwrite_current_action(eval_str)
  if @recording
    @current_recording[-1] = eval_str
  end
end

#record_action(eval_str) ⇒ Object



141
142
143
144
145
146
147
148
149
# File 'lib/vimamsa/macro.rb', line 141

def record_action(eval_str)
  if @recording
    if eval_str == "repeat_last_action"
      @current_recording << $command_history.last
    else
      @current_recording << eval_str
    end
  end
end

#run_actions(acts) ⇒ Object

Run the provided list of actions



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/vimamsa/macro.rb', line 163

def run_actions(acts)
  acts = [acts] if acts.class != Array
  isok = true
  # if acts.kind_of?(Array) and acts.any?
  if acts.any?
    vma.buf&.new_undo_group
    vma.buf&.instance_variable_set(:@macro_group_active, true)
    @running_macro = true
    # TODO:needed?
    # set_last_command({ method: vma.macro.method("run_macro"), params: [name] })
    for a in acts
      ret = exec_action(a)
      if ret == false
        error "Error while running macro"
        isok = false
        break
      end

      vma.buf.view.after_action
      sleep cnf.macro.animation_delay!
    end
  end
  @running_macro = false
  vma.buf&.instance_variable_set(:@macro_group_active, false)
  vma.buf&.new_undo_group
  buf.set_pos(buf.pos)
  # TODO: Should be a better way to trigger this. Sometimes need to wait for GTK to process things before updating the cursor.
  run_as_idle proc { vma.buf.refresh_cursor; vma.buf.refresh_cursor }, delay: 0.15
  return isok
end

#run_last_macroObject



158
159
160
# File 'lib/vimamsa/macro.rb', line 158

def run_last_macro
  run_macro(@last_macro)
end

#run_macro(name) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/vimamsa/macro.rb', line 194

def run_macro(name)
  if vma.macro.is_recording == true
    message("Can't run a macro that runs a macro (recursion risk)")
    return false
  end
  message("Start running macro [#{name}]")
  if @recorded_macros.has_key?(name)
    @last_macro = name
  end
  acts = @recorded_macros[name]
  return run_actions(acts)
end

#saveObject



71
72
73
74
75
# File 'lib/vimamsa/macro.rb', line 71

def save()
  vma.marshal_save("macros", @recorded_macros)
  # named_macros are kept current via save_named_macros; save a Marshal copy as backup
  vma.marshal_save("named_macros", @named_macros)
end

#save_macro(name) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/vimamsa/macro.rb', line 213

def save_macro(name)
  m = @recorded_macros[name]
  return if !(m.kind_of?(Array) and m.any?)
  contents = m.join(";")
  dot_dir = File.expand_path("~/.config/.vimamsa")
  Dir.mkdir(dot_dir) unless File.exist?(dot_dir)
  save_fn = "#{dot_dir}/macro_#{name}.rb"

  Thread.new {
    File.open(save_fn, "w+") do |io|
      #io.set_encoding(self.encoding)

      begin
        io.write(contents)
      rescue Encoding::UndefinedConversionError => ex
        # 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)
      end
    end
    sleep 3 #TODO:remove
  }
end

#save_named_macrosObject

Save named macros as JSON immediately — called automatically after name_macro.



48
49
50
51
52
53
# File 'lib/vimamsa/macro.rb', line 48

def save_named_macros
  require "json"
  File.write(named_macros_path, JSON.pretty_generate(@named_macros))
rescue => e
  error("Failed to save named macros: #{e}")
end

#start_recording(name) ⇒ Object



115
116
117
118
119
120
121
122
123
# File 'lib/vimamsa/macro.rb', line 115

def start_recording(name)
  @recording = true
  @current_name = name
  @current_recording = []
  message("Start recording macro [#{name}]")

  # Returning false prevents from putting start_recording to start of macro
  return false
end