utilities.rb 16.2 KB
Newer Older
Sylvester Keil's avatar
Sylvester Keil committed
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|
Sylvester Keil's avatar
Sylvester Keil committed
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

Sylvester Keil's avatar
Sylvester Keil committed
21
      attr_reader :config, :site, :context, :prefix, :text, :offset, :max, :relative
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

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

Sylvester Keil's avatar
Sylvester Keil committed
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

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

64
          opts.on('-r', '--relative RELATIVE') do |relative|
65 66
            @relative = relative.to_s.strip
          end
67

68 69 70
          opts.on('-t', '--text TEXT') do |text|
            @text = text
          end
71

72 73 74 75
          opts.on('-l', '--locator LOCATOR') do |locator|
            locators << locator
          end

76 77 78 79
          opts.on('-o', '--offset OFFSET') do |offset|
            @offset = offset.to_i
          end

Sylvester Keil's avatar
Sylvester Keil committed
80
          opts.on('-m', '--max MAX') do |max|
81
            @max = max.to_i
Sylvester Keil's avatar
Sylvester Keil committed
82 83
          end

84 85
          opts.on('-s', '--style STYLE') do |style|
            @style = style
86
          end
87

88 89 90 91
          opts.on('-g', '--group_by GROUP') do |group_by|
            @group_by = group_by
          end

92 93 94
          opts.on('-T', '--template TEMPLATE') do |template|
            @bibliography_template = template
          end
95 96
        end

97
        argv = arguments.split(/(\B-[cCfqrptTsglomA]|\B--(?:cited(_in_order)?|file|query|relative|prefix|text|style|group_by|template|locator|offset|max|suppress_author|))/)
98 99 100

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

102 103 104 105
      def locators
        @locators ||= []
      end

106 107 108 109 110 111 112 113 114
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

115
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
116 117
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
118 119 120 121
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
122
      end
123

124 125 126 127 128 129 130
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
131
      def bibtex_path
132
        bibtex_paths[0]
133
      end
134

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

        @bibliography
146 147
      end

148 149 150 151
      def query
        interpolate @query
      end

152
      def entries
153 154
        sort bibliography[query || config['query']]
      end
155

egon w. stemle's avatar
egon w. stemle committed
156 157 158 159 160 161 162 163
      def offset
        @offset ||= 0
      end

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

Sylvester Keil's avatar
Sylvester Keil committed
164
      def limit_entries?
egon w. stemle's avatar
egon w. stemle committed
165
        !offset.nil? || !max.nil?
Sylvester Keil's avatar
Sylvester Keil committed
166 167
      end

168
      def sort(unsorted)
Sylvester Keil's avatar
Sylvester Keil committed
169
        return unsorted if skip_sort?
170

171 172 173 174 175 176 177 178 179 180 181 182
        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
183
        end
184
 
185
        sorted
186
      end
187

188
      def sort_keys
189 190 191 192 193 194
        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 }
195 196
      end

197 198 199 200 201 202 203 204
      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
205
      def group_by
Sylvester Keil's avatar
Sylvester Keil committed
206
        @group_by ||= config['group_by']
207
      end
Sylvester Keil's avatar
Sylvester Keil committed
208

Patrick de Kok's avatar
Patrick de Kok committed
209 210 211 212
      def group?
        group_by != 'none'
      end

213 214 215 216 217 218 219 220 221 222
      def group(ungrouped)
        def grouper(items,keys,order)
          groups = items
            .group_by do |item|
              group_value(keys.first,item)
            end
          if keys.count == 1
            groups
          else
            groups.merge(groups) do |key,items|
223
              grouper(items,keys.drop(1),order.drop(1))
224 225 226 227 228
            end
          end
        end
        grouper(ungrouped,group_keys,group_order)
      end
Sylvester Keil's avatar
Sylvester Keil committed
229

230 231 232
      def group_keys
        return @group_keys unless @group_keys.nil?

Patrick de Kok's avatar
Patrick de Kok committed
233
        @group_keys = Array(group_by)
