Skip to content

Instantly share code, notes, and snippets.

@gdsmith
Last active April 19, 2024 19:23
Show Gist options
  • Save gdsmith/10b7eefa413af7d1ba914fc5dffe44e9 to your computer and use it in GitHub Desktop.
Save gdsmith/10b7eefa413af7d1ba914fc5dffe44e9 to your computer and use it in GitHub Desktop.
Textmate command to find, create and add color marks for hex and rgb colors
#!/usr/bin/env ruby -wU
require 'erb'
# 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/"
box = ColorBox.new(dir)
Dir.glob("#{dir}*.eps") { | file |
%x{ \"$TM_MATE\" --clear-mark '#{file}' }
}
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])
%x{ \"$TM_MATE\" --line #{idx+1} --set-mark '#{box.save}' }
}
end
end
# fork and redirect output to log
pid = fork do
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)
@gdsmith
Copy link
Author

gdsmith commented Jun 2, 2016

Scope selector: source.css,source.scss,source.less
Save: nothing
Input: Document > Text
Output: Discard

To update on document load and save add:
Semantic Class: callback.document.did-save,callback.document.did-open

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment