utilities.rb 16.4 KB
Newer Older
1
module Jekyll
2
  class Scholar
3
    require 'date'
4

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


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

20

21
      attr_reader :config, :site, :context, :prefix, :text, :offset, :max
22 23


24 25 26 27 28 29 30 31 32 33

      def split_arguments(arguments)

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

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

        [args, opts]
      end
34 35 36 37 38 39 40 41 42

      def optparse(arguments)
        return if arguments.nil? || arguments.empty?

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

43 44 45 46
          opts.on('-C', '--cited_in_order') do |cited|
            @cited, @skip_sort = true, true
          end

47 48 49 50
          opts.on('-A', '--suppress_author') do |cited|
            @suppress_author = true
          end

51
          opts.on('-f', '--file FILE') do |file|
52 53
            @bibtex_files ||= []
            @bibtex_files << file
54 55 56 57
          end

          opts.on('-q', '--query QUERY') do |query|
            @query = query
58
          end
59 60 61 62 63 64 65 66

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

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

68 69 70 71
          opts.on('-l', '--locator LOCATOR') do |locator|
            locators << locator
          end

72 73 74 75
          opts.on('-o', '--offset OFFSET') do |offset|
            @offset = offset.to_i
          end

Sylvester Keil's avatar
Sylvester Keil committed
76
          opts.on('-m', '--max MAX') do |max|
77
            @max = max.to_i
Sylvester Keil's avatar
Sylvester Keil committed
78 79
          end

80 81
          opts.on('-s', '--style STYLE') do |style|
            @style = style
82
          end
83

84 85 86 87
          opts.on('-g', '--group_by GROUP') do |group_by|
            @group_by = group_by
          end

88 89 90 91
          opts.on('-G', '--group_order ORDER') do |group_order|
            self.group_order = group_order
          end

92 93 94 95
          opts.on('-O', '--type_order ORDER') do |type_order|
            @group_by = type_order
          end

96 97 98
          opts.on('-T', '--template TEMPLATE') do |template|
            @bibliography_template = template
          end
99 100
        end

101
        argv = arguments.split(/(\B-[cCfqptTsgGOlomA]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|group_(?:by|order)|type_order|template|locator|offset|max|suppress_author|))/)
102 103 104

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

106 107 108 109
      def locators
        @locators ||= []
      end

110 111 112 113 114 115 116 117 118
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

119
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
120 121
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
122 123 124 125
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
126
      end
127

128 129 130 131 132 133 134
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
135
      def bibtex_path
136
        bibtex_paths[0]
137
      end
138

139
      def bibliography
140
        unless @bibliography
141
          @bibliography = BibTeX::Bibliography.parse(
142 143 144
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
145
          @bibliography.replace_strings if replace_strings?
146
          @bibliography.join if join_strings? && replace_strings?
147 148 149
        end

        @bibliography
150 151
      end

152 153 154 155
      def query
        interpolate @query
      end

156
      def entries
157 158
        sort bibliography[query || config['query']]
      end
159

egon w. stemle's avatar
egon w. stemle committed
160 161 162 163 164 165 166 167
      def offset
        @offset ||= 0
      end

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

Sylvester Keil's avatar
Sylvester Keil committed
168
      def limit_entries?
egon w. stemle's avatar
egon w. stemle committed
169
        !offset.nil? || !max.nil?
Sylvester Keil's avatar
Sylvester Keil committed
170 171
      end

172
      def sort(unsorted)
173
        return unsorted if skip_sort?
174

175 176 177 178 179 180 181 182 183 184 185 186
        sorted = unsorted.sort do |e1, e2|
          sort_keys
            .map.with_index do |key, idx|
              v1 = e1[key].nil? ? BibTeX::Value.new : e1[key]
              v2 = e2[key].nil? ? BibTeX::Value.new : e2[key]
              if (sort_order[idx] || sort_order.last) =~ /^(desc|reverse)/i
                v2 <=> v1
              else
                v1 <=> v2
              end
            end
            .find { |c| c != 0 } || 0
187
        end
188

189
        sorted
190
      end
191

192
      def sort_keys
193 194 195 196 197 198
        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 }
199 200
      end

201 202 203 204 205 206 207 208
      def sort_order
        return @sort_order unless @sort_order.nil?

        @sort_order = Array(config['order'])
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
      end

Patrick de Kok's avatar
Patrick de Kok committed
209
      def group_by
210
        @group_by ||= config['group_by']
211
      end
212

Patrick de Kok's avatar
Patrick de Kok committed
213 214 215 216
      def group?
        group_by != 'none'
      end

