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

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

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

66 67 68 69
          opts.on('-o', '--offset OFFSET') do |offset|
            @offset = offset.to_i
          end

Sylvester Keil's avatar
Sylvester Keil committed
70
          opts.on('-m', '--max MAX') do |max|
71
            @max = max.to_i
Sylvester Keil's avatar
Sylvester Keil committed
72 73
          end

74 75
          opts.on('-s', '--style STYLE') do |style|
            @style = style
76
          end
77 78 79 80

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

83
        argv = arguments.split(/(\B-[cCfqptTslomA]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|template|locator|offset|max|suppress_author|))/)
84 85 86

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

88 89 90 91
      def locators
        @locators ||= []
      end

92 93 94 95 96 97 98 99 100
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

101
      def bibtex_options
Sylvester Keil's avatar
Sylvester Keil committed
102 103
        @bibtex_options ||=
          (config['bibtex_options'] || {}).symbolize_keys
104 105 106 107
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
108
      end
109

110 111 112 113 114 115 116
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
117
      def bibtex_path
118
        bibtex_paths[0]
119
      end
120

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

        @bibliography
132 133
      end

134 135 136 137
      def query
        interpolate @query
      end

138
      def entries
139 140
        sort bibliography[query || config['query']]
      end
141

egon w. stemle's avatar
egon w. stemle committed
142 143 144 145 146 147 148 149 150 151 152 153
      def offset
        @offset ||= 0
      end

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

      def limit_entries?
        !offset.nil? || !max.nil?
      end

154
      def sort(unsorted)
Sylvester Keil's avatar
Sylvester Keil committed
155
        return unsorted if skip_sort?
156

157 158 159 160
        sorted = unsorted.sort_by do |e|
          e.values_at(*sort_keys).map { |v| v.nil? ? BibTeX::Value.new : v }
        end

161 162
        sorted.reverse! if config['order'] =~ /^(desc|reverse)/i
        sorted
163
      end
164

165
      def sort_keys
166 167 168 169 170 171
        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 }
172 173
      end

Sylvester Keil's avatar
Sylvester Keil committed
174 175 176 177
      def suppress_author?
        !!@suppress_author
      end

178 179 180 181 182 183 184 185 186
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
187
        repo = Hash.new { |h,k| h[k] = {} }
188

189 190 191 192 193 194 195 196
        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
197 198 199 200 201 202
      end

      def repository_path
        config['repository']
      end

203 204 205 206
      def replace_strings?
        config['replace_strings']
      end

207 208 209 210
      def join_strings?
        config['join_strings']
      end

211 212 213 214
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
215 216 217 218
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

219 220
      def extend_path(name)
        if name.nil? || name.empty?
221
          name = config['bibliography']
222
        end
223

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

Sylvester Keil's avatar
Sylvester Keil committed
228 229 230 231 232 233 234 235 236 237 238 239
        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
240
      end
241

Sylvester Keil's avatar
Sylvester Keil committed
242
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
243
        return missing_reference unless entry
244

245
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
246
        reference = render_bibliography entry, index
247

Sylvester Keil's avatar
Sylvester Keil committed
248 249 250 251
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

252 253 254 255
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
256 257 258 259 260 261 262 263 264
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
265 266 267 268 269
        @bibliography_template || config['bibliography_template']
      end

      def liquid_template
        return @liquid_template if @liquid_template
270

271
        tmp = bibliography_template
272 273

        case
274
        when tmp.nil?, tmp.empty?
275 276 277 278 279
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

280
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
281 282
      end

283
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
284 285
        return missing_reference unless entry

286
        liquid_template.render({
Sylvester Keil's avatar
Sylvester Keil committed
287
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
288
          'reference' => reference_tag(entry, index),
289
          'key' => entry.key,
290
          'type' => entry.type.to_s,
291
          'link' => repository_link_for(entry),
292
          'links' => repository_links_for(entry),
293 294
          'index' => index,
          'details' => details_link_for(entry)
295
        })
296 297
      end

Sylvester Keil's avatar
Sylvester Keil committed
298 299 300 301
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
302
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
303

304 305 306
        if entry.field_names(config['bibtex_skip_fields']).empty?
          e['bibtex'] = entry.to_s
        else
Sylvester Keil's avatar
Sylvester Keil committed
307
          tmp = entry.dup
308 309 310 311 312

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

Sylvester Keil's avatar
Sylvester Keil committed
313 314
          e['bibtex'] = tmp.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
315 316 317 318 319 320 321 322 323

        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

324 325 326
      def bibtex_skip_fields
      end

327 328 329
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
330

331 332
      def details_file_for(entry)
        name = entry.key.to_s.dup
333

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

336
        if site.config['permalink'] == 'pretty'
Sylvester Keil's avatar
fix #55  
Sylvester Keil committed
337
          name << '/index.html'
338 339 340
        else
          name << '.html'
        end
341
      end
342

343
      def repository_link_for(entry, base = base_url)
344 345 346
        links = repository[entry.key]
        url   = links['pdf'] || links['ps']

347 348 349 350 351
        return unless url

        File.join(base, url)
      end

352 353 354 355 356 357
      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
358
      def details_link_for(entry, base = base_url)
359
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
360
      end
361

Sylvester Keil's avatar
Sylvester Keil committed
362
      def base_url
363
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
364
      end
365

366 367 368
      def details_path
        config['details_dir']
      end
369

Sylvester Keil's avatar
Sylvester Keil committed
370 371 372 373
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end
374

375 376
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
377
          cited_keys << entry.key
Sylvester Keil's avatar
4.2.1  
Sylvester Keil committed
378
          cited_keys.uniq!
379

Sylvester Keil's avatar
Sylvester Keil committed
380
          item = citation_item_for entry, citation_number(entry.key)
381
          item.locator = locator
382

383 384
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
385 386
      end

Sylvester Keil's avatar
Sylvester Keil committed
387 388 389
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
390 391
      end

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

400
      def cited_keys
401
        context['cited'] ||= []
402
      end
403

Sylvester Keil's avatar
Sylvester Keil committed
404 405
      def citation_number(key)
        (context['citation_numbers'] ||= {})[key] ||= cited_keys.length
Sylvester Keil's avatar
Sylvester Keil committed
406 407
      end

408 409 410 411 412 413 414 415
      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
416
        end
417 418

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

421
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
422
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
423
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
424
        else
425
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
426 427
        end
      end
428

Sylvester Keil's avatar
Sylvester Keil committed
429 430 431 432 433 434
      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
435

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

Sylvester Keil's avatar
Sylvester Keil committed
438 439 440 441 442 443
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
444

Sylvester Keil's avatar
Sylvester Keil committed
445 446 447
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
448

449 450 451 452
      def cited_references
        context && context['cited'] || []
      end

453 454
      def keys
        # De-reference keys (in case they are variables)
Sylvester Keil's avatar
Sylvester Keil committed
455 456
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
457 458 459 460 461
        Array(@keys).map do |key|
          context.send(:resolve, key) || key
        end
      end

462 463 464 465 466 467 468 469
      def interpolate(string)
        return unless string

        string.gsub(/{{\s*([\w\.]+)\s*}}/) do |match|
          context.send(:resolve, $1) || match
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
470
      def set_context_to(context)
471
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
472
        config.merge!(site.config['scholar'] || {})
473
        self
Sylvester Keil's avatar
Sylvester Keil committed
474
      end
475
    end
476

477
  end
Hiren Patel's avatar
Hiren Patel committed
478
end