234 235 236 237
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
          .map { |key| key == 'month' ? 'month_numeric' : key }
      end
Sylvester Keil's avatar
Sylvester Keil committed
238

239 240 241 242 243 244 245
      def group_order
        return @group_order unless @group_order.nil?

        @group_order = Array(config['group_order'])
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
      end
Sylvester Keil's avatar
Sylvester Keil committed
246

247
      def group_compare(key,v1,v2)
248 249
        case key
        when 'type'
250 251 252 253 254 255 256 257 258 259 260
          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
261
        else
262
          v1 <=> v2
263 264
        end
      end
Sylvester Keil's avatar
Sylvester Keil committed
265

266 267 268
      def group_value(key,item)
        case key
        when 'type'
269
          type_aliases[item.type.to_s] || item.type.to_s
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        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
 
      def group_name(key,value)
        case key
        when 'type'
293
          type_names[value] || value.to_s
294
        when 'month_numeric'
295
          month_names[value] || "(unknown)"
296 297 298 299
        else
          value.to_s
        end
      end
300 301 302 303 304

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

305 306 307 308
      def type_aliases
        @type_aliases ||= Scholar.defaults['type_aliases'].merge(config['type_aliases'])
      end

309 310 311 312 313 314 315 316
      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
317
      end
318

Sylvester Keil's avatar
Sylvester Keil committed
319 320 321 322
      def suppress_author?
        !!@suppress_author
      end

Sylvester Keil's avatar
Sylvester Keil committed
323
      def raw_bibtex?
324
        config['use_raw_bibtex_entry']
Sylvester Keil's avatar
Sylvester Keil committed
325 326
      end

327 328 329 330 331 332 333 334 335
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
336
        repo = Hash.new { |h,k| h[k] = {} }
337

338 339 340 341 342 343 344 345
        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
346 347 348 349 350 351
      end

      def repository_path
        config['repository']
      end

352 353 354 355
      def replace_strings?
        config['replace_strings']
      end

356 357 358 359
      def join_strings?
        config['join_strings']
      end

360 361 362 363
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
364 365 366 367
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

368 369
      def extend_path(name)
        if name.nil? || name.empty?
370
          name = config['bibliography']
371
        end
372

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

Sylvester Keil's avatar
Sylvester Keil committed
377 378 379 380 381 382 383 384 385 386 387 388
        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
389
      end
390

Sylvester Keil's avatar
Sylvester Keil committed
391
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
392
        return missing_reference unless entry
393

394
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
395
        reference = render_bibliography entry, index
396

Sylvester Keil's avatar
Sylvester Keil committed
397 398 399 400
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

401 402 403 404
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
405 406 407 408 409 410 411 412 413
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
414 415 416 417 418
        @bibliography_template || config['bibliography_template']
      end

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

421
        tmp = bibliography_template
422 423

        case
424
        when tmp.nil?, tmp.empty?
425 426 427 428 429
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

430
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
431 432
      end

433
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
434 435
        return missing_reference unless entry

436
        liquid_template.render(
437 438 439 440 441 442 443 444 445 446 447
          reference_data(entry,index)
            .merge(site.site_payload)
            .merge({
              'index' => index,
              'details' => details_link_for(entry)
            }),
          {
            :registers => { :site => site },
            :filters => [Jekyll::Filters]
          }
        )
448 449 450 451
      end

      def reference_data(entry, index = nil)
        {
Sylvester Keil's avatar
Sylvester Keil committed
452
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
453
          'reference' => reference_tag(entry, index),
454
          'key' => entry.key,
455
          'type' => entry.type.to_s,
456
          'link' => repository_link_for(entry),
457 458
          'links' => repository_links_for(entry)
        }
459 460
      end

Sylvester Keil's avatar
Sylvester Keil committed
461 462 463 464
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
465
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
466

467 468 469
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
Sylvester Keil's avatar
Sylvester Keil committed
470
          tmp = entry.dup
471 472 473 474 475

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

Sylvester Keil's avatar
Sylvester Keil committed
476 477
          e['bibtex'] = tmp.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
