Skip to content

Instantly share code, notes, and snippets.

@sorbits
Created February 15, 2017 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorbits/7e5631dc6f17d07926da162203f23261 to your computer and use it in GitHub Desktop.
Save sorbits/7e5631dc6f17d07926da162203f23261 to your computer and use it in GitHub Desktop.
Create new command and set scope selector to `source.css` and semantic class to `callback.document.did-open, callback.document.did-save`
#!/usr/bin/env ruby -wU
require 'erb'
require 'fileutils'
require 'shellwords'
# extension to String to extract colours into rgb array
class String
# hex to array
def h2a
if self.length == 4
self.scan(/[0-9A-Fa-f]/).
map {|i| (i*2).to_i(16) }
else
self.scan(/[0-9A-Fa-f]{2}/).
map {|i| i.to_i(16) }
end
end
# rgb to array
def rgb2a
self.gsub(/[\s\(\)rgba]/,'').
split(',')[0,3].
map{|c| c.to_i}
end
end
# extension to Array to divide all elements by 255
# to get decimal rgb value
class Array
def by255
self.map{|i| (i/255.0).round(4).to_s }
end
end
# template for
def get_template()
end
class ColorBox
include ERB::Util
attr_accessor :color, :dir
Template = %{
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 80 80
gsave 0 0 80 80 rectclip gsave
<%= @color.join(' ') %> setrgbcolor
10 10 70 70 rectfill
grestore grestore
}
def initialize(dir)
Dir.mkdir(dir, 0700) unless Dir.exist?(dir)
@dir = dir
end
# set color
def set_color(color)
@color = get_rgb_array(color)
end
# get array from color string
def get_rgb_array(c)
if c[0] == '#'
return c.h2a.by255
end
if c.match(/^rgb/)
return c.rgb2a.by255
end
end
# render the template
def render()
ERB.new(Template).result(binding)
end
# save the file in the given dir unless it exists
def save()
file = File.join(@dir, @color.join('-')+'.eps')
unless File.exists?(file.to_s)
File.open(file, "w+") do |f|
f.write(render)
end
end
return file.to_s
end
end
def markup
dir = "#{ENV['HOME']}/Library/Caches/com.macromates.textmate.colors/"
args = [ "--clear-mark=#{dir.shellescape}", "--uuid=#{ENV['TM_DOCUMENT_UUID']}" ]
box = ColorBox.new(dir)
ARGF.each_with_index do |line, idx|
line.scan(/(#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})(?=[^0-9A-Fa-f])|rgba{0,1}\([0-9]{1,3}[, ]+?[0-9]{1,3}[, ]+?[0-9]{1,3}[, 0-9\.]*?\))/) { |c|
box.set_color(c[0])
args << "--line=#{idx+1}" << "--set-mark=#{box.save.shellescape}"
}
end
system(ENV['TM_MATE'], *args)
end
# fork and redirect output to log
pid = fork do
FileUtils.mkdir_p("#{ENV['HOME']}/Library/Caches/com.macromates.textmate.colors")
STDOUT.reopen(open("#{ENV['HOME']}/Library/Caches/com.macromates.textmate.colors/log.txt", 'w'))
STDERR.reopen(open("#{ENV['HOME']}/Library/Caches/com.macromates.textmate.colors/err.txt", 'w'))
markup
end
Process.detach(pid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment