Module: Kitabu::Base

Extended by:
Base
Included in:
Base
Defined in:
lib/kitabu/base.rb

Constant Summary collapse

DEFAULT_LAYOUT =
'boom'
DEFAULT_THEME =
'eiffel'
DEFAULT_SYNTAX =
'plain_text'
DEFAULT_MARKDOWN_PROCESSOR =
'rdiscount'
GEM_ROOT =
File.expand_path(File.dirname(__FILE__) + "/../../")

Instance Method Summary collapse

Instance Method Details

#app_nameObject



188
189
190
# File 'lib/kitabu/base.rb', line 188

def app_name
  ENV['KITABU_NAME'] || 'kitabu'
end

#configObject



31
32
33
# File 'lib/kitabu/base.rb', line 31

def config
  @config = YAML::load_file(config_path)
end

#config_pathObject



23
24
25
# File 'lib/kitabu/base.rb', line 23

def config_path
  KITABU_ROOT + "/config.yml"
end

#default_layoutObject



212
213
214
# File 'lib/kitabu/base.rb', line 212

def default_layout
  DEFAULT_LAYOUT
end

#default_markdown_processorObject



216
217
218
# File 'lib/kitabu/base.rb', line 216

def default_markdown_processor
  DEFAULT_MARKDOWN_PROCESSOR
end

#default_syntaxObject



208
209
210
# File 'lib/kitabu/base.rb', line 208

def default_syntax
  DEFAULT_SYNTAX
end

#default_themeObject



204
205
206
# File 'lib/kitabu/base.rb', line 204

def default_theme
  DEFAULT_THEME
end

#generate_htmlObject



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
124
125
126
127
128
129
130
131
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/kitabu/base.rb', line 77

