utilities.rb 12.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
    # 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|
Sylvester Keil's avatar
Sylvester Keil committed
8 9 10
      style = CSL::Style.load k
      style = style.independent_parent unless style.independent?
      h[k.to_s] = style
Sylvester Keil's avatar
Sylvester Keil committed
11 12 13
    end


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

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

      def split_arguments(arguments)

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

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

        [args, opts]
      end
30 31 32 33 34 35 36 37 38

      def optparse(arguments)
        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
Sylvester Keil's avatar
Sylvester Keil committed
83 84 85 86

          opts.on('-R', '--raw_bibtex') do |raw_bibtex|
            @raw_bibtex = raw_bibtex
          end
87 88
        end

Sylvester Keil's avatar
Sylvester Keil committed
89
        argv = arguments.split(/(\B-[cCfqptTslomAR]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|template|locator|offset|max|suppress_author|raw_bibtex|))/)
90 91 92

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

94 95 96 97
      def locators
        @locators ||= []
      end

98 99 100 101 102 103 104 105 106
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

107
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
108 109
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
110 111 112 113
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
114
      end
115

116 117 118 119 120 121 122
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
123
      def bibtex_path
124
        bibtex_paths[0]
125
      end
126

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

        @bibliography
138 139
      end

140 141 142 143
      def query
        interpolate @query
      end

144
      def entries
145 146
        sort bibliography[query || config['query']]
      end
147

egon w. stemle's avatar
egon w. stemle committed
148 149 150 151 152 153 154 155
      def offset
        @offset ||= 0
      end

      def max
        @max.nil? ? -1 : @max + offset - 1
      end

Sylvester Keil's avatar
Sylvester Keil committed
156
      def limit_entries?
egon w. stemle's avatar
egon w. stemle committed
157
        !offset.nil? || !max.nil?
Sylvester Keil's avatar
Sylvester Keil committed
158 159
      end

160
      def sort(unsorted)
Sylvester Keil's avatar
Sylvester Keil committed
161
        return unsorted if skip_sort?
162

163 164 165 166
        sorted = unsorted.sort_by do |e|
          e.values_at(*sort_keys).map { |v| v.nil? ? BibTeX::Value.new : v }
        end

167 168
        sorted.reverse! if config['order'] =~ /^(desc|reverse)/i
        sorted
169
      end
170

171
      def sort_keys
172 173 174 175 176 177
        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 }
178 179
      end

Sylvester Keil's avatar
Sylvester Keil committed
180 181 182 183
      def suppress_author?
        !!@suppress_author
      end

Sylvester Keil's avatar
Sylvester Keil committed
184 185 186 187
      def raw_bibtex?
        !!@raw_bibtex
      end

188 189 190 191 192 193 194 195 196
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
197
        repo = Hash.new { |h,k| h[k] = {} }
198

199 200 201 202 203 204 205 206
        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
207 208 209 210 211 212
      end

      def repository_path
        config['repository']
      end

213 214 215 216
      def replace_strings?
        config['replace_strings']
      end

217 218 219 220
      def join_strings?
        config['join_strings']
      end

221 222 223 224
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
225 226 227 228
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

229 230
      def extend_path(name)
        if name.nil? || name.empty?
231
          name = config['bibliography']
232
        end
233

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

Sylvester Keil's avatar
Sylvester Keil committed
238 239 240 241 242 243 244 245 246 247 248 249
        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
250
      end
251

Sylvester Keil's avatar
Sylvester Keil committed
252
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
253
        return missing_reference unless entry
254

255
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
256
        reference = render_bibliography entry, index
257

Sylvester Keil's avatar
Sylvester Keil committed
258 259 260 261
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

262 263 264 265
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
266 267 268 269 270 271 272 273 274
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
275 276 277 278 279
        @bibliography_template || config['bibliography_template']
      end

      def liquid_template
        return @liquid_template if @liquid_template
egon w. stemle's avatar
egon w. stemle committed
280
        Liquid::Template.register_filter(Jekyll::Filters)
281

282
        tmp = bibliography_template
283 284

        case
285
        when tmp.nil?, tmp.empty?
286 287 288 289 290
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

291
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
292 293
      end

294
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
295 296
        return missing_reference unless entry

