utilities.rb 16 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 22 23

      attr_reader :config, :site, :context, :prefix, :text, :offset, :max, :relative


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

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

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

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

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

93
        argv = arguments.split(/(\B-[cCfqrptTslomA]|\B--(?:cited(_in_order)?|file|query|relative|prefix|text|style|template|locator|offset|max|suppress_author|))/)
94 95 96

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

98 99 100 101
      def locators
        @locators ||= []
      end

102 103 104 105 106 107 108 109 110
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

111
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
112 113
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
114 115 116 117
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
118
      end
119

120 121 122 123 124 125 126
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
127
      def bibtex_path
128
        bibtex_paths[0]
129
      end
130

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

        @bibliography
142 143
      end

144 145 146 147
      def query
        interpolate @query
      end

148
      def entries
149 150
        sort bibliography[query || config['query']]
      end
151

egon w. stemle's avatar
egon w. stemle committed
152 153 154 155 156 157 158 159
      def offset
        @offset ||= 0
      end

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

Sylvester Keil's avatar
Sylvester Keil committed
160
      def limit_entries?
egon w. stemle's avatar
egon w. stemle committed
161
        !offset.nil? || !max.nil?
Sylvester Keil's avatar
Sylvester Keil committed
162 163
      end

164
      def sort(unsorted)
165
        return unsorted if skip_sort?
166

167 168 169 170 171 172 173 174 175 176 177 178
        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
179
        end
180
 
181
        sorted
182
      end
183

184
      def sort_keys
185 186 187 188 189 190
        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 }
191 192
      end

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
      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

      def group?
        config['group_by'] != 'none'
      end
 
      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|
215
              grouper(items,keys.drop(1),order.drop(1))
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
            end
          end
        end
        grouper(ungrouped,group_keys,group_order)
      end
 
      def group_keys
        return @group_keys unless @group_keys.nil?

        @group_keys = Array(config['group_by'])
          .map { |key| key.to_s.split(/\s*,\s*/) }
          .flatten
          .map { |key| key == 'month' ? 'month_numeric' : key }
      end
 
      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
 
239
      def group_compare(key,v1,v2)
240 241
        case key
        when 'type'
242 243 244 245 246 247 248 249 250 251 252
          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
253
        else
254
          v1 <=> v2
255 256 257 258 259 260
        end
      end
      
      def group_value(key,item)
        case key
        when 'type'
261
          type_aliases[item.type.to_s] || item.type.to_s
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        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'
285
          type_names[value] || value.to_s
286
        when 'month_numeric'
287
          month_names[value] || "(unknown)"
288 289 290 291
        else
          value.to_s
        end
      end
292 293 294 295 296

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

297 298 299 300
      def type_aliases
        @type_aliases ||= Scholar.defaults['type_aliases'].merge(config['type_aliases'])
      end

301 302 303 304 305 306 307 308
      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
309
      end
310

311 312 313 314
      def suppress_author?
        !!@suppress_author
      end

Sylvester Keil's avatar
Sylvester Keil committed
315
      def raw_bibtex?
316
        config['use_raw_bibtex_entry']
Sylvester Keil's avatar
Sylvester Keil committed
317 318
      end

319 320 321 322 323 324 325 326 327
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
328
        repo = Hash.new { |h,k| h[k] = {} }
329

330 331 332 333 334 335 336 337
        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
338 339 340 341 342 343
      end

      def repository_path
        config['repository']
      end

344 345 346 347
      def replace_strings?
        config['replace_strings']
      end

348 349 350 351
      def join_strings?
        config['join_strings']
      end

352 353 354 355
      def cited_only?
        !!@cited
      end

356 357 358 359
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

360 361
      def extend_path(name)
        if name.nil? || name.empty?
362
          name = config['bibliography']
363
        end
364

365 366
        # Return as is if it is an absolute path
        # Improve by using Pathname from stdlib?
367
        return name if name.start_with?('/') && File.exists?(name)
368

369 370 371 372 373 374 375 376 377 378 379 380
        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
381
      end
382

383
      def reference_tag(entry, index = nil)
384
        return missing_reference unless entry
385

386
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
387
        reference = render_bibliography entry, index
388

389 390 391 392
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

393 394 395 396
      def style
        @style || config['style']
      end

397 398 399 400 401 402 403 404 405
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
406 407 408 409 410
        @bibliography_template || config['bibliography_template']
      end

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

