utilities.rb 16.8 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

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

23
24
25
26
27
28
29
30
31
32

      def split_arguments(arguments)

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

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

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

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

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

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

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

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

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

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

Sylvester Keil's avatar
Sylvester Keil committed
71
          opts.on('-L', '--label LABEL') do |label|
72
            labels << label
Sylvester Keil's avatar
Sylvester Keil committed
73
74
          end

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

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

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

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

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

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

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

Sylvester Keil's avatar
Sylvester Keil committed
104
        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|))/)
105
106
107

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

109
110
111
112
      def locators
        @locators ||= []
      end

113
114
115
116
      def labels
        @labels ||= []
      end

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

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

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

      def bibtex_filters
        config['bibtex_filters'] ||= []
133
      end
134

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

      # :nodoc: backwards compatibility
142
      def bibtex_path
143
        bibtex_paths[0]
144
      end
145

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

        @bibliography
157
158
      end

159
160
161
162
      def query
        interpolate @query
      end

163
      def entries
164
165
        sort bibliography[query || config['query']]
      end
166

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

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

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

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

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

196
        sorted
197
      end
198

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

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

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

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

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

        grouper(ungrouped, group_keys, group_order)
240
      end
Sylvester Keil's avatar
Sylvester Keil committed
241

242
243
244
      def group_keys
        return @group_keys unless @group_keys.nil?

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

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

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

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

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

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

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

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

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

Sylvester Keil's avatar
Sylvester Keil committed
334
335
336
337
      def suppress_author?
        !!@suppress_author
      end

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

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

      def repository
        @repository ||= load_repository
      end

      def load_repository
351
        repo = Hash.new { |h,k| h[k] = {} }
352

353
        return repo unless repository?
354
355
356
357
358
359
        
        # ensure that the base directory format is literally 
        # the same as the entries that are in the directory
        base = Dir[site.source][0] 
        
        Dir[File.join(site.source, repository_path, '**/*')].each do |path|
360
          extname = File.extname(path)
361
          repo[File.basename(path, extname)][extname[1..-1]] = Pathname(path).relative_path_from(Pathname(base))
362
363
364
        end

        repo
365
366
367
368
369
370
      end

      def repository_path
        config['repository']
      end

371
372
373
374
      def replace_strings?
        config['replace_strings']
      end

375
376
377
378
      def join_strings?
        config['join_strings']
      end

379
380
381
382
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
383
384
385
386
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

387
388
      def extend_path(name)
        if name.nil? || name.empty?
389
          name = config['bibliography']
390
        end
391

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

Sylvester Keil's avatar
Sylvester Keil committed
396
397
398
399
400
401
402
        name = File.join scholar_source, name
        name << '.bib' if File.extname(name).empty? && !File.exists?(name)
        name
      end

      def scholar_source
        source = config['source']
403
        
Sylvester Keil's avatar
Sylvester Keil committed
404
405
406
407
        # Improve by using Pathname from stdlib?
        return source if source.start_with?('/') && File.exists?(source)

        File.join site.source, source
408
      end
409

Alex Gil's avatar
Alex Gil committed
410
      def relative
411
        config['relative']
Alex Gil's avatar
Alex Gil committed
412
413
      end

Sylvester Keil's avatar
Sylvester Keil committed
414
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
415
        return missing_reference unless entry
416

417
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
418
        reference = render_bibliography entry, index
419

Sylvester Keil's avatar
Sylvester Keil committed
420
421
422
423
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

424
425
426
427
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
428
429
430
431
432
433
434
435
436
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
437
438
439
440
441
        @bibliography_template || config['bibliography_template']
      end

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

444
        tmp = bibliography_template
445
446

        case
447
        when tmp.nil?, tmp.empty?
448
449
450
451
452
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

453
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
454
455
      end

456
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
457
458
        return missing_reference unless entry

459
        liquid_template.render(
460
461
462
463
464
465
466
467
468
469
470
          reference_data(entry,index)
            .merge(site.site_payload)
            .merge({
              'index' => index,
              'details' => details_link_for(entry)
            }),
          {
            :registers => { :site => site },
            :filters => [Jekyll::Filters]
          }
        )