478

Sylvester Keil's avatar
Sylvester Keil committed
479 480 481 482
        if raw_bibtex?
          e['bibtex'] = "{%raw%}#{e['bibtex']}{%endraw%}"
        end

Sylvester Keil's avatar
Sylvester Keil committed
483 484 485
        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
486 487

          if value.is_a?(BibTeX::Names)
488
            e["#{key}_array"] = arr = []
489
            value.each.with_index do |name, idx|
490
              parts = {}
491 492
              name.each_pair do |k, v|
                e["#{key}_#{idx}_#{k}"] = v.to_s
493
                parts[k.to_s] = v.to_s
494
              end
495
              arr << parts
496 497
            end
          end
Sylvester Keil's avatar
Sylvester Keil committed
498 499 500 501 502
        end

        e
      end

503 504 505
      def bibtex_skip_fields
      end

506 507 508
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
509

510 511
      def details_file_for(entry)
        name = entry.key.to_s.dup
512

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

515
        if site.config['permalink'] == 'pretty'
516
          name << '/'
517 518 519
        else
          name << '.html'
        end
520
      end
521

522
      def repository_link_for(entry, base = base_url)
523 524 525
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

526 527 528 529 530
        return unless url

        File.join(base, url)
      end

531 532 533 534 535 536
      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
537
      def details_link_for(entry, base = base_url)
538
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
539
      end
540

Sylvester Keil's avatar
Sylvester Keil committed
541
      def base_url
542
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
543
      end
544

545 546 547
      def details_path
        config['details_dir']
      end
548

549 550 551 552
      def renderer(force = false)
        return @renderer if @renderer && !force
          
        @renderer = CiteProc::Ruby::Renderer.new :format => 'html',
Sylvester Keil's avatar
Sylvester Keil committed
553 554
          :style => style, :locale => config['locale']
      end
555

556 557
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
558
          cited_keys << entry.key
Sylvester Keil's avatar
4.2.1  
Sylvester Keil committed
559
          cited_keys.uniq!
560

Sylvester Keil's avatar
Sylvester Keil committed
561
          item = citation_item_for entry, citation_number(entry.key)
562
          item.locator = locator
563

564 565
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
566 567
      end

Sylvester Keil's avatar
Sylvester Keil committed
568 569 570
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
571 572
      end

Sylvester Keil's avatar
Sylvester Keil committed
573
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
574 575
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
576
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
577
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
578 579 580
        end
      end

581
      def cited_keys
582
        context['cited'] ||= []
583
      end
584

Sylvester Keil's avatar
Sylvester Keil committed
585 586
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
Sylvester Keil's avatar
Sylvester Keil committed
587 588
      end

589
      def link_target_for key
590
        "#{base_url}#{relative}##{[prefix, key].compact.join('-')}"
591 592
      end

593 594 595 596 597 598 599 600
      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
601
        end
602

603
        link_to link_target_for(keys[0]), render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
604
      end
Sylvester Keil's avatar
Sylvester Keil committed
605

606
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
607
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
608
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
609
        else
610
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
611 612
        end
      end
613

Sylvester Keil's avatar
Sylvester Keil committed
614 615 616 617 618 619
      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
620

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

Sylvester Keil's avatar
Sylvester Keil committed
623 624 625 626 627 628
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
629

Sylvester Keil's avatar
Sylvester Keil committed
630 631 632
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
633

634 635 636 637
      def cited_references
        context && context['cited'] || []
      end

638 639
      def keys
        # De-reference keys (in case they are variables)
Sylvester Keil's avatar
Sylvester Keil committed
640 641
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
642
        Array(@keys).map do |key|
643
          context[key] || key
644 645 646
        end
      end

647 648 649 650
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
651
          context[$1] || match
652 653 654
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
655
      def set_context_to(context)
656
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
657
        config.merge!(site.config['scholar'] || {})
658
        self
Sylvester Keil's avatar
Sylvester Keil committed
659
      end
660
    end
661

662
  end
Hiren Patel's avatar
Hiren Patel committed
663
end