utilities.rb 16.6 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 22
      attr_reader :config, :site, :context,
        :prefix, :text, :offset, :max, :label
23 24


25 26 27 28 29 30 31 32 33 34

      def split_arguments(arguments)

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

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

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

      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
44 45 46 47
          opts.on('-C', '--cited_in_order') do |cited|
            @cited, @skip_sort = true, true
          end

Sylvester Keil's avatar
Sylvester Keil committed
48 49 50 51
          opts.on('-A', '--suppress_author') do |cited|
            @suppress_author = true
          end

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

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

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

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

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

Sylvester Keil's avatar
Sylvester Keil committed
73 74 75 76
          opts.on('-L', '--label LABEL') do |label|
            @label = label
          end

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

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

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

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

93 94 95 96
          opts.on('-G', '--group_order ORDER') do |group_order|
            self.group_order = group_order
          end

97 98 99 100
          opts.on('-O', '--type_order ORDER') do |type_order|
            @group_by = type_order
          end

101 102 103
          opts.on('-T', '--template TEMPLATE') do |template|
            @bibliography_template = template
          end
104 105
        end

Sylvester Keil's avatar
Sylvester Keil committed
106
        argv = arguments.split(/(\B-[cCfqptTsgGOlLomA]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|group_(?:by|order)|type_order|template|locator|label|offset|max|suppress_author|))/)
107 108 109

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

111 112 113 114
      def locators
        @locators ||= []
      end

115 116 117 118 119 120 121 122 123
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

124
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
125 126
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
127 128 129 130
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
131
      end
132

133 134 135 136 137 138 139
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
140
      def bibtex_path
141
        bibtex_paths[0]
142
      end
143

144
      def bibliography
145
        unless @bibliography
146
          @bibliography = BibTeX::Bibliography.parse(
147 148 149
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
150
          @bibliography.replace_strings if replace_strings?
151
          @bibliography.join if join_strings? && replace_strings?
152 153 154
        end

        @bibliography
155 156
      end

157 158 159 160
      def query
        interpolate @query
      end

161
      def entries
162 163
        sort bibliography[query || config['query']]
      end
164

egon w. stemle's avatar
egon w. stemle committed
165 166 167 168 169 170 171 172
      def offset
        @offset ||= 0
      end

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

Sylvester Keil's avatar
Sylvester Keil committed
173
      def limit_entries?
egon w. stemle's avatar
egon w. stemle committed
174
        !offset.nil? || !max.nil?
Sylvester Keil's avatar
Sylvester Keil committed
175 176
      end

177
      def sort(unsorted)
Sylvester Keil's avatar
Sylvester Keil committed
178
        return unsorted if skip_sort?
179

180 181 182 183 184 185 186 187 188 189 190 191
        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
192
        end
193

194
        sorted
195
      end
196

197
      def sort_keys
198 199 200 201 202 203
        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 }
204 205
      end

206 207 208 209 210 211 212 213
      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
214
      def group_by
Sylvester Keil's avatar
Sylvester Keil committed
215
        @group_by ||= config['group_by']
216
      end
Sylvester Keil's avatar
Sylvester Keil committed
217

Patrick de Kok's avatar
Patrick de Kok committed
218 219 220 221
      def group?
        group_by != 'none'
      end

222
      def group(ungrouped)
223 224 225 226 227
        def grouper(items, keys, order)
          groups = items.group_by do |item|
            group_value(keys.first, item)
          end

228 229 230
          if keys.count == 1
            groups
          else
231 232
            groups.merge(groups) do |key, items|
              grouper(items, keys.drop(1), order.drop(1))
233 234 235
            end
          end
        end
236 237

        grouper(ungrouped, group_keys, group_order)
238
      end
Sylvester Keil's avatar
Sylvester Keil committed
239

240 241 242
      def group_keys
        return @group_keys unless @group_keys.nil?

Patrick de Kok's avatar
Patrick de Kok committed
243
        @group_keys = Array(group_by)
244 245 246 247
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
          .map { |key| key == 'month' ? 'month_numeric' : key }
      end
Sylvester Keil's avatar
Sylvester Keil committed
248

