utilities.rb 9.5 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, :query,
18
        :context, :prefix, :text, :max
19 20 21 22 23 24 25 26 27 28

      def split_arguments(arguments)

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

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

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

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

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

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

55 56 57 58
          opts.on('-l', '--locator LOCATOR') do |locator|
            locators << locator
          end

Sylvester Keil's avatar
Sylvester Keil committed
59 60 61 62
          opts.on('-m', '--max MAX') do |max|
            @max = max
          end

63 64
          opts.on('-s', '--style STYLE') do |style|
            @style = style
65
          end
66 67 68 69

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

Sylvester Keil's avatar
Sylvester Keil committed
72
        argv = arguments.split(/(\B-[cfqptTslm]|\B--(?:cited|file|query|prefix|text|style|template|locator|max|))/)
73 74 75

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

77 78 79 80
      def locators
        @locators ||= []
      end

81 82 83 84 85 86 87 88 89
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

90
      def bibtex_options
91 92 93 94 95
        config['bibtex_options'] ||= {}
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
96
      end
97

98 99 100 101 102 103 104
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
105
      def bibtex_path
106
        bibtex_paths[0]
107
      end
108

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

        @bibliography
120 121
      end

122
      def entries
123 124
        sort bibliography[query || config['query']]
      end
125

Sylvester Keil's avatar
Sylvester Keil committed
126 127 128 129
      def limit_entries?
        !max.nil?
      end

130 131
      def sort(unsorted)
        return unsorted if config['sort_by'] == 'none'
132

133 134 135
        sorted = unsorted.sort_by { |e| e[config['sort_by']].to_s }
        sorted.reverse! if config['order'] =~ /^(desc|reverse)/i
        sorted
136
      end
137

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
      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

158 159 160 161
      def replace_strings?
        config['replace_strings']
      end

162 163 164 165
      def join_strings?
        config['join_strings']
      end

166 167 168 169
      def cited_only?
        !!@cited
      end

170 171
      def extend_path(name)
        if name.nil? || name.empty?
172
          name = config['bibliography']
173
        end
174

175 176
        # return as is if it is an absolute path
        return name if name.start_with?('/') && File.exists?(name)
177

178 179 180
        p = File.join(config['source'], name)
        p << '.bib' unless File.exists?(p)
        p
181
      end
182

Sylvester Keil's avatar
Sylvester Keil committed
183
      def reference_tag(entry, index = nil)
Sylvester Keil's avatar
Sylvester Keil committed
184
        return missing_reference unless entry
185

186
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
187
        reference = render_bibliography entry, index
188

Sylvester Keil's avatar
Sylvester Keil committed
189 190 191 192
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

193 194 195 196
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
197 198 199 200 201 202 203 204 205
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
206 207 208 209 210
        @bibliography_template || config['bibliography_template']
      end

      def liquid_template
        return @liquid_template if @liquid_template
211

212
        tmp = bibliography_template
213 214

        case
215
        when tmp.nil?, tmp.empty?
216 217 218 219 220
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

221
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
222 223
      end

224
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
225 226
        return missing_reference unless entry

227
        liquid_template.render({
Sylvester Keil's avatar
Sylvester Keil committed
228
          'entry' => liquidify(entry),
Sylvester Keil's avatar
Sylvester Keil committed
229
          'reference' => reference_tag(entry, index),
230 231 232 233 234
          'key' => entry.key,
          'type' => entry.type,
          'link' => repository_link_for(entry),
          'index' => index
        })
235 236
      end

Sylvester Keil's avatar
Sylvester Keil committed
237 238 239 240 241 242
      def liquidify(entry)
        e = {}

        e['key'] = entry.key
        e['type'] = entry.type

Sylvester Keil's avatar
Sylvester Keil committed
243 244 245 246 247 248 249
        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
250 251 252 253 254 255 256 257 258

        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

259 260 261
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
262

263 264
      def details_file_for(entry)
        name = entry.key.to_s.dup
265

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

268 269
        [name, 'html'].join('.')
      end
270

271 272 273 274 275 276 277
      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
278
      def details_link_for(entry, base = base_url)
279
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
280
      end
281

Sylvester Keil's avatar
Sylvester Keil committed
282
      def base_url
283
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
284
      end
285

286 287 288
      def details_path
        config['details_dir']
      end
289

Sylvester Keil's avatar
Sylvester Keil committed
290 291 292 293
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end
294

295 296
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
Sylvester Keil's avatar
Sylvester Keil committed
297
          cited_keys << entry.key
298

Sylvester Keil's avatar
Sylvester Keil committed
299
          item = citation_item_for entry, citation_number
300
          item.locator = locator
301

302 303
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
304 305
      end

Sylvester Keil's avatar
Sylvester Keil committed
306 307 308
      def render_bibliography(entry, index = nil)
        renderer.render citation_item_for(entry, index),
          STYLES[style].bibliography
Sylvester Keil's avatar
Sylvester Keil committed
309 310
      end

Sylvester Keil's avatar
Sylvester Keil committed
311
      def citation_item_for(entry, citation_number = nil)
Sylvester Keil's avatar
Sylvester Keil committed
312 313
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
Sylvester Keil's avatar
Sylvester Keil committed
314
          c.data[:'citation-number'] = citation_number
Sylvester Keil's avatar
Sylvester Keil committed
315 316 317
        end
      end

318
      def cited_keys
319
        context['cited'] ||= []
320
      end
321

Sylvester Keil's avatar
Sylvester Keil committed
322 323 324 325 326 327
      def citation_number
        number = context['citation_number'] || 1
        context['citation_number'] = number.succ
        number
      end

328 329
      def cite(keys)
        items = keys.map do |key|
Sylvester Keil's avatar
Sylvester Keil committed
330 331 332
          # dereference variables in current scope
          key = context.scopes.last[key] || key

333 334 335 336 337 338
          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
339
        end
340 341

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

344
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
345
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
346
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
347
        else
348
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
349 350
        end
      end
351

Sylvester Keil's avatar
Sylvester Keil committed
352 353 354 355 356 357
      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
358

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

Sylvester Keil's avatar
Sylvester Keil committed
361 362 363 364 365 366
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
367

Sylvester Keil's avatar
Sylvester Keil committed
368 369 370
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
371

372 373 374 375
      def cited_references
        context && context['cited'] || []
      end

376 377 378 379 380 381 382
      def keys
        # De-reference keys (in case they are variables)
        Array(@keys).map do |key|
          context.send(:resolve, key) || key
        end
      end

Sylvester Keil's avatar
Sylvester Keil committed
383
      def set_context_to(context)
384
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
385
        config.merge!(site.config['scholar'] || {})
386
        self
Sylvester Keil's avatar
Sylvester Keil committed
387
      end
388
    end
389

390
  end
Hiren Patel's avatar
Hiren Patel committed
391
end