utilities.rb 8.01 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, :key, :text

      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|
29 30
            @bibtex_files ||= []
            @bibtex_files << file
31 32 33 34 35 36 37 38 39 40 41 42 43
          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
44 45 46

          opts.on('-s', '--style STYLE') do |style|
            @style = style
47
          end
48 49 50 51

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

54
        argv = arguments.split(/(\B-[cfqptTs]|\B--(?:cited|file|query|prefix|text|style|template|))/)
55 56 57

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

59 60 61 62 63 64 65 66 67
      def bibtex_files
        @bibtex_files ||= [config['bibliography']]
      end

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

68
      def bibtex_options
69 70 71 72 73
        config['bibtex_options'] ||= {}
      end

      def bibtex_filters
        config['bibtex_filters'] ||= []
74
      end
75

76 77 78 79 80 81 82
      def bibtex_paths
        @bibtex_paths ||= bibtex_files.map { |file|
          extend_path file
        }
      end

      # :nodoc: backwards compatibility
83
      def bibtex_path
84
        bibtex_paths[0]
85
      end
86

87
      def bibliography
88
        unless @bibliography
89 90 91 92
          @bibliography = BibTeX.parse(
            bibtex_paths.reduce('') { |s, p| s << IO.read(p) },
            bibtex_options
          )
93 94 95 96
          @bibliography.replace_strings if replace_strings?
        end

        @bibliography
97 98
      end

99
      def entries
100
        b = bibliography[query || config['query']]
101 102

        unless config['sort_by'] == 'none'
103
          b = b.sort_by { |e| e[config['sort_by']].to_s }
104 105
          b.reverse! if config['order'] =~ /^(desc|reverse)/i
        end
106

107 108
        b
      end
109

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
      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

130 131 132 133
      def replace_strings?
        config['replace_strings']
      end

134 135 136 137
      def cited_only?
        !!@cited
      end

138 139
      def extend_path(name)
        if name.nil? || name.empty?
140
          name = config['bibliography']
141
        end
142

143 144
        # return as is if it is an absolute path
        return name if name.start_with?('/') && File.exists?(name)
145

146 147 148
        p = File.join(config['source'], name)
        p << '.bib' unless File.exists?(p)
        p
149
      end
150

151
      def reference_tag(entry)
Sylvester Keil's avatar
Sylvester Keil committed
152
        return missing_reference unless entry
153

154
        entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?
Sylvester Keil's avatar
Sylvester Keil committed
155
        reference = render_bibliography entry
156

Sylvester Keil's avatar
Sylvester Keil committed
157 158 159 160
        content_tag reference_tagname, reference,
          :id => [prefix, entry.key].compact.join('-')
      end

161 162 163 164
      def style
        @style || config['style']
      end

Sylvester Keil's avatar
Sylvester Keil committed
165 166 167 168 169 170 171 172 173
      def missing_reference
        config['missing_reference']
      end

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

      def bibliography_template
174 175 176 177 178
        @bibliography_template || config['bibliography_template']
      end

      def liquid_template
        return @liquid_template if @liquid_template
179

180
        tmp = bibliography_template
181 182

        case
183
        when tmp.nil?, tmp.empty?
184 185 186 187 188
          tmp = '{{reference}}'
        when site.layouts.key?(tmp)
          tmp = site.layouts[tmp].content
        end

189
        @liquid_template = Liquid::Template.parse(tmp)
Sylvester Keil's avatar
Sylvester Keil committed
190 191
      end

192
      def bibliography_tag(entry, index)
Sylvester Keil's avatar
Sylvester Keil committed
193 194
        return missing_reference unless entry

195
        liquid_template.render({
Sylvester Keil's avatar
Sylvester Keil committed
196
          'entry' => liquidify(entry),
197 198 199 200 201 202
          'reference' => reference_tag(entry),
          'key' => entry.key,
          'type' => entry.type,
          'link' => repository_link_for(entry),
          'index' => index
        })
203 204
      end

Sylvester Keil's avatar
Sylvester Keil committed
205 206 207 208 209 210
      def liquidify(entry)
        e = {}

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

Sylvester Keil's avatar
Sylvester Keil committed
211 212 213 214 215 216 217
        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
218 219 220 221 222 223 224 225 226

        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

227 228 229
      def generate_details?
        site.layouts.key?(File.basename(config['details_layout'], '.html'))
      end
230

231 232
      def details_file_for(entry)
        name = entry.key.to_s.dup
233

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

236 237
        [name, 'html'].join('.')
      end
238

239 240 241 242 243 244 245
      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
246
      def details_link_for(entry, base = base_url)
247
        File.join(base, details_path, details_file_for(entry))
Sylvester Keil's avatar
Sylvester Keil committed
248
      end
249

Sylvester Keil's avatar
Sylvester Keil committed
250
      def base_url
251
        @base_url ||= site.config['baseurl'] || site.config['base_url'] || ''
252
      end
253

254 255 256
      def details_path
        config['details_dir']
      end
257

Sylvester Keil's avatar
Sylvester Keil committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      def renderer
        @renderer ||= CiteProc::Ruby::Renderer.new :format => 'html',
          :style => style, :locale => config['locale']
      end

      def render_citation(entry)
        renderer.render [citation_item_for(entry)], STYLES[style].citation
      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

Sylvester Keil's avatar
Sylvester Keil committed
277
      def cite(key)
278 279 280
        context['cited'] ||= []
        context['cited'] << key

Sylvester Keil's avatar
Sylvester Keil committed
281
        if bibliography.key?(key)
282 283 284
          entry = bibliography[key]
          entry = entry.convert(*bibtex_filters) unless bibtex_filters.empty?

Sylvester Keil's avatar
Sylvester Keil committed
285
          link_to "##{[prefix, entry.key].compact.join('-')}", render_citation(entry)
Sylvester Keil's avatar
Sylvester Keil committed
286
        else
287
          missing_reference
Sylvester Keil's avatar
Sylvester Keil committed
288 289
        end
      end
Sylvester Keil's avatar
Sylvester Keil committed
290

291
      def cite_details(key, text)
Hiren Patel's avatar
Hiren Patel committed
292
        if bibliography.key?(key)
Sylvester Keil's avatar
Sylvester Keil committed
293
          link_to details_link_for(bibliography[key]), text || config['details_link']
Hiren Patel's avatar
Hiren Patel committed
294
        else
295
          missing_reference
Hiren Patel's avatar
Hiren Patel committed
296 297
        end
      end
298

Sylvester Keil's avatar
Sylvester Keil committed
299 300 301 302 303 304
      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
305

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

Sylvester Keil's avatar
Sylvester Keil committed
308 309 310 311 312 313
        if content.nil?
          "<#{[name, attributes].flatten.compact.join(' ')}/>"
        else
          "<#{[name, attributes].flatten.compact.join(' ')}>#{content}</#{name}>"
        end
      end
314

Sylvester Keil's avatar
Sylvester Keil committed
315 316 317
      def link_to(href, content, attributes = {})
        content_tag :a, content || href, attributes.merge(:href => href)
      end
318

319 320 321 322
      def cited_references
        context && context['cited'] || []
      end

Sylvester Keil's avatar
Sylvester Keil committed
323
      def set_context_to(context)
324
        @context, @site, = context, context.registers[:site]
Sylvester Keil's avatar
Sylvester Keil committed
325 326
        config.merge!(site.config['scholar'] || {})
      end
327
    end
328

329
  end
Hiren Patel's avatar
Hiren Patel committed
330
end