249
      def group_order
250 251 252
        self.group_order = config['group_order'] if @group_order.nil?
        @group_order
      end
253

254 255
      def group_order=(value)
        @group_order = Array(value)
256 257 258
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
      end
Sylvester Keil's avatar
Sylvester Keil committed
259

260
      def group_compare(key,v1,v2)
261 262
        case key
        when 'type'
263 264 265 266 267 268 269 270 271 272 273
          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
274
        else
275
          v1 <=> v2
276 277
        end
      end
Sylvester Keil's avatar
Sylvester Keil committed
278

279 280 281
      def group_value(key,item)
        case key
        when 'type'
282
          type_aliases[item.type.to_s] || item.type.to_s
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        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
302

303 304 305
      def group_name(key,value)
        case key
        when 'type'
306
          type_names[value] || value.to_s
307
        when 'month_numeric'
308
          month_names[value] || "(unknown)"
309 310 311 312
        else
          value.to_s
        end
      end
313 314 315 316 317

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

318 319 320 321
      def type_aliases
        @type_aliases ||= Scholar.defaults['type_aliases'].merge(config['type_aliases'])
      end

322 323 324 325 326 327 328 329
      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
330
      end
331

Sylvester Keil's avatar
Sylvester Keil committed
332 333 334 335
      def suppress_author?
        !!@suppress_author
      end

Sylvester Keil's avatar
Sylvester Keil committed
336
      def raw_bibtex?
337
        config['use_raw_bibtex_entry']
Sylvester Keil's avatar
Sylvester Keil committed
338 339
      end

340 341 342 343 344 345 346 347 348
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
349
        repo = Hash.new { |h,k| h[k] = {} }
350

351 352 353 354 355 356 357 358
        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
359 360 361 362 363 364
      end

      def repository_path
        config['repository']
      end

365 366 367 368
      def replace_strings?
        config['replace_strings']
      end

369 370 371 372
      def join_strings?
        config['join_strings']
      end

373 374 375 376
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
377 378 379 380
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

381 382
      def extend_path(name)
        if name.nil? || name.empty?
383
          name = config['bibliography']
384
        end
385

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

Sylvester Keil's avatar
Sylvester Keil committed
390 391 392 393 394 395 396 397 398 399 400 401
        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
402
      end
403

Alex Gil's avatar
Alex Gil committed
404
      def relative
405
        config['relative']
Alex Gil's avatar
Alex Gil committed
406 407
      end

Sylvester Keil's avatar
Sylvester Keil committed
408
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
409
        return missing_reference unless entry
410

411
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
412
        reference = render_bibliography entry, index
413

Sylvester Keil's avatar
Sylvester Keil committed
414 415 416 417
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

418 419 420 421
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
422 423 424 425 426 427 428 429 430
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
431 432 433 434 435
        @bibliography_template || config['bibliography_template']
      end

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

438
        tmp = bibliography_template
439 440

        case
441
        when tmp.nil?, tmp.empty?
442 443 444 445 446
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

447
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
448 449
      end

450
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
451 452
        return missing_reference unless entry

453
        liquid_template.render(
454 455 456 457 458 459 460 461 462 463 464
          reference_data(entry,index)
            .merge(site.site_payload)
            .merge({
              'index' => index,
              'details' => details_link_for(entry)
            }),
          {
            :registers => { :site => site },
            :filters => [Jekyll::Filters]
          }
        )
465 466 467 468
      end

      def reference_data(entry, index = nil)
        {
Sylvester Keil's avatar
Sylvester Keil committed
469
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
470
          'reference' => reference_tag(entry, index),
471
          'key' => entry.key,
472
          'type' => entry.type.to_s,
473
          'link' => repository_link_for(entry),
474 475
          'links' => repository_links_for(entry)
        }
476 477
      end

Sylvester Keil's avatar
Sylvester Keil committed
478 479 480 481
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
482
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
483

484 485 486
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
Sylvester Keil's avatar
Sylvester Keil committed
487
          tmp = entry.dup
488 489 490 491 492

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

Sylvester Keil's avatar
Sylvester Keil committed
493 494
          e['bibtex'] = tmp.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
