Skip to content

Instantly share code, notes, and snippets.

@bjmorgan
Created December 20, 2012 11:56
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 bjmorgan/4344886 to your computer and use it in GitHub Desktop.
Save bjmorgan/4344886 to your computer and use it in GitHub Desktop.
A Ruby TextExpander snippet that takes data copied to the clipboard from Numbers and pastes LaTeX source for a table environment. Discussed here: http://analysisandsynthesis.com/utilities/2012/12/20/quick-latex-tables-using-textexpander.html
#!/usr/local/bin/ruby
class Line
@@max_length = nil
@@eol = ' \\\\'
def initialize( data )
@contents = data
@@max_length = [0]*@contents.size if @@max_length.nil? # initialize array if this is the first Line instance
@contents.each_with_index{ |element, i| @@max_length[i] = [element.length, @@max_length[i]].max } # update column widths
end
def to_tex
@contents.zip( @@max_length ).collect { |entry, length| entry.ljust(length).sub(/\|/,' ').gsub('&','\\\&') }.join(' & ') + @@eol
end
def define_format
@contents.inject('|'){ |string, entry| /\|/.match(entry) ? string + 'c|' : string + 'c' } + '|'
end
end
table_header = <<END
\\begin{table}[htb]
\\begin{center}
\\begin{tabular}{FORMAT} \\hline
END
table_footer = <<END
\\hline
\\end{tabular}
\\caption{\\label{tab:NEW_LABEL}CAPTION}
\\end{center}
\\end{table}
END
contents = "%clipboard".split( /[\n\r]/ ).collect{ |line| Line.new( line.split( /\t/ ) )}
puts table_header.sub( 'FORMAT', contents[0].define_format )
puts contents.collect{ |line| line.to_tex }.join("\n")
puts table_footer
@mreiach
Copy link

mreiach commented Mar 7, 2013

I'm having issues getting this script going. I think I have it setup correctly in TextExpander: http://cl.ly/image/2t3d341B3y0r .

I have these numbers in Numbers: http://cl.ly/image/3R3q1D2v1H1d . When I copy them to the clipboard and use ':testable' as my snippet call, nothing is output. Any help would be greatly appreciated. Thanks.

@bjmorgan
Copy link
Author

@mreiach: Looks okay to me. What do you get as the output if you just run the snippet as a normal ruby executable? I get

\begin{table}[htb]
\begin{center}
\begin{tabular}{|c|} \aline
%clipboard \\
\hline
\end{tabular}
\caption{\label{tab:NEW_LABEL}CAPTION}
\end{center}
\end{table}

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