297
        liquid_template.render(
298 299 300 301 302 303 304 305 306 307 308
          reference_data(entry,index)
            .merge(site.site_payload)
            .merge({
              'index' => index,
              'details' => details_link_for(entry)
            }),
          {
            :registers => { :site => site },
            :filters => [Jekyll::Filters]
          }
        )
309 310 311 312
      end

      def reference_data(entry, index = nil)
        {
Sylvester Keil's avatar
Sylvester Keil committed
313
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
314
          'reference' => reference_tag(entry, index),
315
          'key' => entry.key,
316
          'type' => entry.type.to_s,
317
          'link' => repository_link_for(entry),
318 319
          'links' => repository_links_for(entry)
        }
320 321
      end

Sylvester Keil's avatar
Sylvester Keil committed
322 323 324 325
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
326
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
327

328 329 330
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
Sylvester Keil's avatar
Sylvester Keil committed
331
          tmp = entry.dup
332 333 334 335 336

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

Sylvester Keil's avatar
Sylvester Keil committed
337 338
          e['bibtex'] = tmp.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
339

Sylvester Keil's avatar
Sylvester Keil committed
340 341 342 343
        if raw_bibtex?
          e['bibtex'] = "{%raw%}#{e['bibtex']}{%endraw%}"
        end

Sylvester Keil's avatar
Sylvester Keil committed
344 345 346
        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
347 348 349 350 351 352 353 354

          if value.is_a?(BibTeX::Names)
            value.each.with_index do |name, idx|
              name.each_pair do |k, v|
                e["#{key}_#{idx}_#{k}"] = v.to_s
              end
            end
          end
Sylvester Keil's avatar
Sylvester Keil committed
355 356 357 358 359
        end

        e
      end

360 361 362
      def bibtex_skip_fields
      end

363 364 365
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
366

367 368
      def details_file_for(entry)
        name = entry.key.to_s.dup
369

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

372
        if site.config['permalink'] == 'pretty'
373
          name << '/'
374 375 376
        else
          name << '.html'
        end
377
      end
378

379
      def repository_link_for(entry, base = base_url)
380 381 382
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

383 384 385 386 387
        return unless url

        File.join(base, url)
      end

388 389 390 391 392 393
      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
394
      def details_link_for(entry, base = base_url)
395
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
396
      end
397

Sylvester Keil's avatar
Sylvester Keil committed
398
      def base_url
399
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
400
      end
401

402 403 404
      def details_path
        config['details_dir']
      end
405

Sylvester Keil's avatar
Sylvester Keil committed
406 407 408 409
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end
410

411 412
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
413
          cited_keys << entry.key
Sylvester Keil's avatar
4.2.1  
Sylvester Keil committed
414
          cited_keys.uniq!
415

Sylvester Keil's avatar
Sylvester Keil committed
416
          item = citation_item_for entry, citation_number(entry.key)
417
          item.locator = locator
418

419 420
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
421 422
      end

Sylvester Keil's avatar
Sylvester Keil committed
423 424 425
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
426 427
      end

Sylvester Keil's avatar
Sylvester Keil committed
428
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
429 430
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
431
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
432
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
433 434 435
        end
      end

436
      def cited_keys
437
        context['cited'] ||= []
438
      end
439

Sylvester Keil's avatar
Sylvester Keil committed
440 441
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
Sylvester Keil's avatar
Sylvester Keil committed
442 443
      end

444 445 446 447 448 449 450 451
      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
452
        end
453 454

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

457
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
458
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
459
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
460
        else
461
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
462 463
        end
      end
464

Sylvester Keil's avatar
Sylvester Keil committed
465 466 467 468 469 470
      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
471

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

Sylvester Keil's avatar
Sylvester Keil committed
474 475 476 477 478 479
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
480

Sylvester Keil's avatar
Sylvester Keil committed
481 482 483
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
484

485 486 487 488
      def cited_references
        context && context['cited'] || []
      end

489 490
      def keys
        # De-reference keys (in case they are variables)
Sylvester Keil's avatar
Sylvester Keil committed
491 492
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
493
        Array(@keys).map do |key|
494
          context[key] || key
495 496 497
        end
      end

498 499 500 501
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
502
          context[$1] || match
503 504 505
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
506
      def set_context_to(context)
507
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
508
        config.merge!(site.config['scholar'] || {})
509
        self
Sylvester Keil's avatar
Sylvester Keil committed
510
      end
511
    end
512

513
  end
Hiren Patel's avatar
Hiren Patel committed
514
end