utilities.rb 11.6 KB
Newer Older
Sylvester Keil's avatar
Sylvester Keil committed
1
module Jekyll
2
  class Scholar
3

Sylvester Keil's avatar
Sylvester Keil committed
4 5 6 7 8 9 10 11
    # Load styles into static memory.
    # They should be thread safe as long as they are
    # treated as being read-only.
    STYLES = Hash.new do |h, k|
      h[k.to_s] = CSL::Style.load k
    end


12
    # Utility methods used by several Scholar plugins. The methods in this
13
    # module may depend on the presence of #config, #bibtex_files, and
14 15
    # #site readers
    module Utilities
16

17
      attr_reader :config, :site, :context, :prefix, :text, :offset, :max
18 19 20 21 22 23 24 25 26 27

      def split_arguments(arguments)

        tokens = arguments.strip.split(/\s+/)

        args = tokens.take_while { |a| !a.start_with?('-') }
        opts = (tokens - args).join(' ')

        [args, opts]
      end
28 29

      def optparse(arguments)
30 31
        @offset = 0   # set default
        @max = -1     # set default
32 33 34 35 36 37 38
        return if arguments.nil? || arguments.empty?

        parser = OptionParser.new do |opts|
          opts.on('-c', '--cited') do |cited|
            @cited = true
          end

Sylvester Keil's avatar
Sylvester Keil committed
39 40 41 42
          opts.on('-C', '--cited_in_order') do |cited|
            @cited, @skip_sort = true, true
          end

Sylvester Keil's avatar
Sylvester Keil committed
43 44 45 46
          opts.on('-A', '--suppress_author') do |cited|
            @suppress_author = true
          end

47
          opts.on('-f', '--file FILE') do |file|
48 49
            @bibtex_files ||= []
            @bibtex_files << file
50 51 52 53 54 55 56 57 58 59 60 61 62
          end

          opts.on('-q', '--query QUERY') do |query|
            @query = query
          end

          opts.on('-p', '--prefix PREFIX') do |prefix|
            @prefix = prefix
          end

          opts.on('-t', '--text TEXT') do |text|
            @text = text
          end
63

64 65 66 67
          opts.on('-l', '--locator LOCATOR') do |locator|
            locators << locator
          end

68 69 70 71
          opts.on('-o', '--offset OFFSET') do |offset|
            @offset = offset.to_i
          end

Sylvester Keil's avatar
Sylvester Keil committed
72
          opts.on('-m', '--max MAX') do |max|
73
            @max = max.to_i
Sylvester Keil's avatar
Sylvester Keil committed
74 75
          end

76 77
          opts.on('-s', '--style STYLE') do |style|
            @style = style
78
          end
79 80 81 82

          opts.on('-T', '--template TEMPLATE') do |template|
            @bibliography_template = template
          end
83 84
        end

85
        argv = arguments.split(/(\B-[cCfqptTslomA]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|template|locator|offset|max|suppress_author|))/)
86 87 88

        parser.parse argv.map(&:strip).reject(&:empty?)
      end
89

90 91 92 93
      def locators
        @locators ||= []
      end

94 95 96 97 98 99 100 101 102
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

      # :nodoc: backwards compatibility
      def bibtex_file
        bibtex_files[0]
      end

103
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
104 105
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
106 107 108 109
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
110
      end
111

112 113 114 115 116 117 118
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
119
      def bibtex_path
120
        bibtex_paths[0]
121
      end
122

123
      def bibliography
124
        unless @bibliography