217
      def group(ungrouped)
218 219 220 221 222
        def grouper(items, keys, order)
          groups = items.group_by do |item|
            group_value(keys.first, item)
          end

223 224 225
          if keys.count == 1
            groups
          else
226 227
            groups.merge(groups) do |key, items|
              grouper(items, keys.drop(1), order.drop(1))
228 229 230
            end
          end
        end
231 232

        grouper(ungrouped, group_keys, group_order)
233
      end
234

235 236 237
      def group_keys
        return @group_keys unless @group_keys.nil?

Patrick de Kok's avatar
Patrick de Kok committed
238
        @group_keys = Array(group_by)
239 240 241 242
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
          .map { |key| key == 'month' ? 'month_numeric' : key }
      end
243

244
      def group_order
245 246 247
        self.group_order = config['group_order'] if @group_order.nil?
        @group_order
      end
248

249 250
      def group_order=(value)
        @group_order = Array(value)
251 252 253
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
      end
254

255
      def group_compare(key,v1,v2)
256 257
        case key
        when 'type'
258 259 260 261 262 263 264 265 266 267 268
          o1 = type_order.find_index(v1)
          o2 = type_order.find_index(v2)
          if o1.nil? && o2.nil?
            0
          elsif o1.nil?
            1
          elsif o2.nil?
            -1
          else
            o1 <=> o2
          end
269
        else
270
          v1 <=> v2
271 272
        end
      end
273

274 275 276
      def group_value(key,item)
        case key
        when 'type'
277
          type_aliases[item.type.to_s] || item.type.to_s
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        else
          value = item[key]
          if value.numeric?
            value.to_i
          elsif value.date?
            value.to_date
          else
            value.to_s
          end
        end
      end

      def group_tags
        return @group_tags unless @group_tags.nil?

        @group_tags = Array(config['bibliography_group_tag'])
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
      end
297

298 299 300
      def group_name(key,value)
        case key
        when 'type'
301
          type_names[value] || value.to_s
302
        when 'month_numeric'
303
          month_names[value] || "(unknown)"
304 305 306 307
        else
          value.to_s
        end
      end
308 309 310 311 312

      def type_order
        @type_order ||= config['type_order']
      end

313 314 315 316
      def type_aliases
        @type_aliases ||= Scholar.defaults['type_aliases'].merge(config['type_aliases'])
      end

317 318 319 320 321 322 323 324
      def type_names
        @type_names ||= Scholar.defaults['type_names'].merge(config['type_names'])
      end

      def month_names
        return @month_names unless @month_names.nil?

        @month_names = config['month_names'].nil? ? Date::MONTHNAMES : config['month_names'].unshift(nil)
Hendrik van Antwerpen's avatar
Hendrik van Antwerpen committed
325
      end
326

327 328 329 330
      def suppress_author?
        !!@suppress_author
      end

Sylvester Keil's avatar
Sylvester Keil committed
331
      def raw_bibtex?
332
        config['use_raw_bibtex_entry']
Sylvester Keil's avatar
Sylvester Keil committed
333 334
      end

335 336 337 338 339 340 341 342 343
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
344
        repo = Hash.new { |h,k| h[k] = {} }
345

346 347 348 349 350 351 352 353
        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
354 355 356 357 358 359
      end

      def repository_path
        config['repository']
      end

360 361 362 363
      def replace_strings?
        config['replace_strings']
      end

364 365 366 367
      def join_strings?
        config['join_strings']
      end

368 369 370 371
      def cited_only?
        !!@cited
      end

372 373 374 375
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

376 377
      def extend_path(name)
        if name.nil? || name.empty?
378
          name = config['bibliography']
379
        end
380

381 382
        # Return as is if it is an absolute path
        # Improve by using Pathname from stdlib?
383
        return name if name.start_with?('/') && File.exists?(name)
384

385 386 387 388 389 390 391 392 393 394 395 396
        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
397
      end
398

399
      def relative
400
        config['relative']
401 402
      end

403
      def reference_tag(entry, index = nil)
404
        return missing_reference unless entry
405

406
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
407
        reference = render_bibliography entry, index
408

409 410 411 412
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

413 414 415 416
      def style
        @style || config['style']
      end

417 418 419 420 421 422 423 424 425
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
426 427 428 429 430
        @bibliography_template || config['bibliography_template']
      end

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

433
        tmp = bibliography_template
434 435

        case
436
        when tmp.nil?, tmp.empty?
437 438 439 440 441
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

