Module: Snibbets

Defined in:
lib/snibbets.rb,
lib/snibbets.rb,
lib/snibbets/os.rb,
lib/snibbets/hash.rb,
lib/snibbets/menu.rb,
lib/snibbets/array.rb,
lib/snibbets/colors.rb,
lib/snibbets/config.rb,
lib/snibbets/lexers.rb,
lib/snibbets/string.rb,
lib/snibbets/version.rb,
lib/snibbets/highlight.rb

Overview

Defined Under Namespace

Modules: Color, Highlight, Lexers, Menu, OS Classes: Config

Constant Summary collapse

VERSION =
'2.0.40'

Class Method Summary collapse

Class Method Details

.argumentsObject



37
38
39
# File 'lib/snibbets.rb', line 37

def arguments
  @arguments = config.arguments
end

.change_query(query) ⇒ Object



45
46
47
# File 'lib/snibbets.rb', line 45

def change_query(query)
  @query = query
end

.configObject



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

def config
  @config ||= Config.new
end

.handle_launchbar(results) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/snibbets.rb', line 294

def handle_launchbar(results)
  output = []

  if results.empty?
    out = {
      "title" => "No matching snippets found",
    }.to_json
    puts out
    Process.exit
  end

  results.each do |result|
    input = IO.read(result["path"])
    snippets = input.snippets
    next if snippets.empty?

    children = []

    if snippets.length == 1
      output << {
        "title" => result["title"],
        "path" => result["path"],
        "action" => "copyIt",
        "actionArgument" => snippets[0]["code"],
        "label" => "Copy",
      }
      next
    end

    snippets.each { |s|
      children << {
        "title" => s["title"],
        "path" => result["path"],
        "action" => "copyIt",
        "actionArgument" => s["code"],
        "label" => "Copy",
      }
    }

    output << {
      "title" => result["title"],
      "path" => result["path"],
      "children" => children,
    }
  end

  puts output.to_json
end

.handle_results(results) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/snibbets.rb', line 343

def handle_results(results)
  if Snibbets.options[:launchbar]
    handle_launchbar(results)
  else
    filepath = nil
    if results.empty?
      warn "No results" if Snibbets.options[:interactive]
      Process.exit 0
    elsif results.length == 1 || !Snibbets.options[:interactive]
      filepath = results[0]["path"]
      input = IO.read(filepath)
    else
      answer = Snibbets::Menu.menu(results, title: "Select a file")
      filepath = answer["path"]
      input = IO.read(filepath)
    end

    if Snibbets.arguments[:edit_snippet]
      open_snippet_in_editor(filepath)
      Process.exit 0
    end

    if Snibbets.arguments[:nvultra]
      open_snippet_in_nvultra(filepath)
      Process.exit 0
    end

    snippets = input.snippets

    if snippets.empty?
      warn "No snippets found" if Snibbets.options[:interactive]
      Process.exit 0
    elsif snippets.length == 1 || !Snibbets.options[:interactive]
      if Snibbets.options[:output] == "json"
        print(snippets.to_json, filepath)
      else
        snippets.each do |snip|
          header = File.basename(filepath, ".md")
          if $stdout.isatty
            puts "{bw}#{header}{x}".x
            puts "{dw}#{"-" * header.length}{x}".x
            puts ""
          end
          code = snip["code"]
          lang = snip["language"]

          print(code, filepath, lang)
        end
      end
    elsif snippets.length > 1
      if Snibbets.options[:all]
        print_all(snippets, filepath)
      else
        select_snippet(snippets, filepath)
      end
    end
  end
end

.new_snippet_from_clipboardObject



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
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/snibbets.rb', line 164

def new_snippet_from_clipboard
  return false unless $stdout.isatty

  trap("SIGINT") do
    Howzit.console.info "\nCancelled"
    exit!
  end

  pb = OS.paste.outdent
  reader = TTY::Reader.new

  begin
    input = reader.read_line("{by}What does this snippet do{bw}? ".x).strip
    title = input unless input.empty?

    input = reader.read_line("{by}What language(s) does it use ({xw}separate with spaces, full names or file extensions{by}){bw}? ".x).strip
    langs = input.split(/ +/).map(&:strip) unless input.empty?
  rescue TTY::Reader::InputInterrupt
    puts "\nCancelled"
    Process.exit 1
  end

  exts = langs.map { |lang| Lexers.lang_to_ext(lang) }.delete_if(&:nil?)
  tags = langs.map { |lang| Lexers.ext_to_lang(lang) }.concat(langs).delete_if(&:nil?).sort.uniq

  exts = langs if exts.empty?

  filename = "#{title}#{exts.map { |x| ".#{x}" }.join("")}.#{Snibbets.options[:extension]}"
  filepath = File.join(File.expand_path(Snibbets.options[:source]), filename.escape_filename)
  File.open(filepath, "w") do |f|
    f.puts "tags: #{tags.join(", ")}

