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

      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

59 60
          opts.on('-s', '--style STYLE') do |style|
            @style = style
61
          end
62 63 64 65

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

68
        argv = arguments.split(/(\B-[cfqptTsl]|\B--(?:cited|file|query|prefix|text|style|template|locator|))/)
69 70 71

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

73 74 75 76
      def locators
        @locators ||= []
      end

77 78 79 80 81 82 83 84 85
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

86
      def bibtex_options
87 88 89 90 91
        config['bibtex_options'] ||= {}
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
92
      end
93

94 95 96 97 98 99 100
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
101
      def bibtex_path
102
        bibtex_paths[0]
103
      end
104

105
      def bibliography
106
        unless @bibliography
107 108 109 110
          @bibliography = BibTeX.parse(
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
111 112 113 114
          @bibliography.replace_strings if replace_strings?
        end

        @bibliography
115 116
      end

117
      def entries
118
        b = bibliography[query || config['query']]
119 120

        unless config['sort_by'] == 'none'
121
          b = b.sort_by { |e| e[config['sort_by']].to_s }
122 123
          b.reverse! if config['order'] =~ /^(desc|reverse)/i
        end
124

125 126
        b
      end
127

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      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

148 149 150 151
      def replace_strings?
        config['replace_strings']
      end

152 153 154 155
      def cited_only?
        !!@cited
      end

156 157
      def extend_path(name)
        if name.nil? || name.empty?
158
          name = config['bibliography']
159
        end
160

161 162
        # return as is if it is an absolute path
        return name if name.start_with?('/') && File.exists?(name)
163

164 165 166
        p = File.join(config['source'], name)
        p << '.bib' unless File.exists?(p)
        p
167
      end
168

169
      def reference_tag(entry)
Sylvester Keil's avatar
Sylvester Keil committed
170
        return missing_reference unless entry
171

172
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
173
        reference = render_bibliography entry
174

Sylvester Keil's avatar
Sylvester Keil committed
175 176 177 178
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

179 180 181 182
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
183 184 185 186 187 188 189 190 191
      def missing_reference
        config['missing_reference']
      end

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

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

      def liquid_template
        return @liquid_template if @liquid_template
197

198
        tmp = bibliography_template
199 200

        case
201
        when tmp.nil?, tmp.empty?
202 203 204 205 206
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

207
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
208 209
      end

210
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
211 212
        return missing_reference unless entry

213
        liquid_template.render({
Sylvester Keil's avatar
Sylvester Keil committed
214
          'entry' => liquidify(entry),
215 216 217 218 219 220
          'reference' => reference_tag(entry),
          'key' => entry.key,
          'type' => entry.type,
          'link' => repository_link_for(entry),
          'index' => index
        })
221 222
      end

Sylvester Keil's avatar
Sylvester Keil committed
223 224 225 226 227 228
      def liquidify(entry)
        e = {}

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

229 230 231 232 233 234 235
        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
236 237 238 239 240 241 242 243 244

        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

245 246 247
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
248

249 250
      def details_file_for(entry)
        name = entry.key.to_s.dup
251

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

254 255
        [name, 'html'].join('.')
      end
256

257 258 259 260 261 262 263
      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
264
      def details_link_for(entry, base = base_url)
265
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
266
      end
267

Sylvester Keil's avatar
Sylvester Keil committed
268
      def base_url
269
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
270
      end
271

272 273 274
      def details_path
        config['details_dir']
      end
275

Sylvester Keil's avatar
Sylvester Keil committed
276 277 278 279 280
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end

281 282 283 284 285 286
      def render_citation(items)
        renderer.render items.zip(locators).map { |entry, locator|
          item = citation_item_for entry
          item.locator = locator
          item
        }, STYLES[style].citation
Sylvester Keil's avatar
Sylvester Keil committed
287 288 289 290 291 292 293 294 295 296 297 298
      end

      def render_bibliography(entry)
        renderer.render citation_item_for(entry), STYLES[style].bibliography
      end

      def citation_item_for(entry)
        CiteProc::CitationItem.new id: entry.id do |c|
          c.data = CiteProc::Item.new entry.to_citeproc
        end
      end

299
      def cited_keys
300
        context['cited'] ||= []
301
      end
302

303 304 305
      def cite(keys)
        items = keys.map do |key|
          cited_keys << key
306

307 308 309 310 311 312
          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
313
        end
314 315

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

318
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
319
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
320
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
321
        else
322
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
323 324
        end
      end
325

Sylvester Keil's avatar
Sylvester Keil committed
326 327 328 329 330 331
      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
332

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

Sylvester Keil's avatar
Sylvester Keil committed
335 336 337 338 339 340
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
341

Sylvester Keil's avatar
Sylvester Keil committed
342 343 344
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
345

346 347 348 349
      def cited_references
        context && context['cited'] || []
      end

Sylvester Keil's avatar
Sylvester Keil committed
350
      def set_context_to(context)
351
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
352 353
        config.merge!(site.config['scholar'] || {})
      end
354
    end
355

356
  end
Hiren Patel's avatar
Hiren Patel committed
357
end