Class: HtmlTex

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

Overview

Converts HTML code to a TeX like syntax

Class Method Summary collapse

Class Method Details

.convert(html) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/html_tex.rb', line 5

def self.convert(html)
  tex = html
  # Convert tags that need to be opened and closed in TeX
  direct_conversions.each do |html_tag, tex_tag|
    tex = tex.gsub(/<\s*#{html_tag}{1}\b(\s[^>]*>|>)/i, "\\#{tex_tag}")
  end

  # Take care of tags which, in TeX, only need to be opened
  simple_conversions.each do |html_tag, tex_tag|
    tex = tex.gsub(/<\s*#{html_tag}{1}\b(\s[^>]*>|>)/i, "\\#{tex_tag} ")
    # Remove closing tags, if they exist
    tex = tex.gsub(/<\s*\/\s*#{html_tag}+>/i, '')
    tex = tex.gsub(/<\s*\/\s*#{html_tag}{1}\b(\s[^>]*>|>)/i, '')
  end

  # Create TeX environments
  environment_conversions.each do |html_tag, tex_tag|
    # Open environment
    tex = tex.gsub(/<\s*#{html_tag}{1}\b(\s[^>]*>|>)/i, "\\begin{#{tex_tag}}")
    # Close environment
    tex = tex.gsub(/<\s*\/\s*#{html_tag}{1}\b(\s[^>]*>|>)/i, "\\end{#{tex_tag}}")
  end

  # Close remaining tags
  tex = tex.gsub(/<\s*\/\s*([a-zA-Z]+)>/, '}')
  tex
end

.direct_conversionsObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/html_tex.rb', line 33

def self.direct_conversions
  {
    h1: 'part{',
    h2: 'chapter{',
    h3: 'section{',
    h4: 'subsection{',
    h5: 'subsubsection{',
    h6: 'textbf{',
    i: 'textit{',
    u: 'underline{',
    b: 'textbf{',
    strong: 'textbf{',
    br: '\\'
  }
end

.environment_conversionsObject



57
58
59
60
61
62
63
# File 'lib/html_tex.rb', line 57

def self.environment_conversions
  {
    ol: 'enumerate',
    ul: 'itemize',
    body: 'document'
  }
end

.simple_conversionsObject



49
50
51
52
53
54
55
# File 'lib/html_tex.rb', line 49

def self.simple_conversions
  {
    p: '\\',
    hr: 'hrule',
    li: 'item'
  }
end