125 126 127 128
          @bibliography = BibTeX.parse(
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
129
          @bibliography.replace_strings if replace_strings?
130
          @bibliography.join if join_strings? && replace_strings?
131 132 133
        end

        @bibliography
134 135
      end

136 137 138 139
      def query
        interpolate @query
      end

140
      def entries
141 142
        sort bibliography[query || config['query']]
      end
143

144
      def sort(unsorted)
Sylvester Keil's avatar
Sylvester Keil committed
145
        return unsorted if skip_sort?
146

147 148 149 150
        sorted = unsorted.sort_by do |e|
          e.values_at(*sort_keys).map { |v| v.nil? ? BibTeX::Value.new : v }
        end

151 152
        sorted.reverse! if config['order'] =~ /^(desc|reverse)/i
        sorted
153
      end
154

155
      def sort_keys
156 157 158 159 160 161
        return @sort_keys unless @sort_keys.nil?

        @sort_keys = Array(config['sort_by'])
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
          .map { |key| key == 'month' ? 'month_numeric' : key }
162 163
      end

Sylvester Keil's avatar
Sylvester Keil committed
164 165 166 167
      def suppress_author?
        !!@suppress_author
      end

168 169 170 171 172 173 174 175 176
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
177
        repo = Hash.new { |h,k| h[k] = {} }
178

179 180 181 182 183 184 185 186
        return repo unless repository?

        Dir[File.join(repository_path, '**/*')].each do |path|
          extname = File.extname(path)
          repo[File.basename(path, extname)][extname[1..-1]] = path
        end

        repo
187 188 189 190 191 192
      end

      def repository_path
        config['repository']
      end

193 194 195 196
      def replace_strings?
        config['replace_strings']
      end

197 198 199 200
      def join_strings?
        config['join_strings']
      end

201 202 203 204
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
205 206 207 208
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

209 210
      def extend_path(name)
        if name.nil? || name.empty?
211
          name = config['bibliography']
212
        end
213

Sylvester Keil's avatar
Sylvester Keil committed
214 215
        # Return as is if it is an absolute path
        # Improve by using Pathname from stdlib?
216
        return name if name.start_with?('/') && File.exists?(name)
217

Sylvester Keil's avatar
Sylvester Keil committed
218 219 220 221 222 223 224 225 226 227 228 229
        name = File.join scholar_source, name
        name << '.bib' if File.extname(name).empty? && !File.exists?(name)
        name
      end

      def scholar_source
        source = config['source']

        # Improve by using Pathname from stdlib?
        return source if source.start_with?('/') && File.exists?(source)

        File.join site.source, source
230
      end
231

Sylvester Keil's avatar
Sylvester Keil committed
232
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
233
        return missing_reference unless entry
234

235
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
236
        reference = render_bibliography entry, index
237

Sylvester Keil's avatar
Sylvester Keil committed
238 239 240 241
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

242 243 244 245
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
246 247 248 249 250 251 252 253 254
      def missing_reference
        config['missing_reference']
      end

      def reference_tagname
        config['reference_tagname'] || :span
      end

      def bibliography_template
255 256 257 258 259
        @bibliography_template || config['bibliography_template']
      end

      def liquid_template
        return @liquid_template if @liquid_template
260

261
        tmp = bibliography_template
262 263

        case
264
        when tmp.nil?, tmp.empty?
265 266 267 268 269
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

270
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
271 272
      end

273
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
274 275
        return missing_reference unless entry

276
        liquid_template.render({
Sylvester Keil's avatar
Sylvester Keil committed
277
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
278
          'reference' => reference_tag(entry, index),
279
          'key' => entry.key,
280
          'type' => entry.type.to_s,
281
          'link' => repository_link_for(entry),
282
          'links' => repository_links_for(entry),
283 284
          'index' => index,
          'details' => details_link_for(entry)
285
        })
286 287
      end

Sylvester Keil's avatar
Sylvester Keil committed
288 289 290 291
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
292
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
293

294 295 296
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
Sylvester Keil's avatar
Sylvester Keil committed
297
          tmp = entry.dup
298 299 300 301 302

          config['bibtex_skip_fields'].each do |name|
            tmp.delete name if tmp.field?(name)
          end

Sylvester Keil's avatar
Sylvester Keil committed
303 304
          e['bibtex'] = tmp.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
305 306 307 308 309 310 311 312 313

        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
        end

        e
      end

314 315 316
      def bibtex_skip_fields
      end

317 318 319
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
320

321 322
      def details_file_for(entry)
        name = entry.key.to_s.dup
323

324
        name.gsub!(/[:\s]+/, '_')
325

326
        if site.config['permalink'] == 'pretty'
Sylvester Keil's avatar
fix #55  
Sylvester Keil committed
327
          name << '/index.html'
328 329 330
        else
          name << '.html'
        end
331
      end
332

333
      def repository_link_for(entry, base = base_url)
334 335 336
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

337 338 339 340 341
        return unless url

        File.join(base, url)
      end

342 343 344 345 346 347
      def repository_links_for(entry, base = base_url)
        Hash[repository[entry.key].map { |ext, url|
          [ext, File.join(base, url)]
        }]
      end

Sylvester Keil's avatar
Sylvester Keil committed
348
      def details_link_for(entry, base = base_url)
349
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
350
      end
351

Sylvester Keil's avatar
Sylvester Keil committed
352
      def base_url
353
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
354
      end
355

356 357 358
      def details_path
        config['details_dir']
      end
359

Sylvester Keil's avatar
Sylvester Keil committed
360 361 362 363
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end
364

365 366
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
367
          cited_keys << entry.key
Sylvester Keil's avatar
4.2.1  
Sylvester Keil committed
368
          cited_keys.uniq!
369

Sylvester Keil's avatar
Sylvester Keil committed
370
          item = citation_item_for entry, citation_number(entry.key)
371
          item.locator = locator
372

373 374
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
375 376
      end

Sylvester Keil's avatar
Sylvester Keil committed
377 378 379
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
380 381
      end

Sylvester Keil's avatar
Sylvester Keil committed
382
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
383 384
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
385
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
386
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
387 388 389
        end
      end

390
      def cited_keys
391
        context['cited'] ||= []
392
      end
393

Sylvester Keil's avatar
Sylvester Keil committed
394 395
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
Sylvester Keil's avatar
Sylvester Keil committed
396 397
      end

398 399 400 401 402 403 404 405
      def cite(keys)
        items = keys.map do |key|
          if bibliography.key?(key)
            entry = bibliography[key]
            entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
          else
            return missing_reference
          end
Sylvester Keil's avatar
Sylvester Keil committed
406
        end
407 408

        link_to "##{[prefix, keys[0]].compact.join('-')}", render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
409
      end
Sylvester Keil's avatar
Sylvester Keil committed
410

411
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
412
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
413
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
414
        else
415
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
416 417
        end
      end
418

Sylvester Keil's avatar
Sylvester Keil committed
419 420 421 422 423 424
      def content_tag(name, content_or_attributes, attributes = {})
        if content_or_attributes.is_a?(Hash)
          content, attributes = nil, content_or_attributes
        else
          content = content_or_attributes
        end
425

Sylvester Keil's avatar
Sylvester Keil committed
426
        attributes = attributes.map { |k,v| %Q(#{k}="#{v}") }
427

Sylvester Keil's avatar
Sylvester Keil committed
428 429 430 431 432 433
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
434

Sylvester Keil's avatar
Sylvester Keil committed
435 436 437
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
438

439 440 441 442
      def cited_references
        context && context['cited'] || []
      end

443 444
      def keys
        # De-reference keys (in case they are variables)
Sylvester Keil's avatar
Sylvester Keil committed
445 446
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
447 448 449 450 451
        Array(@keys).map do |key|
          context.send(:resolve, key) || key
        end
      end

452 453 454 455 456 457 458 459
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
          context.send(:resolve, $1) || match
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
460
      def set_context_to(context)
461
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
462
        config.merge!(site.config['scholar'] || {})
463
        self
Sylvester Keil's avatar
Sylvester Keil committed
464
      end
465
    end
466

467
  end
Hiren Patel's avatar
Hiren Patel committed
468
end