utilities.rb 9.93 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, :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

41
          opts.on('-f', '--file FILE') do |file|
42 43
            @bibtex_files ||= []
            @bibtex_files << file
44 45 46 47 48 49 50 51 52 53 54 55 56
          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
57

58 59 60 61
          opts.on('-l', '--locator LOCATOR') do |locator|
            locators << locator
          end

Sylvester Keil's avatar
Sylvester Keil committed
62 63 64 65
          opts.on('-m', '--max MAX') do |max|
            @max = max
          end

66 67
          opts.on('-s', '--style STYLE') do |style|
            @style = style
68
          end
69 70 71 72

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

Sylvester Keil's avatar
Sylvester Keil committed
75
        argv = arguments.split(/(\B-[cCfqptTslm]|\B--(?:cited(_in_order)?|file|query|prefix|text|style|template|locator|max|))/)
76 77 78

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

80 81 82 83
      def locators
        @locators ||= []
      end

84 85 86 87 88 89 90 91 92
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

93
      def bibtex_options
94 95 96 97 98
        config['bibtex_options'] ||= {}
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
99
      end
100

101 102 103 104 105 106 107
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
108
      def bibtex_path
109
        bibtex_paths[0]
110
      end
111

112
      def bibliography
113
        unless @bibliography
114 115 116 117
          @bibliography = BibTeX.parse(
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
118
          @bibliography.replace_strings if replace_strings?
119
          @bibliography.join if join_strings? && replace_strings?
120 121 122
        end

        @bibliography
123 124
      end

125 126 127 128
      def query
        interpolate @query
      end

129
      def entries
130 131
        sort bibliography[query || config['query']]
      end
132

Sylvester Keil's avatar
Sylvester Keil committed
133 134 135 136
      def limit_entries?
        !max.nil?
      end

137
      def sort(unsorted)
Sylvester Keil's avatar
Sylvester Keil committed
138
        return unsorted if skip_sort?
139

140 141 142
        sorted = unsorted.sort_by { |e| e[config['sort_by']].to_s }
        sorted.reverse! if config['order'] =~ /^(desc|reverse)/i
        sorted
143
      end
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
      def repository?
        !config['repository'].nil? && !config['repository'].empty?
      end

      def repository
        @repository ||= load_repository
      end

      def load_repository
        return {} unless repository?

        Hash[Dir[File.join(repository_path, '**/*.{pdf,ps}')].map { |path|
          [File.basename(path).sub(/\.(pdf|ps)$/, ''), path]
        }]
      end

      def repository_path
        config['repository']
      end

165 166 167 168
      def replace_strings?
        config['replace_strings']
      end

169 170 171 172
      def join_strings?
        config['join_strings']
      end

173 174 175 176
      def cited_only?
        !!@cited
      end

Sylvester Keil's avatar
Sylvester Keil committed
177 178 179 180
      def skip_sort?
        @skip_sort || config['sort_by'] == 'none'
      end

181 182
      def extend_path(name)
        if name.nil? || name.empty?
183
          name = config['bibliography']
184
        end
185

186 187
        # return as is if it is an absolute path
        return name if name.start_with?('/') && File.exists?(name)
188

189 190 191
        p = File.join(config['source'], name)
        p << '.bib' unless File.exists?(p)
        p
192
      end
193

Sylvester Keil's avatar
Sylvester Keil committed
194
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
195
        return missing_reference unless entry
196

197
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
198
        reference = render_bibliography entry, index
199

Sylvester Keil's avatar
Sylvester Keil committed
200 201 202 203
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

204 205 206 207
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
208 209 210 211 212 213 214 215 216
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
217 218 219 220 221
        @bibliography_template || config['bibliography_template']
      end

      def liquid_template
        return @liquid_template if @liquid_template
222

223
        tmp = bibliography_template
224 225

        case
226
        when tmp.nil?, tmp.empty?
227 228 229 230 231
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

232
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
233 234
      end

235
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
236 237
        return missing_reference unless entry

238
        liquid_template.render({
Sylvester Keil's avatar
Sylvester Keil committed
239
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
240
          'reference' => reference_tag(entry, index),
241
          'key' => entry.key,
242
          'type' => entry.type.to_s,
243 244 245
          'link' => repository_link_for(entry),
          'index' => index
        })
246 247
      end

Sylvester Keil's avatar
Sylvester Keil committed
248 249 250 251
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
252
        e['type'] = entry.type.to_s
Sylvester Keil's avatar
Sylvester Keil committed
253

Sylvester Keil's avatar
Sylvester Keil committed
254 255 256 257 258 259 260
        if entry.field?(:abstract)
          tmp = entry.dup
          tmp.delete :abstract
          e['bibtex'] = tmp.to_s
        else
          e['bibtex'] = entry.to_s
        end
Sylvester Keil's avatar
Sylvester Keil committed
261 262 263 264 265 266 267 268 269

        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

270 271 272
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
273

274 275
      def details_file_for(entry)
        name = entry.key.to_s.dup
276

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

279 280
        [name, 'html'].join('.')
      end
281

282 283 284 285 286 287 288
      def repository_link_for(entry, base = base_url)
        url = repository[entry.key]
        return unless url

        File.join(base, url)
      end

Sylvester Keil's avatar
Sylvester Keil committed
289
      def details_link_for(entry, base = base_url)
290
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
291
      end
292

Sylvester Keil's avatar
Sylvester Keil committed
293
      def base_url
294
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
295
      end
296

297 298 299
      def details_path
        config['details_dir']
      end
300

Sylvester Keil's avatar
Sylvester Keil committed
301 302 303 304
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end
305

306 307
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
308
          cited_keys << entry.key
309

Sylvester Keil's avatar
Sylvester Keil committed
310
          item = citation_item_for entry, citation_number
311
          item.locator = locator
312

313 314
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
315 316
      end

Sylvester Keil's avatar
Sylvester Keil committed
317 318 319
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
320 321
      end

Sylvester Keil's avatar
Sylvester Keil committed
322
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
323 324
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
325
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
326 327 328
        end
      end

329
      def cited_keys
330
        context['cited'] ||= []
331
      end
332

Sylvester Keil's avatar
Sylvester Keil committed
333 334 335 336 337 338
      def citation_number
        number = context['citation_number'] || 1
        context['citation_number'] = number.succ
        number
      end

339 340 341 342 343 344 345 346
      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
347
        end
348 349

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

352
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
353
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
354
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
355
        else
356
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
357 358
        end
      end
359

Sylvester Keil's avatar
Sylvester Keil committed
360 361 362 363 364 365
      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
366

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

Sylvester Keil's avatar
Sylvester Keil committed
369 370 371 372 373 374
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
375

Sylvester Keil's avatar
Sylvester Keil committed
376 377 378
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
379

380 381 382 383
      def cited_references
        context && context['cited'] || []
      end

384 385
      def keys
        # De-reference keys (in case they are variables)
Sylvester Keil's avatar
Sylvester Keil committed
386 387
        # We need to do this every time, to support for loops,
        # where the context can change for each invocation.
388 389 390 391 392
        Array(@keys).map do |key|
          context.send(:resolve, key) || key
        end
      end

393 394 395 396 397 398 399 400
      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
401
      def set_context_to(context)
402
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
403
        config.merge!(site.config['scholar'] || {})
404
        self
Sylvester Keil's avatar
Sylvester Keil committed
405
      end
406
    end
407

408
  end
Hiren Patel's avatar
Hiren Patel committed
409
end