utilities.rb 11.6 KB
Newer Older
1
module Jekyll
2
  class Scholar
3

Sylvester Keil's avatar
Sylvester Keil committed
4 5 6 7 8 9 10 11
    # 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|
      h[k.to_s] = CSL::Style.load k
    end


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

17
      attr_reader :config, :site, :context, :prefix, :text, :max
18 19 20 21 22 23 24 25 26 27

      def split_arguments(arguments)

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

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

        [args, opts]
      end
28 29 30 31 32 33 34 35 36

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

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

37 38 39 40
          opts.on('-C', '--cited_in_order') do |cited|
            @cited, @skip_sort = true, true
          end

41 42 43 44
          opts.on('-A', '--suppress_author') do |cited|
            @suppress_author = true
          end

45
          opts.on('-f', '--file FILE') do |file|
46 47
            @bibtex_files ||= []
            @bibtex_files << file
48 49 50 51 52 53 54 55 56 57 58 59 60
          end

          opts.on('-q', '--query QUERY') do |query|
            @query = query
          end

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

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

62 63 64 65
          opts.on('-l', '--locator LOCATOR') do |locator|
            locators << locator
          end

Sylvester Keil's avatar
Sylvester Keil committed
66 67 68 69
          opts.on('-m', '--max MAX') do |max|
            @max = max
          end

70 71
          opts.on('-s', '--style STYLE') do |style|
            @style = style
72
          end
73 74 75 76

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

79
        argv = arguments.split(/(\B-[cCfqptTslmA]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|template|locator|max|suppress_author|))/)
80 81 82

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

84 85 86 87
      def locators
        @locators ||= []
      end

88 89 90 91 92 93 94 95 96
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

97
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
98 99
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
100 101 102 103
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
104
      end
105

106 107 108 109 110 111 112
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
113
      def bibtex_path
114
        bibtex_paths[0]
115
      end
116

117
      def bibliography
118
        unless @bibliography
119 120 121 122
          @bibliography = BibTeX.parse(
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
123
          @bibliography.replace_strings if replace_strings?
124
          @bibliography.join if join_strings? && replace_strings?
125 126 127
        end

        @bibliography
128 129
      end

130 131 132 133
      def query
        interpolate @query
      end

134
      def entries
135 136
        sort bibliography[query || config['query']]
      end
137

Sylvester Keil's avatar
Sylvester Keil committed
138 139 140 141
      def limit_entries?
        !max.nil?
      end

142
      def sort(unsorted)
143
        return unsorted if skip_sort?
144

145 146 147 148
        sorted = unsorted.sort_by do |e|
          e.values_at(*sort_keys).map { |v| v.nil? ? BibTeX::Value.new : v }
        end

149 150
        sorted.reverse! if config['order'] =~ /^(desc|reverse)/i
        sorted
151
      end
152

153
      def sort_keys
154 155 156 157 158 159
        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 }
160 161
      end

162 163 164 165
      def suppress_author?
        !!@suppress_author
      end

166 167 168 169 170 171 172 173 174
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
175
        repo = Hash.new { |h,k| h[k] = {} }
176

177 178 179 180 181 182 183 184
        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
185 186 187 188 189 190
      end

      def repository_path
        config['repository']
      end

191 192 193 194
      def replace_strings?
        config['replace_strings']
      end

195 196 197 198
      def join_strings?
        config['join_strings']
      end

199 200 201 202
      def cited_only?
        !!@cited
      end

203 204 205 206
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

207 208
      def extend_path(name)
        if name.nil? || name.empty?
209
          name = config['bibliography']
210
        end
211

212 213
        # Return as is if it is an absolute path
        # Improve by using Pathname from stdlib?
214
        return name if name.start_with?('/') && File.exists?(name)
215

216 217 218 219 220 221 222 223 224 225 226 227
        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
228
      end
229

230
      def reference_tag(entry, index = nil)
231
        return missing_reference unless entry
232

233
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
234
        reference = render_bibliography entry, index
235

236 237 238 239
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

240 241 242 243
      def style
        @style || config['style']
      end