413
        tmp = bibliography_template
414 415

        case
416
        when tmp.nil?, tmp.empty?
417 418 419 420 421
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

422
        @liquid_template = Liquid::Template.parse(tmp)
423 424
      end

425
      def bibliography_tag(entry, index)
426 427
        return missing_reference unless entry

428
        liquid_template.render(
429 430 431 432 433 434 435 436 437 438 439
          reference_data(entry,index)
            .merge(site.site_payload)
            .merge({
              'index' => index,
              'details' => details_link_for(entry)
            }),
          {
            :registers => { :site => site },
            :filters => [Jekyll::Filters]
          }
        )
440 441 442 443
      end

      def reference_data(entry, index = nil)
        {
444
          'entry' => liquidify(entry),
445
          'reference' => reference_tag(entry, index),
446
          'key' => entry.key,
447
          'type' => entry.type.to_s,
448
          'link' => repository_link_for(entry),
449 450
          'links' => repository_links_for(entry)
        }
451 452
      end

453 454 455 456
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
457
        e['type'] = entry.type.to_s
458

459 460 461
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
462
          tmp = entry.dup
463 464 465 466 467

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

468 469
          e['bibtex'] = tmp.to_s
        end
470

Sylvester Keil's avatar
Sylvester Keil committed
471 472 473 474
        if raw_bibtex?
          e['bibtex'] = "{%raw%}#{e['bibtex']}{%endraw%}"
        end

475 476 477
        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
478 479 480 481 482 483 484 485

          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
486 487 488 489 490
        end

        e
      end

491 492 493
      def bibtex_skip_fields
      end

494 495 496
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
497

498 499
      def details_file_for(entry)
        name = entry.key.to_s.dup
500

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

503
        if site.config['permalink'] == 'pretty'
504
          name << '/'
505 506 507
        else
          name << '.html'
        end
508
      end
509

510
      def repository_link_for(entry, base = base_url)
511 512 513
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

514 515 516 517 518
        return unless url

        File.join(base, url)
      end

519 520 521 522 523 524
      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
525
      def details_link_for(entry, base = base_url)
526
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
527
      end
528

Sylvester Keil's avatar
Sylvester Keil committed
529
      def base_url
530
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
531
      end
532

533 534 535
      def details_path
        config['details_dir']
      end
536

537 538 539 540
      def renderer(force = false)
        return @renderer if @renderer && !force
          
        @renderer = CiteProc::Ruby::Renderer.new :format => 'html',
Sylvester Keil's avatar
Sylvester Keil committed
541 542
          :style => style, :locale => config['locale']
      end
543

544 545
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
546
          cited_keys << entry.key
Sylvester Keil's avatar
Sylvester Keil committed
547
          cited_keys.uniq!
548

549
          item = citation_item_for entry, citation_number(entry.key)
550
          item.locator = locator
551

552 553
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
554 555
      end

556 557 558
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
559 560
      end

561
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
562 563
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
564
          c.data[:'citation-number'] = citation_number
565
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
566 567 568
        end
      end

569
      def cited_keys
570
        context['cited'] ||= []
571
      end
572

573 574
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
575 576
      end

577
      def link_target_for key
Alex Gil's avatar
Alex Gil committed
578
        "#{base_url}#{relative}##{[prefix, key].compact.join('-')}"
579 580
      end

581 582 583 584 585 586 587 588
      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
589
        end
590

591
        link_to link_target_for(keys[0]), render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
592
      end
Sylvester Keil's avatar
Sylvester Keil committed
593

594
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
595
        if bibliography.key?(key)
596
          link_to details_link_for(bibliography[key]), text || config['details_link']
597
        else
598
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
599 600
        end
      end
601

602 603 604 605 606 607
      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
608

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

611 612 613 614 615 616
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
617

618 619 620
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
621

622 623 624 625
      def cited_references
        context && context['cited'] || []
      end

626 627
      def keys
        # De-reference keys (in case they are variables)
628 629
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
630
        Array(@keys).map do |key|
631
          context[key] || key
632 633 634
        end
      end

635 636 637 638
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
639
          context[$1] || match
640 641 642
        end
      end

643
      def set_context_to(context)
644
        @context, @site, = context, context.registers[:site]
645
        config.merge!(site.config['scholar'] || {})
646
        self
647
      end
648
    end
649

650
  end
Hiren Patel's avatar
Hiren Patel committed
651
end