def generate_html
  # parsed file holder
  contents = ""
  
  entries = Dir.entries(text_dir).sort.reject do |entry| 
    %w(. .. .svn .git).include?(entry) || (File.file?(entry) && entry !~ /\.(markdown|textile)$/)
  end
  
  $stdout << "\nNo markup files found!\n" if entries.empty?
  
  # first, get all chapters; then, get all parsed markdown
  # files from this chapter and group them into a <div class="chapter"> tag
  entries.each do |entry|
    # gets all parsed markdown files to wrap in a 
    # chapter element
    chapter = ""
    
    # entry can be a file outside chapter folder
    file = "#{text_dir}/#{entry}"
    
    if File.file?(file)
      markup_files = [file]
    else
      # merge all markdown and textile files into a single list
      markup_files =  Dir["#{text_dir}/#{entry}/**/*.markdown"] + 
                      Dir["#{text_dir}/#{entry}/**/*.textile"]
    end
    
    # no files, so skip it!
    next if markup_files.empty?
    
    markup_files.sort.each do |markup_file|
      # get the file contents
      markup_contents = File.read(markup_file)
      
      # instantiate a markup object
      begin
        if markup_file =~ /\.textile$/
          markup = BlackCloth.new(markup_contents)
          markup.no_span_caps = true
        else
          markup = markdown_processor_class.new(markup_contents)
        end
      rescue Exception => e
        $stdout << "\nSkipping #{markup_file} (#{e.message})"
        next
      end
      
      # convert the markup into html
      parsed_contents = markup.to_html
      
      if defined?(Uv)
        if markup.respond_to?(:syntax_blocks)
          # textile
          parsed_contents.gsub!(/@syntax:([0-9]+)/m) do |m|
            syntax, code = markup.syntax_blocks[$1.to_i]
            Kitabu::Markup.syntax(code, syntax, :textile)
          end
        else
          # markdown
          parsed_contents.gsub! /<pre><code>(.*?)<\/code><\/pre>/m do |block|
            code = $1.gsub(/&lt;/, '<').gsub(/&gt;/, '>').gsub(/&amp;/, '&')
            code_lines = StringIO.new(code).readlines
            syntax_settings = code_lines.first
          
            syntax = 'plain_text'
          
            if syntax_settings =~ /syntax\(.*?\)\./
              code = code_lines.slice(1, code_lines.size).join
            
              # syntax
              m, syntax = *syntax_settings.match(/syntax\(([^ #]+).*?\)./)
            
              # file name
              m, source_file = *syntax_settings.match(/syntax\(.*?\)\. +(.*?)$/)
            
              # get line interval
              m, from_line, to_line = *syntax_settings.match(/syntax\(.*? ([0-9]+),([0-9]+)\)/)
            
              # get block name
              m, block_name = *syntax_settings.match(/syntax\(.*?#([0-9a-z_]+)\)/)
            
              code = Kitabu::Markup.content_for({
                :code => code,
                :from_line => from_line,
                :to_line => to_line,
                :block_name => block_name,
                :source_file => source_file
              })
            end
          
            Kitabu::Markup.syntax(code, syntax, :markdown)
          end
        end
      end
      
      chapter << (parsed_contents + "\n\n")
    end
    
    contents << '<div class="chapter">%s</div>' % chapter
  end
  
  # create output directory if is missing
  FileUtils.mkdir(File.dirname(html_path)) unless File.exists?(File.dirname(html_path))
  
  # save html file
  File.open(html_path, 'w+') do |f|
    f << Kitabu::Base.parse_layout(contents)
  end
end

#generate_pdfObject



73
74
75
# File 'lib/kitabu/base.rb', line 73

def generate_pdf
  IO.popen('prince %s -o %s' % [html_path, pdf_path])
end

#html_pathObject



11
12
13
# File 'lib/kitabu/base.rb', line 11

def html_path
  KITABU_ROOT + "/output/#{app_name}.html"
end

#layout?(layout_name) ⇒ Boolean

Returns:

  • (Boolean)


200
201
202
# File 'lib/kitabu/base.rb', line 200

def layout?(layout_name)
  layouts.include?(layout_name)
end

#layoutsObject



237
238
239
240
241
242
# File 'lib/kitabu/base.rb', line 237

def layouts
  @layouts ||= begin
    dir = File.join(GEM_ROOT, "templates/layouts")
    Dir.entries(dir).reject{|p| p =~ /^\.+$/ }.sort
  end
end

#markdown_processorObject



220
221
222
# File 'lib/kitabu/base.rb', line 220

def markdown_processor
  config['markdown'] || default_markdown_processor
end

#markdown_processor_classObject



224
225
226
227
228
229
230
231
# File 'lib/kitabu/base.rb', line 224

def markdown_processor_class
  case markdown_processor
  when 'maruku' then Maruku
  when 'bluecloth' then BlueCloth
  when 'peg_markdown' then PEGMarkdown
  else RDiscount
  end
end

#parse_layout(contents) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/kitabu/base.rb', line 35

def parse_layout(contents)
  template = File.new(template_path).read
  contents, toc = self.table_of_contents(contents)
  cfg = config.merge(:contents => contents, :toc => toc)
  env = OpenStruct.new(cfg)

  ERB.new(template).result env.instance_eval{ binding }
end

#pdf_pathObject



15
16
17
# File 'lib/kitabu/base.rb', line 15

def pdf_path
  KITABU_ROOT + "/output/#{app_name}.pdf"
end

#syntax?(syntax_name) ⇒ Boolean

Returns:

  • (Boolean)


196
197
198
# File 'lib/kitabu/base.rb', line 196

def syntax?(syntax_name)
  syntaxes.include?(syntax_name)
end

#syntaxesObject



233
234
235
# File 'lib/kitabu/base.rb', line 233

def syntaxes
  Uv.syntaxes
end

#table_of_contents(contents) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/kitabu/base.rb', line 44

def table_of_contents(contents)
  return [contents, nil] unless defined?('Hpricot') && defined?('Unicode')
  
  doc = Hpricot(contents)
  counter = {}

  (doc/"h2, h3, h4, h5, h6").each do |node|
    title = node.inner_text
    permalink = Kitabu::Base.to_permalink(title)
    
    # initialize and increment counter
    counter[permalink] ||= 0
    counter[permalink] += 1
    
    # set a incremented permalink if more than one occurrence
    # is found
    permalink = "#{permalink}-#{counter[permalink]}" if counter[permalink] > 1
    
    node.set_attribute(:id, permalink)
  end
  
  contents = doc.to_html
  io = StringIO.new(contents)
  toc = Toc.new
  REXML::Document.parse_stream(io, toc) rescue nil

  [contents, toc.to_s]
end

#template_pathObject



19
20
21
# File 'lib/kitabu/base.rb', line 19

def template_path
  KITABU_ROOT + "/templates/layout.html"
end

#text_dirObject



27
28
29
# File 'lib/kitabu/base.rb', line 27

def text_dir
  KITABU_ROOT + "/text"
end

#theme?(theme_name) ⇒ Boolean

Returns:

  • (Boolean)


192
193
194
# File 'lib/kitabu/base.rb', line 192

def theme?(theme_name)
  themes.include?(theme_name)
end

#themesObject



244
245
246
247
248
249
# File 'lib/kitabu/base.rb', line 244

def themes
  @themes ||= begin
    filter = File.join(GEM_ROOT, "templates/themes/*.css")
    Dir[filter].collect{|path| File.basename(path).gsub(/\.css$/, '') }.sort
  end
end


251
252
253
254
255
256
# File 'lib/kitabu/base.rb', line 251

def to_permalink(str)
  str = Unicode.normalize_KD(str).gsub(/[^\x00-\x7F]/n,'') 
  str = str.gsub(/[^-_\s\w]/, ' ').downcase.squeeze(' ').tr(' ', '-')
  str = str.gsub(/-+/, '-').gsub(/^-+/, '').gsub(/-+$/, '')
  str
end