244 245 246 247 248 249 250 251 252
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
253 254 255 256 257
        @bibliography_template || config['bibliography_template']
      end

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

260
        tmp = bibliography_template
261 262

        case
263
        when tmp.nil?, tmp.empty?
264 265 266 267 268
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

269
        @liquid_template = Liquid::Template.parse(tmp)
270 271
      end

272
      def bibliography_tag(entry, index)
273 274
        return missing_reference unless entry

275 276 277 278 279 280 281 282 283
        liquid_template.render(
          reference_data(entry,index).merge({
            'index' => index,
            'details' => details_link_for(entry)
        }))
      end

      def reference_data(entry, index = nil)
        {
284
          'entry' => liquidify(entry),
285
          'reference' => reference_tag(entry, index),
286
          'key' => entry.key,
287
          'type' => entry.type.to_s,
288
          'link' => repository_link_for(entry),
289 290
          'links' => repository_links_for(entry)
        }
291 292
      end

293 294 295 296
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
297
        e['type'] = entry.type.to_s
298

299 300 301
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
302
          tmp = entry.dup
303 304 305 306 307

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

308 309
          e['bibtex'] = tmp.to_s
        end
310 311 312 313 314 315 316 317 318

        entry.fields.each do |key, value|
          value = value.convert(*bibtex_filters) unless bibtex_filters.empty?
          e[key.to_s] = value.to_s
        end

        e
      end

319 320 321
      def bibtex_skip_fields
      end

322 323 324
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
325

326 327
      def details_file_for(entry)
        name = entry.key.to_s.dup
328

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

331
        if site.config['permalink'] == 'pretty'
332
          name << '/'
333 334 335
        else
          name << '.html'
        end
336
      end
337

338
      def repository_link_for(entry, base = base_url)
339 340 341
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

342 343 344 345 346
        return unless url

        File.join(base, url)
      end

347 348 349 350 351 352
      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
353
      def details_link_for(entry, base = base_url)
354
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
355
      end
356

Sylvester Keil's avatar
Sylvester Keil committed
357
      def base_url
358
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
359
      end
360

361 362 363
      def details_path
        config['details_dir']
      end
364

Sylvester Keil's avatar
Sylvester Keil committed
365 366 367 368
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end
369

370 371
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
372
          cited_keys << entry.key
Sylvester Keil's avatar
Sylvester Keil committed
373
          cited_keys.uniq!
374

375
          item = citation_item_for entry, citation_number(entry.key)
376
          item.locator = locator
377

378 379
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
380 381
      end

382 383 384
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
385 386
      end

387
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
388 389
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
390
          c.data[:'citation-number'] = citation_number
391
          c.data.suppress! 'author' if suppress_author?
Sylvester Keil's avatar
Sylvester Keil committed
392 393 394
        end
      end

395
      def cited_keys
396
        context['cited'] ||= []
397
      end
398

399 400
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
401 402
      end

403 404 405 406 407 408 409 410
      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
411
        end
412 413

        link_to "##{[prefix, keys[0]].compact.join('-')}", render_citation(items)
Sylvester Keil's avatar
Sylvester Keil committed
414
      end
Sylvester Keil's avatar
Sylvester Keil committed
415

416
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
417
        if bibliography.key?(key)
418
          link_to details_link_for(bibliography[key]), text || config['details_link']
419
        else
420
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
421 422
        end
      end
423

424 425 426 427 428 429
      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
430

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

433 434 435 436 437 438
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
439

440 441 442
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
443

444 445 446 447
      def cited_references
        context && context['cited'] || []
      end

448 449
      def keys
        # De-reference keys (in case they are variables)
450 451
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
452
        Array(@keys).map do |key|
453
          context[key] || key
454 455 456
        end
      end

457 458 459 460
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
461
          context[$1] || match
462 463 464
        end
      end

465
      def set_context_to(context)
466
        @context, @site, = context, context.registers[:site]
467
        config.merge!(site.config['scholar'] || {})
468
        self
469
      end
470
    end
471

472
  end
Hiren Patel's avatar
Hiren Patel committed
473
end