442
        @liquid_template = Liquid::Template.parse(tmp)
443 444
      end

445
      def bibliography_tag(entry, index)
446 447
        return missing_reference unless entry

448
        liquid_template.render(
449 450 451 452 453 454 455 456 457 458 459
          reference_data(entry,index)
            .merge(site.site_payload)
            .merge({
              'index' => index,
              'details' => details_link_for(entry)
            }),
          {
            :registers => { :site => site },
            :filters => [Jekyll::Filters]
          }
        )
460 461 462 463
      end

      def reference_data(entry, index = nil)
        {
464
          'entry' => liquidify(entry),
465
          'reference' => reference_tag(entry, index),
466
          'key' => entry.key,
467
          'type' => entry.type.to_s,
468
          'link' => repository_link_for(entry),
469 470
          'links' => repository_links_for(entry)
        }
471 472
      end

473 474 475 476
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
477
        e['type'] = entry.type.to_s
478

479 480 481
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
482
          tmp = entry.dup
483 484 485 486 487

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

488 489
          e['bibtex'] = tmp.to_s
        end
490

Sylvester Keil's avatar
Sylvester Keil committed
491 492 493 494
        if raw_bibtex?
          e['bibtex'] = "{%raw%}#{e['bibtex']}{%endraw%}"
        end

495 496 497
        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
498 499

          if value.is_a?(BibTeX::Names)
500
            e["#{key}_array"] = arr = []
501
            value.each.with_index do |name, idx|
502
              parts = {}
503 504
              name.each_pair do |k, v|
                e["#{key}_#{idx}_#{k}"] = v.to_s
505
                parts[k.to_s] = v.to_s
506
              end
507
              arr << parts
508 509
            end
          end
510 511 512 513 514
        end

        e
      end

515 516 517
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
518

519 520
      def details_file_for(entry)
        name = entry.key.to_s.dup
521

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

524
        if site.config['permalink'] == 'pretty'
525
          name << '/'
526 527 528
        else
          name << '.html'
        end
529
      end
530

531
      def repository_link_for(entry, base = base_url)
532 533 534
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

535 536 537 538 539
        return unless url

        File.join(base, url)
      end

540 541 542 543 544 545
      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
546
      def details_link_for(entry, base = base_url)
547
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
548
      end
549

Sylvester Keil's avatar
Sylvester Keil committed
550
      def base_url
551
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
552
      end
553

554 555 556
      def details_path
        config['details_dir']
      end
557

558 559
      def renderer(force = false)
        return @renderer if @renderer && !force
560

561
        @renderer = CiteProc::Ruby::Renderer.new :format => 'html',
Sylvester Keil's avatar
Sylvester Keil committed
562 563
          :style => style, :locale => config['locale']
      end
564

565 566
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
567
          cited_keys << entry.key
Sylvester Keil's avatar
Sylvester Keil committed
568
          cited_keys.uniq!
569

570
          item = citation_item_for entry, citation_number(entry.key)
571
          item.locator = locator
572

573 574
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
575 576
      end

577 578 579
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
580 581
      end

582
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
583 584
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
585
          c.data[:'citation-number'] = citation_number
586
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
587 588 589
        end
      end

590
      def cited_keys
591
        context['cited'] ||= []
592
      end
593

594 595
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
596 597
      end

598 599
      def link_target_for(key)
        "#{relative}##{[prefix, key].compact.join('-')}"
600 601
      end

602 603 604 605 606 607 608 609
      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
610
        end
611

612
        link_to link_target_for(keys[0]), render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
613
      end
Sylvester Keil's avatar
Sylvester Keil committed
614

615
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
616
        if bibliography.key?(key)
617
          link_to details_link_for(bibliography[key]), text || config['details_link']
618
        else
619
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
620 621
        end
      end
622

623 624 625 626 627 628
      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
629

630
        attributes = attributes.map { |k,v| %Q(#{k}="#{v}") }
631

632 633 634 635 636 637
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
638

639 640 641
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
642

643 644 645 646
      def cited_references
        context && context['cited'] || []
      end

647 648
      def keys
        # De-reference keys (in case they are variables)
649 650
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
651
        Array(@keys).map do |key|
652
          context[key] || key
653 654 655
        end
      end

656 657 658 659
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
660
          context[$1] || match
661 662 663
        end
      end

664
      def set_context_to(context)
665
        @context, @site, = context, context.registers[:site]
666
        config.merge!(site.config['scholar'] || {})
667
        self
668
      end
669
    end
670

671
  end
Hiren Patel's avatar
Hiren Patel committed
672
end