```
#{pb}
```"
  end

  puts "{bg}New snippet written to {bw}#{filename}.".x

  open_snippet_in_editor(filepath) if Snibbets.arguments[:edit_snippet]
  open_snippet_in_nvultra(filepath) if Snibbets.arguments[:nvultra]
end

.new_snippet_with_editor(options) ⇒ Object



207
208
209
210
211
212
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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/snibbets.rb', line 207

def new_snippet_with_editor(options)
  return false unless $stdout.isatty

  trap("SIGINT") do
    Howzit.console.info "\nCancelled"
    exit!
  end

  reader = TTY::Reader.new
  if options[:filename]
    title = options[:filename].sub(/(\.#{Snibbets.options[:extension]})$/, "")
    extensions = options[:filename].match(/(\.\w+)+$/)
    langs = extensions ? extensions[0].split(/\./).delete_if(&:empty?) : []
    title.sub!(/(\.\w+)+$/, "")
  else
    begin
      input = reader.read_line("{by}What does this snippet do{bw}? ".x).strip
      title = input unless input.empty?
    rescue TTY::Reader::InputInterrupt
      puts "\nCancelled"
      Process.exit 1
    end
  end

  if langs.nil? || langs.empty?
    begin
      # printf 'What language(s) does it use (separate with spaces, full names or file extensions will work)? '
      input = reader.read_line("{by}What language(s) does it use ({xw}separate with spaces, full names or file extensions{by}){bw}? ".x).strip
      # input = $stdin.gets.chomp
      langs = input.split(/ +/).map(&:strip) unless input.empty?
    rescue TTY::Reader::InputInterrupt
      puts "\nCancelled"
      Process.exit 1
    end
  end

  exts = langs.map { |lang| Lexers.lang_to_ext(lang) }.delete_if(&:nil?)
  tags = langs.map { |lang| Lexers.ext_to_lang(lang) }.concat(langs).delete_if(&:nil?).sort.uniq

  exts = langs if exts.empty?

  filename = "#{title}#{exts.map { |x| ".#{x}" }.join("")}.#{Snibbets.options[:extension]}"
  filepath = File.join(File.expand_path(Snibbets.options[:source]), filename.escape_filename)

  output = <<~EOOUTPUT
    tags: #{tags.join(", ")}

    > #{title}
  EOOUTPUT

  if langs.count.positive?
    tags.each do |lang|
      comment = case lang
        when /(c|cpp|objectivec|java|javascript|dart|php|golang|typescript|kotlin)/
          "// Code"
        else
          "# Code"
        end

      output << <<~EOLANGS

        ```#{lang}
        #{comment}
        ```
      EOLANGS
    end
  else
    output << <<~EOCODE
      ```LANG
      ```
    EOCODE
  end

  File.open(filepath, "w") do |f|
    f.puts output
  end

  puts "{bg}New snippet written to {bw}#{filename}.".x

  if Snibbets.arguments[:nvultra]
    sleep 2
    open_snippet_in_nvultra(filepath)
  else
    open_snippet_in_editor(filepath)
  end
end

.open_snippet_in_editor(filepath) ⇒ Object



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

def open_snippet_in_editor(filepath)
  editor = Snibbets.options[:editor] || Snibbets::Config.best_editor

  os = RbConfig::CONFIG["target_os"]

  if editor.nil?
    OS.open(filepath)
  else
    if os =~ /darwin.*/i
      if editor =~ /^TextEdit/
        `open -a TextEdit "#{filepath}"`
      elsif TTY::Which.bundle_id?(editor)
        `open -b "#{editor}" "#{filepath}"`
      elsif TTY::Which.app?(editor)
        `open -a "#{editor}" "#{filepath}"`
      elsif TTY::Which.exist?(editor)
        editor = TTY::Which.which(editor)
        system %(#{editor} "#{filepath}") if editor
      else
        puts "{br}No editor configured, or editor is missing".x
        Process.exit 1
      end
    elsif TTY::Which.exist?(editor)
      editor = TTY::Which.which(editor)
      system %(#{editor} "#{filepath}") if editor
    else
      puts "{br}No editor configured, or editor is missing".x
      Process.exit 1
    end
  end
end

.open_snippet_in_nvultra(filepath) ⇒ Object



125
126
127
128
129
130
# File 'lib/snibbets.rb', line 125

def open_snippet_in_nvultra(filepath)
  notebook = Snibbets.options[:source].gsub(/ /, "%20")
  note = ERB::Util.url_encode(File.basename(filepath, ".md"))
  url = "x-nvultra://open?notebook=#{notebook}&note=#{note}"
  `open '#{url}'`
end

.optionsObject



33
34
35
# File 'lib/snibbets.rb', line 33

def options
  @options = config.options
end


450
451
452
453
454
455
456
457
458
459
460
# File 'lib/snibbets.rb', line 450

def print(output, filepath, syntax = nil)
  if Snibbets.options[:copy]
    OS.copy(Snibbets.options[:all_notes] ? output : output.clean_code)
    warn "Copied to clipboard"
  end
  if Snibbets.options[:highlight] && Snibbets.options[:output] == "raw"
    $stdout.puts(Highlight.highlight(output, filepath, syntax))
  else
    $stdout.puts(Snibbets.options[:all_notes] ? output : output.clean_code)
  end
end


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

def print_all(snippets, filepath)
  if Snibbets.options[:output] == "json"
    print(snippets.to_json, filepath)
  else
    snippets.each do |snippet|
      lang = snippet["language"]

      puts "{dw}### {xbw}#{snippet["title"]} {xdw}### {x}".x
      puts ""

      print(snippet["code"], filepath, lang)
      puts
    end
  end
end

.search(try: 0, matches: []) ⇒ Object

Search the snippets directory for query using find and grep



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/snibbets.rb', line 50

def search(try: 0, matches: [])
  folder = File.expand_path(Snibbets.options[:source])
  # start by doing a spotlight search with mdfind
  # next try only search by filenames (find)
  # next try search with grep (rg, ag, ack, grep)
  # concatenate results from each search, removing duplicates and sorting
  ext = Snibbets.options[:extension] || "md"

  cmd = case try
    when 1
      %(find "#{folder}" -iregex '^#{Regexp.escape(folder)}/#{@query.rx}' -name '*.#{ext}')
    when 2
      rg = TTY::Which.which("rg")
      ag = TTY::Which.which("ag")
      ack = TTY::Which.which("ack")
      grep = TTY::Which.which("grep")
      if !rg.empty?
        %(#{rg} -li --color=never --glob='*.#{ext}' '#{@query.rx}' "#{folder}")
      elsif !ag.empty?
        %(#{ag} -li --nocolor -G '.*.#{ext}' '#{@query.rx}' "#{folder}")
      elsif !ack.empty?
        %(#{ack} -li --nocolor --markdown '#{@query.rx}' "#{folder}")
      elsif !grep.empty?
        %(#{grep} -iEl '#{@query.rx}' "#{folder}"/**/*.#{ext})
      else
        nil
      end
    else
      mdfind = TTY::Which.which("mdfind")
      if mdfind.nil? || mdfind.empty?
        nil
      else
        name_only = Snibbets.options[:name_only] ? "-name " : ""
        %(mdfind -onlyin #{folder} #{name_only}'#{@query} name:.#{ext}' 2>/dev/null)
      end
    end

  if try == 2
    if Snibbets.options[:name_only]
      puts "{br}No name matches found".x
      Process.exit 1
    elsif cmd.nil?
      puts "{br}No search method available on this system. Please install ripgrep, silver surfer, ack, or grep.".x
      Process.exit 1
    end
  end

  res = cmd.nil? ? "" : `#{cmd}`.strip

  unless res.empty?
    lines = res.split(/\n/)
    lines.each do |l|
      matches << {
        "title" => File.basename(l, ".*"),
        "path" => l,
      }
    end

    matches.sort_by! { |a| a["title"] }.uniq!

    # return matches unless matches.empty?
  end

  matches.delete_if do |m|
    content = IO.read(m["path"])
    !content.match_all_tags(@query)
  end

  # return after 3 cycles
  return matches if try == 2

  # continue search, appends to current matches
  search(try: try + 1, matches: matches)
end

.select_snippet(snippets, filepath) ⇒ Object



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/snibbets.rb', line 402

def select_snippet(snippets, filepath)
  snippets.push({ "title" => "All snippets", "code" => "" })
  answer = Menu.menu(snippets.dup, filename: File.basename(filepath, ".md"), title: "Select snippet", query: @query)

  if answer["title"] == "All snippets"
    snippets.delete_if { |s| s["title"] == "All snippets" }
    if Snibbets.options[:output] == "json"
      print(snippets.to_json, filepath)
    else
      if $stdout.isatty
        header = File.basename(filepath, ".md")
        warn "{bw}#{header}{x}".x
        warn "{dw}#{"=" * header.length}{x}".x
        warn ""
      end
      print_all(snippets, filepath)
    end
  elsif Snibbets.options[:output] == "json"
    print(answer.to_json, filepath)
  else
    if $stdout.isatty
      header = "{bw}#{File.basename(filepath, ".md")}: {c}#{answer["title"]}{x}".x
      warn header
      warn "-" * header.length
      warn ""
    end
    code = answer["code"]
    lang = answer["language"]
    print(code, filepath, lang)
  end
end