471
472
473
474
      end

      def reference_data(entry, index = nil)
        {
Sylvester Keil's avatar
Sylvester Keil committed
475
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
476
          'reference' => reference_tag(entry, index),
477
          'key' => entry.key,
478
          'type' => entry.type.to_s,
479
          'link' => repository_link_for(entry),
480
481
          'links' => repository_links_for(entry)
        }
482
483
      end

Sylvester Keil's avatar
Sylvester Keil committed
484
485
486
487
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
488
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
489

490
491
492
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
Sylvester Keil's avatar
Sylvester Keil committed
493
          tmp = entry.dup
494
495
496
497
498

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

Sylvester Keil's avatar
Sylvester Keil committed
499
500
          e['bibtex'] = tmp.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
501

Sylvester Keil's avatar
Sylvester Keil committed
502
503
504
505
        if raw_bibtex?
          e['bibtex'] = "{%raw%}#{e['bibtex']}{%endraw%}"
        end

Sylvester Keil's avatar
Sylvester Keil committed
506
507
508
        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
509
510

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

        e
      end

526
527
528
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
529

530
531
      def details_file_for(entry)
        name = entry.key.to_s.dup
532

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

535
        if site.config['permalink'] == 'pretty'
536
          name << '/'
537
538
539
        else
          name << '.html'
        end
540
      end
541

542
      def repository_link_for(entry, base = base_url)
543
544
545
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

546
547
548
549
550
        return unless url

        File.join(base, url)
      end

551
552
553
554
555
556
      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
557
      def details_link_for(entry, base = base_url)
558
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
559
      end
560

Sylvester Keil's avatar
Sylvester Keil committed
561
      def base_url
562
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
563
      end
564

565
566
567
      def details_path
        config['details_dir']
      end
568

569
570
      def renderer(force = false)
        return @renderer if @renderer && !force
571

572
        @renderer = CiteProc::Ruby::Renderer.new :format => 'html',
Sylvester Keil's avatar
Sylvester Keil committed
573
574
          :style => style, :locale => config['locale']
      end
575

576
      def render_citation(items)
577
        renderer.render items.zip(locators.zip(labels)).map { |entry, (locator, label)|
Sylvester Keil's avatar
Sylvester Keil committed
578
          cited_keys << entry.key
Sylvester Keil's avatar
4.2.1    
Sylvester Keil committed
579
          cited_keys.uniq!
580

Sylvester Keil's avatar
Sylvester Keil committed
581
          item = citation_item_for entry, citation_number(entry.key)
582
          item.locator = locator
Sylvester Keil's avatar
Sylvester Keil committed
583
          item.label = label unless label.nil?
584

585
586
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
587
588
      end

Sylvester Keil's avatar
Sylvester Keil committed
589
590
591
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
592
593
      end

Sylvester Keil's avatar
Sylvester Keil committed
594
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
595
596
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
597
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
598
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
599
600
601
        end
      end

602
      def cited_keys
603
        context['cited'] ||= []
604
      end
605

Sylvester Keil's avatar
Sylvester Keil committed
606
607
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
Sylvester Keil's avatar
Sylvester Keil committed
608
609
      end

Alex Gil's avatar
Alex Gil committed
610
611
      def link_target_for(key)
        "#{relative}##{[prefix, key].compact.join('-')}"
612
613
      end

614
615
616
617
618
619
620
621
      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
622
        end
623

624
        link_to link_target_for(keys[0]), render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
625
      end
Sylvester Keil's avatar
Sylvester Keil committed
626

627
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
628
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
629
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
630
        else
631
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
632
633
        end
      end
634

Sylvester Keil's avatar
Sylvester Keil committed
635
636
637
638
639
640
      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
641

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

Sylvester Keil's avatar
Sylvester Keil committed
644
645
646
647
648
649
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
650

Sylvester Keil's avatar
Sylvester Keil committed
651
652
653
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
654

655
656
657
658
      def cited_references
        context && context['cited'] || []
      end

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

668
669
670
671
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
672
          context[$1] || match
673
674
675
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
676
      def set_context_to(context)
677
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
678
        config.merge!(site.config['scholar'] || {})
679
        self
Sylvester Keil's avatar
Sylvester Keil committed
680
      end
681
    end
682

683
  end
Hiren Patel's avatar
Hiren Patel committed
684
end