495

Sylvester Keil's avatar
Sylvester Keil committed
496 497 498 499
        if raw_bibtex?
          e['bibtex'] = "{%raw%}#{e['bibtex']}{%endraw%}"
        end

Sylvester Keil's avatar
Sylvester Keil committed
500 501 502
        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
503 504

          if value.is_a?(BibTeX::Names)
505
            e["#{key}_array"] = arr = []
506
            value.each.with_index do |name, idx|
507
              parts = {}
508 509
              name.each_pair do |k, v|
                e["#{key}_#{idx}_#{k}"] = v.to_s
510
                parts[k.to_s] = v.to_s
511
              end
512
              arr << parts
513 514
            end
          end
Sylvester Keil's avatar
Sylvester Keil committed
515 516 517 518 519
        end

        e
      end

520 521 522
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
523

524 525
      def details_file_for(entry)
        name = entry.key.to_s.dup
526

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

529
        if site.config['permalink'] == 'pretty'
530
          name << '/'
531 532 533
        else
          name << '.html'
        end
534
      end
535

536
      def repository_link_for(entry, base = base_url)
537 538 539
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

540 541 542 543 544
        return unless url

        File.join(base, url)
      end

545 546 547 548 549 550
      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
551
      def details_link_for(entry, base = base_url)
552
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
553
      end
554

Sylvester Keil's avatar
Sylvester Keil committed
555
      def base_url
556
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
557
      end
558

559 560 561
      def details_path
        config['details_dir']
      end
562

563 564
      def renderer(force = false)
        return @renderer if @renderer && !force
565

566
        @renderer = CiteProc::Ruby::Renderer.new :format => 'html',
Sylvester Keil's avatar
Sylvester Keil committed
567 568
          :style => style, :locale => config['locale']
      end
569

570 571
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
572
          cited_keys << entry.key
Sylvester Keil's avatar
4.2.1  
Sylvester Keil committed
573
          cited_keys.uniq!
574

Sylvester Keil's avatar
Sylvester Keil committed
575
          item = citation_item_for entry, citation_number(entry.key)
576
          item.locator = locator
Sylvester Keil's avatar
Sylvester Keil committed
577
          item.label = label unless label.nil?
578

579 580
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
581 582
      end

Sylvester Keil's avatar
Sylvester Keil committed
583 584 585
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
586 587
      end

Sylvester Keil's avatar
Sylvester Keil committed
588
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
589 590
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
591
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
592
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
593 594 595
        end
      end

596
      def cited_keys
597
        context['cited'] ||= []
598
      end
599

Sylvester Keil's avatar
Sylvester Keil committed
600 601
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
Sylvester Keil's avatar
Sylvester Keil committed
602 603
      end

Alex Gil's avatar
Alex Gil committed
604 605
      def link_target_for(key)
        "#{relative}##{[prefix, key].compact.join('-')}"
606 607
      end

608 609 610 611 612 613 614 615
      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
616
        end
617

618
        link_to link_target_for(keys[0]), render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
619
      end
Sylvester Keil's avatar
Sylvester Keil committed
620

621
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
622
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
623
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
624
        else
625
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
626 627
        end
      end
628

Sylvester Keil's avatar
Sylvester Keil committed
629 630 631 632 633 634
      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
635

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

Sylvester Keil's avatar
Sylvester Keil committed
638 639 640 641 642 643
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
644

Sylvester Keil's avatar
Sylvester Keil committed
645 646 647
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
648

649 650 651 652
      def cited_references
        context && context['cited'] || []
      end

653 654
      def keys
        # De-reference keys (in case they are variables)
Sylvester Keil's avatar
Sylvester Keil committed
655 656
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
657
        Array(@keys).map do |key|
658
          context[key] || key
659 660 661
        end
      end

662 663 664 665
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
666
          context[$1] || match
667 668 669
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
670
      def set_context_to(context)
671
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
672
        config.merge!(site.config['scholar'] || {})
673
        self
Sylvester Keil's avatar
Sylvester Keil committed
674
      end
675
    end
676

677
  end
Hiren Patel's avatar
Hiren Patel committed
678
end