aboutsummaryrefslogtreecommitdiff
path: root/wikilinks.rb
blob: 92e26fe7e34978eec797eb3d95cda432ef09ee26 (plain)
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
68
69
70
71
72
73
74
module Jekyll
  module Wikilinks
    class Wikilink
      def self.parse(text)
        inner = text[2..-3]
        name, title = inner.split('|', 2)
        self.new(name, title)
      end
      
      attr_accessor :name, :title
      attr_reader :match
      
      def initialize(name, title)
        @name = name.strip
        @title = title
      end
      
      def title
        if @title.nil?
          if not @match.nil?
            match_title @match
          else
            @name
          end  
        else
          @title
        end
      end

      def match_title(m)
	if not m.data.nil? and m.data.include? 'title'
	  m.data['title']
	end
      end
      
      def url
        @match.url
      end
      
      def has_match?
        not @match.nil?
      end
      
      def match_post(posts)
        @match = posts.find { |p| p.slug.downcase == @name.downcase or match_title(p) == name }
      end
      
      def match_page(pages)
        @match = pages.find { |p| p.basename.downcase == @name.downcase or match_title(p) == name }
      end
      
      def markdown
        @match.nil? ? "\\[\\[#{title}\\]\\]" : "[#{title}](#{url})"
      end
    end
  end
  
  module Convertible
    alias old_transform transform

    def transform
      if converter.instance_of? Jekyll::Converters::Markdown
        pat = /\[\[(.+?)\]\]/
        @content = @content.gsub(pat) do |m|
          wl = Wikilinks::Wikilink.parse(m)
          wl.match_page(site.pages)
          wl.match_post(site.posts) unless wl.has_match?
          wl.markdown
        end
      end
      old_transform
    end
  end
end