~hacktivista/tilt-emacs_org

ref: f7e30ff4143eb19434fe06a29af4cc97ef54d46d tilt-emacs_org/lib/tilt/emacs_org.rb -rw-r--r-- 1.4 KiB
f7e30ff4Felix Freeman Initial commit. Working Tilt::EmacsOrg 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true

require 'nokogiri'
require 'open3'
require 'tempfile'
require 'tilt'

# Tilt.
module Tilt
  # Native Emacs Org templating engine for Tilt.
  class EmacsOrgTemplate < Template
    metadata[:mime_type] = 'text/html'

    def head
      @head ||= doc.at_css('head').css('script, link, style').inject do
        |elm, head| "#{head}#{elm}\n"
      end
    end

    def body
      @body ||= doc.at_css('body').inner_html
    end

    def title
      @title ||= doc.at_css('title').content
    end

    protected

    def prepare; end

    def evaluate(_scope, _locals, &_block)
      case @options[:format]
      when :full
        emacs_org_export
      when :body_with_resources
        head + body
      else # :body_only
        body
      end
    end

    def doc
      @doc ||= Nokogiri::HTML(emacs_org_export)
    end

    def emacs_org_export
      @emacs_org_export ||= Tempfile.create(['', '.org']) do |f|
        f.write("#+SETUPFILE: #{@options[:setupfile]}\n") \
          if options.include?(:setupfile)
        f.write(@data)
        f.rewind
        Open3.capture3(
          <<~SH
            emacs --batch --quick --load org --eval='
              (progn
                (find-file-literally "#{f.path}")
                (org-html-export-as-html)
                (message "%s" (buffer-string)))'
          SH
        )[1]
      end
    end
  end

  register(EmacsOrgTemplate, 'org')
end