repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
gxbsst/pbl_service_client
lib/pbl/base/response/extra_response.rb
module Pbl module Base module ExtraResponse include Virtus.module attribute :code, Integer attribute :headers, String attribute :body, String def success? if /^2[0-9][0-9]$/.match(self.code.to_s) true else false end end def data self.fetch(:data) end def meta self.fetch(:meta) end # def id # self.fetch(:id) # end end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/lists_test.rb
require 'test_helper' context "Bulleted lists (:ulist)" do context "Simple lists" do test "dash elements with no blank lines" do input = <<-EOS List ==== - Foo - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 end test "dash elements separated by blank lines should merge lists" do input = <<-EOS List ==== - Foo - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 end test 'dash elements with interspersed line comments should be skipped and not break list' do input = <<-EOS == List - Foo // line comment // another line comment - Boo // line comment more text // another line comment - Blech EOS output = render_embedded_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 assert_xpath %((//ul/li)[2]/p[text()="Boo\nmore text"]), output, 1 end test "dash elements separated by a line comment offset by blank lines should not merge lists" do input = <<-EOS List ==== - Foo - Boo // - Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[2]/li', output, 1 end test "dash elements separated by a block title offset by a blank line should not merge lists" do input = <<-EOS List ==== - Foo - Boo .Also - Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[2]/li', output, 1 assert_xpath '(//ul)[2]/preceding-sibling::*[@class = "title"][text() = "Also"]', output, 1 end test "dash elements separated by an attribute entry offset by a blank line should not merge lists" do input = <<-EOS == List - Foo - Boo :foo: bar - Blech EOS output = render_embedded_string input assert_xpath '//ul', output, 2 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[2]/li', output, 1 end test 'a non-indented wrapped line is folded into text of list item' do input = <<-EOS List ==== - Foo wrapped content - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li[1]/*', output, 1 assert_xpath "//ul/li[1]/p[text() = 'Foo\nwrapped content']", output, 1 end test 'a non-indented wrapped line that resembles a block title is folded into text of list item' do input = <<-EOS == List - Foo .wrapped content - Boo - Blech EOS output = render_embedded_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li[1]/*', output, 1 assert_xpath "//ul/li[1]/p[text() = 'Foo\n.wrapped content']", output, 1 end test 'a non-indented wrapped line that resembles an attribute entry is folded into text of list item' do input = <<-EOS == List - Foo :foo: bar - Boo - Blech EOS output = render_embedded_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li[1]/*', output, 1 assert_xpath "//ul/li[1]/p[text() = 'Foo\n:foo: bar']", output, 1 end test 'an indented wrapped line is unindented and folded into text of list item' do input = <<-EOS List ==== - Foo wrapped content - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li[1]/*', output, 1 assert_xpath "//ul/li[1]/p[text() = 'Foo\nwrapped content']", output, 1 end test 'wrapped list item with hanging indent followed by non-indented line' do input = <<-EOS == Lists - list item 1 // not line comment second wrapped line - list item 2 EOS output = render_embedded_string input assert_css 'ul', output, 1 assert_css 'ul li', output, 2 # NOTE for some reason, we're getting an extra line after the indented line lines = xmlnodes_at_xpath('(//ul/li)[1]/p', output, 1).text.gsub(/\n[[:space:]]*\n/, "\n").lines.entries assert_equal 3, lines.size assert_equal 'list item 1', lines[0].chomp assert_equal ' // not line comment', lines[1].chomp assert_equal 'second wrapped line', lines[2].chomp end test "a literal paragraph offset by blank lines in list content is appended as a literal block" do input = <<-EOS List ==== - Foo literal - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul/li)[1]/p[text() = "Foo"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]', output, 1 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '((//ul/li)[1]/*[@class="literalblock"])[1]//pre[text() = "literal"]', output, 1 end test "a literal paragraph offset by a blank line in list content followed by line with continuation is appended as two blocks" do input = <<-EOS List ==== - Foo literal + para - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul/li)[1]/p[text() = "Foo"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]', output, 1 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '((//ul/li)[1]/*[@class="literalblock"])[1]//pre[text() = "literal"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'appends line as paragraph if attached by continuation following line comment' do input = <<-EOS - list item 1 // line comment + paragraph in list item 1 - list item 2 EOS output = render_embedded_string input assert_css 'ul', output, 1 assert_css 'ul li', output, 2 assert_xpath '(//ul/li)[1]/p[text()="list item 1"]', output, 1 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="paragraph"]/p[text()="paragraph in list item 1"]', output, 1 assert_xpath '(//ul/li)[2]/p[text()="list item 2"]', output, 1 end test "a literal paragraph with a line that appears as a list item that is followed by a continuation should create two blocks" do input = <<-EOS * Foo + literal . still literal + para * Bar EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '(//ul/li)[1]/p[text() = "Foo"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]', output, 1 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath %(((//ul/li)[1]/*[@class="literalblock"])[1]//pre[text() = " literal\n. still literal"]), output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 end test "consecutive literal paragraph offset by blank lines in list content are appended as a literal blocks" do input = <<-EOS List ==== - Foo literal more literal - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul/li)[1]/p[text() = "Foo"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]', output, 2 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="literalblock"]', output, 2 assert_xpath '((//ul/li)[1]/*[@class="literalblock"])[1]//pre[text() = "literal"]', output, 1 assert_xpath "((//ul/li)[1]/*[@class='literalblock'])[2]//pre[text() = 'more\nliteral']", output, 1 end test "a literal paragraph without a trailing blank line consumes following list items" do input = <<-EOS List ==== - Foo literal - Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 1 assert_xpath '(//ul/li)[1]/p[text() = "Foo"]', output, 1 assert_xpath '(//ul/li)[1]/*[@class="literalblock"]', output, 1 assert_xpath '(//ul/li)[1]/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath "((//ul/li)[1]/*[@class='literalblock'])[1]//pre[text() = ' literal\n- Boo\n- Blech']", output, 1 end test "asterisk elements with no blank lines" do input = <<-EOS List ==== * Foo * Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 end test "asterisk elements separated by blank lines should merge lists" do input = <<-EOS List ==== * Foo * Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 end test 'asterisk elements with interspersed line comments should be skipped and not break list' do input = <<-EOS == List * Foo // line comment // another line comment * Boo // line comment more text // another line comment * Blech EOS output = render_embedded_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 assert_xpath %((//ul/li)[2]/p[text()="Boo\nmore text"]), output, 1 end test "asterisk elements separated by a line comment offset by blank lines should not merge lists" do input = <<-EOS List ==== * Foo * Boo // * Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[2]/li', output, 1 end test "asterisk elements separated by a block title offset by a blank line should not merge lists" do input = <<-EOS List ==== * Foo * Boo .Also * Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[2]/li', output, 1 assert_xpath '(//ul)[2]/preceding-sibling::*[@class = "title"][text() = "Also"]', output, 1 end test "asterisk elements separated by an attribute entry offset by a blank line should not merge lists" do input = <<-EOS == List * Foo * Boo :foo: bar * Blech EOS output = render_embedded_string input assert_xpath '//ul', output, 2 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[2]/li', output, 1 end test "list should terminate before next lower section heading" do input = <<-EOS List ==== * first item * second item == Section EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//h2[text() = "Section"]', output, 1 end test "list should terminate before next lower section heading with implicit id" do input = <<-EOS List ==== * first item * second item [[sec]] == Section EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//h2[@id = "sec"][text() = "Section"]', output, 1 end end context "Lists with inline markup" do test "quoted text" do input = <<-EOS List ==== - I am *strong*. - I am 'stressed'. - I am `flexible`. EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul/li)[1]//strong', output, 1 assert_xpath '(//ul/li)[2]//em', output, 1 assert_xpath '(//ul/li)[3]//tt', output, 1 end test "attribute substitutions" do input = <<-EOS List ==== :foo: bar - side a {brvbar} side b - Take me to a {foo}. EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '(//ul/li)[1]//p[text() = "side a | side b"]', output, 1 assert_xpath '(//ul/li)[2]//p[text() = "Take me to a bar."]', output, 1 end test "leading dot is treated as text not block title" do input = <<-EOS * .first * .second * .third EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 3 %w(.first .second .third).each_with_index do |text, index| assert_xpath "(//ul/li)[#{index + 1}]//p[text() = '#{text}']", output, 1 end end test "word ending sentence on continuing line not treated as a list item" do input = <<-EOS A. This is the story about AsciiDoc. It begins here. B. And it ends here. EOS output = render_string input assert_xpath '//ol', output, 1 assert_xpath '//ol/li', output, 2 end end context "Nested lists" do test "asterisk element mixed with dash elements should be nested" do input = <<-EOS List ==== - Foo * Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[1]/li//ul/li', output, 1 end test "dash element mixed with asterisks elements should be nested" do input = <<-EOS List ==== * Foo - Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[1]/li//ul/li', output, 1 end test "lines prefixed with alternating list markers separated by blank lines should be nested" do input = <<-EOS List ==== - Foo * Boo - Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[1]/li//ul/li', output, 1 end test "nested elements (2) with asterisks" do input = <<-EOS List ==== * Foo ** Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 2 assert_xpath '//ul/li', output, 3 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '(//ul)[1]/li//ul/li', output, 1 end test "nested elements (3) with asterisks" do input = <<-EOS List ==== * Foo ** Boo *** Snoo * Blech EOS output = render_string input assert_xpath '//ul', output, 3 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li//ul)[1]/li', output, 1 assert_xpath '(((//ul)[1]/li//ul)[1]/li//ul)[1]/li', output, 1 end test "nested elements (4) with asterisks" do input = <<-EOS List ==== * Foo ** Boo *** Snoo **** Froo * Blech EOS output = render_string input assert_xpath '//ul', output, 4 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li//ul)[1]/li', output, 1 assert_xpath '(((//ul)[1]/li//ul)[1]/li//ul)[1]/li', output, 1 assert_xpath '((((//ul)[1]/li//ul)[1]/li//ul)[1]/li//ul)[1]/li', output, 1 end test "nested elements (5) with asterisks" do input = <<-EOS List ==== * Foo ** Boo *** Snoo **** Froo ***** Groo * Blech EOS output = render_string input assert_xpath '//ul', output, 5 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li//ul)[1]/li', output, 1 assert_xpath '(((//ul)[1]/li//ul)[1]/li//ul)[1]/li', output, 1 assert_xpath '((((//ul)[1]/li//ul)[1]/li//ul)[1]/li//ul)[1]/li', output, 1 assert_xpath '(((((//ul)[1]/li//ul)[1]/li//ul)[1]/li//ul)[1]/li//ul)[1]/li', output, 1 end test "nested ordered elements (2)" do input = <<-EOS List ==== . Foo .. Boo . Blech EOS output = render_string input assert_xpath '//ol', output, 2 assert_xpath '//ol/li', output, 3 assert_xpath '(//ol)[1]/li', output, 2 assert_xpath '(//ol)[1]/li//ol/li', output, 1 end test "nested ordered elements (3)" do input = <<-EOS List ==== . Foo .. Boo ... Snoo . Blech EOS output = render_string input assert_xpath '//ol', output, 3 assert_xpath '(//ol)[1]/li', output, 2 assert_xpath '((//ol)[1]/li//ol)[1]/li', output, 1 assert_xpath '(((//ol)[1]/li//ol)[1]/li//ol)[1]/li', output, 1 end test "nested unordered inside ordered elements" do input = <<-EOS List ==== . Foo * Boo . Blech EOS output = render_string input assert_xpath '//ol', output, 1 assert_xpath '//ul', output, 1 assert_xpath '(//ol)[1]/li', output, 2 assert_xpath '((//ol)[1]/li//ul)[1]/li', output, 1 end test "nested ordered inside unordered elements" do input = <<-EOS List ==== * Foo . Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ol', output, 1 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li//ol)[1]/li', output, 1 end test 'three levels of alternating unordered and ordered elements' do input = <<-EOS == Lists * bullet 1 . numbered 1.1 ** bullet 1.1.1 * bullet 2 EOS output = render_embedded_string input assert_css '.ulist', output, 2 assert_css '.olist', output, 1 assert_css '.ulist > ul > li > p', output, 3 assert_css '.ulist > ul > li > p + .olist', output, 1 assert_css '.ulist > ul > li > p + .olist > ol > li > p', output, 1 assert_css '.ulist > ul > li > p + .olist > ol > li > p + .ulist', output, 1 assert_css '.ulist > ul > li > p + .olist > ol > li > p + .ulist > ul > li > p', output, 1 assert_css '.ulist > ul > li + li > p', output, 1 end test "lines with alternating markers of unordered and ordered list types separated by blank lines should be nested" do input = <<-EOS List ==== * Foo . Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ol', output, 1 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li//ol)[1]/li', output, 1 end test 'list item with literal content should not consume nested list of different type' do input = <<-EOS List ==== - bullet literal but not hungry . numbered EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//li', output, 2 assert_xpath '//ul//ol', output, 1 assert_xpath '//ul/li/p', output, 1 assert_xpath '//ul/li/p[text()="bullet"]', output, 1 assert_xpath '//ul/li/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath %(//ul/li/p/following-sibling::*[@class="literalblock"]//pre[text()="literal\nbut not\nhungry"]), output, 1 assert_xpath '//*[@class="literalblock"]/following-sibling::*[@class="olist arabic"]', output, 1 assert_xpath '//*[@class="literalblock"]/following-sibling::*[@class="olist arabic"]//p[text()="numbered"]', output, 1 end test 'nested list item does not eat the title of the following detached block' do input = <<-EOS List ==== - bullet * nested bullet 1 * nested bullet 2 .Title .... literal .... EOS output = render_embedded_string input assert_xpath '//*[@class="ulist"]/ul', output, 2 assert_xpath '(//*[@class="ulist"])[1]/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '(//*[@class="ulist"])[1]/following-sibling::*[@class="literalblock"]/*[@class="title"]', output, 1 end test "lines with alternating markers of bulleted and labeled list types separated by blank lines should be nested" do input = <<-EOS List ==== * Foo term1:: def1 * Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//dl', output, 1 assert_xpath '//ul[1]/li', output, 2 assert_xpath '//ul[1]/li//dl[1]/dt', output, 1 assert_xpath '//ul[1]/li//dl[1]/dd', output, 1 end test "nested ordered with attribute inside unordered elements" do input = <<-EOS Blah ==== * Foo [start=2] . Boo * Blech EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ol', output, 1 assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li//ol)[1][@start = 2]/li', output, 1 end end context "List continuations" do test "adjacent list continuation line attaches following paragraph" do input = <<-EOS Lists ===== * Item one, paragraph one + Item one, paragraph two + * Item two EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/p', output, 1 assert_xpath '//ul/li[1]//p', output, 2 assert_xpath '//ul/li[1]/p[text() = "Item one, paragraph one"]', output, 1 assert_xpath '//ul/li[1]/*[@class = "paragraph"]/p[text() = "Item one, paragraph two"]', output, 1 end test "adjacent list continuation line attaches following block" do input = <<-EOS Lists ===== * Item one, paragraph one + .... Item one, literal block .... + * Item two EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/p', output, 1 assert_xpath '(//ul/li[1]/p/following-sibling::*)[1][@class = "literalblock"]', output, 1 end test "adjacent list continuation line attaches following block with block attributes" do input = <<-EOS Lists ===== * Item one, paragraph one + :foo: bar [[beck]] .Read the following aloud to yourself [source, ruby] ---- 5.times { print "Odelay!" } ---- * Item two EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/p', output, 1 assert_xpath '(//ul/li[1]/p/following-sibling::*)[1][@id="beck"][@class = "listingblock"]', output, 1 assert_xpath '(//ul/li[1]/p/following-sibling::*)[1][@id="beck"]/div[@class="title"][starts-with(text(),"Read")]', output, 1 assert_xpath '(//ul/li[1]/p/following-sibling::*)[1][@id="beck"]//code[@class="ruby"][starts-with(text(),"5.times")]', output, 1 end test 'trailing block attribute line attached by continuation should not create block' do input = <<-EOS Lists ===== * Item one, paragraph one + [source] * Item two EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/*', output, 1 assert_xpath '//ul/li//*[@class="listingblock"]', output, 0 end test 'trailing block title line attached by continuation should not create block' do input = <<-EOS Lists ===== * Item one, paragraph one + .Disappears into the ether * Item two EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/*', output, 1 end test "consecutive blocks in list continuation attach to list item" do input = <<-EOS Lists ===== * Item one, paragraph one + .... Item one, literal block .... + ____ Item one, quote block ____ + * Item two EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/p', output, 1 assert_xpath '(//ul/li[1]/p/following-sibling::*)[1][@class = "literalblock"]', output, 1 assert_xpath '(//ul/li[1]/p/following-sibling::*)[2][@class = "quoteblock"]', output, 1 end test 'list item with hanging indent followed by block attached by list continuation' do input = <<-EOS == Lists . list item 1 continued + -- open block in list item 1 -- . list item 2 EOS output = render_embedded_string input assert_css 'ol', output, 1 assert_css 'ol li', output, 2 assert_xpath %((//ol/li)[1]/p[text()="list item 1\ncontinued"]), output, 1 assert_xpath '(//ol/li)[1]/p/following-sibling::*[@class="openblock"]', output, 1 assert_xpath '(//ol/li)[1]/p/following-sibling::*[@class="openblock"]//p[text()="open block in list item 1"]', output, 1 assert_xpath %((//ol/li)[2]/p[text()="list item 2"]), output, 1 end test 'list item paragraph in list item and nested list item' do input = <<-EOS == Lists . list item 1 + list item 1 paragraph * nested list item + nested list item paragraph . list item 2 EOS output = render_embedded_string input assert_css '.olist ol', output, 1 assert_css '.olist ol > li', output, 2 assert_css '.ulist ul', output, 1 assert_css '.ulist ul > li', output, 1 assert_xpath '(//ol/li)[1]/*', output, 3 assert_xpath '((//ol/li)[1]/*)[1]/self::p', output, 1 assert_xpath '((//ol/li)[1]/*)[1]/self::p[text()="list item 1"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="paragraph"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="ulist"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="ulist"]/ul/li', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="ulist"]/ul/li/p[text()="nested list item"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="ulist"]/ul/li/p/following-sibling::div[@class="paragraph"]', output, 1 end test 'trailing list continuations should attach to list items at respective levels' do input = <<-EOS == Lists . list item 1 + * nested list item 1 * nested list item 2 + paragraph for nested list item 2 + paragraph for list item 1 . list item 2 EOS output = render_embedded_string input assert_css '.olist ol', output, 1 assert_css '.olist ol > li', output, 2 assert_css '.ulist ul', output, 1 assert_css '.ulist ul > li', output, 2 assert_css '.olist .ulist', output, 1 assert_xpath '(//ol/li)[1]/*', output, 3 assert_xpath '((//ol/li)[1]/*)[1]/self::p', output, 1 assert_xpath '((//ol/li)[1]/*)[1]/self::p[text()="list item 1"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/div[@class="paragraph"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="paragraph"]', output, 1 end test 'trailing list continuations should attach to list items of different types at respective levels' do input = <<-EOS == Lists * bullet 1 . numbered 1.1 ** bullet 1.1.1 + numbered 1.1 paragraph + bullet 1 paragraph * bullet 2 EOS output = render_embedded_string input assert_xpath '(//ul)[1]/li', output, 2 assert_xpath '((//ul)[1]/li[1])/*', output, 3 assert_xpath '(((//ul)[1]/li[1])/*)[1]/self::p[text()="bullet 1"]', output, 1 assert_xpath '(((//ul)[1]/li[1])/*)[2]/ol', output, 1 assert_xpath '(((//ul)[1]/li[1])/*)[3]/self::div[@class="paragraph"]/p[text()="bullet 1 paragraph"]', output, 1 assert_xpath '((//ul)[1]/li)[1]/div/ol/li', output, 1 assert_xpath '((//ul)[1]/li)[1]/div/ol/li/*', output, 3 assert_xpath '(((//ul)[1]/li)[1]/div/ol/li/*)[1]/self::p[text()="numbered 1.1"]', output, 1 assert_xpath '(((//ul)[1]/li)[1]/div/ol/li/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '(((//ul)[1]/li)[1]/div/ol/li/*)[3]/self::div[@class="paragraph"]/p[text()="numbered 1.1 paragraph"]', output, 1 assert_xpath '((//ul)[1]/li)[1]/div/ol/li/div[@class="ulist"]/ul/li', output, 1 assert_xpath '((//ul)[1]/li)[1]/div/ol/li/div[@class="ulist"]/ul/li/*', output, 1 assert_xpath '((//ul)[1]/li)[1]/div/ol/li/div[@class="ulist"]/ul/li/p[text()="bullet 1.1.1"]', output, 1 end test 'repeated list continuations should attach to list items at respective levels' do input = <<-EOS == Lists . list item 1 * nested list item 1 + -- open block for nested list item 1 -- + * nested list item 2 + paragraph for nested list item 2 + paragraph for list item 1 . list item 2 EOS output = render_embedded_string input assert_css '.olist ol', output, 1 assert_css '.olist ol > li', output, 2 assert_css '.ulist ul', output, 1 assert_css '.ulist ul > li', output, 2 assert_css '.olist .ulist', output, 1 assert_xpath '(//ol/li)[1]/*', output, 3 assert_xpath '((//ol/li)[1]/*)[1]/self::p', output, 1 assert_xpath '((//ol/li)[1]/*)[1]/self::p[text()="list item 1"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/div[@class="openblock"]', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/div[@class="paragraph"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="paragraph"]', output, 1 end test 'repeated list continuations attached directly to list item should attach to list items at respective levels' do input = <<-EOS == Lists . list item 1 + * nested list item 1 + -- open block for nested list item 1 -- + * nested list item 2 + paragraph for nested list item 2 + paragraph for list item 1 . list item 2 EOS output = render_embedded_string input assert_css '.olist ol', output, 1 assert_css '.olist ol > li', output, 2 assert_css '.ulist ul', output, 1 assert_css '.ulist ul > li', output, 2 assert_css '.olist .ulist', output, 1 assert_xpath '(//ol/li)[1]/*', output, 3 assert_xpath '((//ol/li)[1]/*)[1]/self::p', output, 1 assert_xpath '((//ol/li)[1]/*)[1]/self::p[text()="list item 1"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/div[@class="openblock"]', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/div[@class="paragraph"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="paragraph"]', output, 1 end test 'repeated list continuations should attach to list items at respective levels ignoring blank lines' do input = <<-EOS == Lists . list item 1 + * nested list item 1 + -- open block for nested list item 1 -- + * nested list item 2 + paragraph for nested list item 2 + paragraph for list item 1 . list item 2 EOS output = render_embedded_string input assert_css '.olist ol', output, 1 assert_css '.olist ol > li', output, 2 assert_css '.ulist ul', output, 1 assert_css '.ulist ul > li', output, 2 assert_css '.olist .ulist', output, 1 assert_xpath '(//ol/li)[1]/*', output, 3 assert_xpath '((//ol/li)[1]/*)[1]/self::p', output, 1 assert_xpath '((//ol/li)[1]/*)[1]/self::p[text()="list item 1"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[1]/div[@class="openblock"]', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/*', output, 2 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/p', output, 1 assert_xpath '(((//ol/li)[1]/*)[2]/self::div[@class="ulist"]/ul/li)[2]/div[@class="paragraph"]', output, 1 assert_xpath '((//ol/li)[1]/*)[3]/self::div[@class="paragraph"]', output, 1 end test 'trailing list continuations should ignore preceding blank lines' do input = <<-EOS == Lists * bullet 1 ** bullet 1.1 *** bullet 1.1.1 + -- open block -- + bullet 1.1 paragraph + bullet 1 paragraph * bullet 2 EOS output = render_embedded_string input assert_xpath '((//ul)[1]/li[1])/*', output, 3 assert_xpath '(((//ul)[1]/li[1])/*)[1]/self::p[text()="bullet 1"]', output, 1 assert_xpath '(((//ul)[1]/li[1])/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '(((//ul)[1]/li[1])/*)[3]/self::div[@class="paragraph"]/p[text()="bullet 1 paragraph"]', output, 1 assert_xpath '((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li', output, 1 assert_xpath '((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/*', output, 3 assert_xpath '(((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/*)[1]/self::p[text()="bullet 1.1"]', output, 1 assert_xpath '(((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/*)[2]/self::div[@class="ulist"]', output, 1 assert_xpath '(((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/*)[3]/self::div[@class="paragraph"]/p[text()="bullet 1.1 paragraph"]', output, 1 assert_xpath '((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/div[@class="ulist"]/ul/li', output, 1 assert_xpath '((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/div[@class="ulist"]/ul/li/*', output, 2 assert_xpath '(((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/div[@class="ulist"]/ul/li/*)[1]/self::p', output, 1 assert_xpath '(((//ul)[1]/li)[1]/div[@class="ulist"]/ul/li/div[@class="ulist"]/ul/li/*)[2]/self::div[@class="openblock"]', output, 1 end # NOTE this is not consistent w/ AsciiDoc output, but this is some screwy input anyway =begin test "consecutive list continuation lines are folded" do input = <<-EOS Lists ===== * Item one, paragraph one + + Item one, paragraph two + + * Item two + + EOS output = render_string input assert_xpath '//ul', output, 1 assert_xpath '//ul/li', output, 2 assert_xpath '//ul/li[1]/p', output, 1 assert_xpath '//ul/li[1]//p', output, 2 assert_xpath '//ul/li[1]//p[text() = "Item one, paragraph one"]', output, 1 assert_xpath '//ul/li[1]//p[text() = "Item one, paragraph two"]', output, 1 end =end end end context "Ordered lists (:olist)" do context "Simple lists" do test "dot elements with no blank lines" do input = <<-EOS List ==== . Foo . Boo . Blech EOS output = render_string input assert_xpath '//ol', output, 1 assert_xpath '//ol/li', output, 3 end test "dot elements separated by blank lines should merge lists" do input = <<-EOS List ==== . Foo . Boo . Blech EOS output = render_string input assert_xpath '//ol', output, 1 assert_xpath '//ol/li', output, 3 end test 'dot elements with interspersed line comments should be skipped and not break list' do input = <<-EOS == List . Foo // line comment // another line comment . Boo // line comment more text // another line comment . Blech EOS output = render_embedded_string input assert_xpath '//ol', output, 1 assert_xpath '//ol/li', output, 3 assert_xpath %((//ol/li)[2]/p[text()="Boo\nmore text"]), output, 1 end test "dot elements separated by line comment offset by blank lines should not merge lists" do input = <<-EOS List ==== . Foo . Boo // . Blech EOS output = render_string input assert_xpath '//ol', output, 2 assert_xpath '(//ol)[1]/li', output, 2 assert_xpath '(//ol)[2]/li', output, 1 end test "dot elements separated by a block title offset by a blank line should not merge lists" do input = <<-EOS List ==== . Foo . Boo .Also . Blech EOS output = render_string input assert_xpath '//ol', output, 2 assert_xpath '(//ol)[1]/li', output, 2 assert_xpath '(//ol)[2]/li', output, 1 assert_xpath '(//ol)[2]/preceding-sibling::*[@class = "title"][text() = "Also"]', output, 1 end test "dot elements separated by an attribute entry offset by a blank line should not merge lists" do input = <<-EOS == List . Foo . Boo :foo: bar . Blech EOS output = render_embedded_string input assert_xpath '//ol', output, 2 assert_xpath '(//ol)[1]/li', output, 2 assert_xpath '(//ol)[2]/li', output, 1 end end end context "Labeled lists (:dlist)" do context "Simple lists" do test "single-line adjacent elements" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "single-line indented adjacent elements" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "single-line elements separated by blank line should create a single list" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 end test "a line comment between elements should divide them into separate lists" do input = <<-EOS term1:: def1 // term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl/dt', output, 2 assert_xpath '(//dl)[1]/dt', output, 1 assert_xpath '(//dl)[2]/dt', output, 1 end test "a ruler between elements should divide them into separate lists" do input = <<-EOS term1:: def1 ''' term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl//hr', output, 0 assert_xpath '(//dl)[1]/dt', output, 1 assert_xpath '(//dl)[2]/dt', output, 1 end test "a block title between elements should divide them into separate lists" do input = <<-EOS term1:: def1 .Some more term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl/dt', output, 2 assert_xpath '(//dl)[1]/dt', output, 1 assert_xpath '(//dl)[2]/dt', output, 1 assert_xpath '(//dl)[2]/preceding-sibling::*[@class="title"][text() = "Some more"]', output, 1 end test "multi-line elements with paragraph content" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line elements with indented paragraph content" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line element with multiple terms" do input = <<-EOS term1:: term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dd', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dt', output, 1 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line elements with blank line before paragraph content" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line elements with paragraph and literal content" do # blank line following literal paragraph is required or else it will gobble up the second term input = <<-EOS term1:: def1 literal term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '//dl/dt/following-sibling::dd//pre', output, 1 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "mixed single and multi-line adjacent elements" do input = <<-EOS term1:: def1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dt/following-sibling::dd', output, 2 assert_xpath '(//dl/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "element with anchor" do input = <<-EOS [[term1]]term1:: def1 [[term2]]term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dt', output, 2 assert_xpath '(//dl/dt)[1]/a[@id = "term1"]', output, 1 assert_xpath '(//dl/dt)[2]/a[@id = "term2"]', output, 1 end test "missing space before term does not produce labeled list" do input = <<-EOS term1::def1 term2::def2 EOS output = render_string input assert_xpath '//dl', output, 0 end test "literal block inside labeled list" do input = <<-EOS term:: + .... literal, line 1 literal, line 2 .... anotherterm:: def EOS output = render_string input assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dd', output, 2 assert_xpath '//dl/dd//pre', output, 1 assert_xpath '(//dl/dd)[1]/*[@class="literalblock"]//pre', output, 1 assert_xpath '(//dl/dd)[2]/p[text() = "def"]', output, 1 end test "literal block inside labeled list with trailing line continuation" do input = <<-EOS term:: + .... literal, line 1 literal, line 2 .... + anotherterm:: def EOS output = render_string input assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dd', output, 2 assert_xpath '//dl/dd//pre', output, 1 assert_xpath '(//dl/dd)[1]/*[@class="literalblock"]//pre', output, 1 assert_xpath '(//dl/dd)[2]/p[text() = "def"]', output, 1 end test "multiple listing blocks inside labeled list" do input = <<-EOS term:: + ---- listing, line 1 listing, line 2 ---- + ---- listing, line 1 listing, line 2 ---- anotherterm:: def EOS output = render_string input assert_xpath '//dl/dt', output, 2 assert_xpath '//dl/dd', output, 2 assert_xpath '//dl/dd//pre', output, 2 assert_xpath '(//dl/dd)[1]/*[@class="listingblock"]//pre', output, 2 assert_xpath '(//dl/dd)[2]/p[text() = "def"]', output, 1 end test "open block inside labeled list" do input = <<-EOS term:: + -- Open block as definition of term. And some more detail... -- anotherterm:: def EOS output = render_string input assert_xpath '//dl/dd//p', output, 3 assert_xpath '(//dl/dd)[1]//*[@class="openblock"]//p', output, 2 end test "paragraph attached by a list continuation on either side in a labeled list" do input = <<-EOS term1:: def1 + more detail + term2:: def2 EOS output = render_string input assert_xpath '(//dl/dt)[1][normalize-space(text())="term1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text())="term2"]', output, 1 assert_xpath '(//dl/dd)[1]//p', output, 2 assert_xpath '((//dl/dd)[1]//p)[1][text()="def1"]', output, 1 assert_xpath '(//dl/dd)[1]/p/following-sibling::*[@class="paragraph"]/p[text() = "more detail"]', output, 1 end test "paragraph attached by a list continuation on either side to a multi-line element in a labeled list" do input = <<-EOS term1:: def1 + more detail + term2:: def2 EOS output = render_string input assert_xpath '(//dl/dt)[1][normalize-space(text())="term1"]', output, 1 assert_xpath '(//dl/dt)[2][normalize-space(text())="term2"]', output, 1 assert_xpath '(//dl/dd)[1]//p', output, 2 assert_xpath '((//dl/dd)[1]//p)[1][text()="def1"]', output, 1 assert_xpath '(//dl/dd)[1]/p/following-sibling::*[@class="paragraph"]/p[text() = "more detail"]', output, 1 end test "verse paragraph inside a labeled list" do input = <<-EOS term1:: def + [verse] la la la term2:: def EOS output = render_string input assert_xpath '//dl/dd//p', output, 2 assert_xpath '(//dl/dd)[1]/*[@class="verseblock"]/pre[text() = "la la la"]', output, 1 end test "list inside a labeled list" do input = <<-EOS term1:: * level 1 ** level 2 * level 1 term2:: def EOS output = render_string input assert_xpath '//dl/dd', output, 2 assert_xpath '//dl/dd/p', output, 1 assert_xpath '(//dl/dd)[1]//ul', output, 2 assert_xpath '((//dl/dd)[1]//ul)[1]//ul', output, 1 end test "list inside a labeled list offset by blank lines" do input = <<-EOS term1:: * level 1 ** level 2 * level 1 term2:: def EOS output = render_string input assert_xpath '//dl/dd', output, 2 assert_xpath '//dl/dd/p', output, 1 assert_xpath '(//dl/dd)[1]//ul', output, 2 assert_xpath '((//dl/dd)[1]//ul)[1]//ul', output, 1 end test "should only grab one line following last item if item has no inline definition" do input = <<-EOS term1:: def1 term2:: def2 A new paragraph Another new paragraph EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dd', output, 2 assert_xpath '(//dl/dd)[1]/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dd)[2]/p[text() = "def2"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]', output, 2 assert_xpath '(//*[@class="dlist"]/following-sibling::*[@class="paragraph"])[1]/p[text() = "A new paragraph"]', output, 1 assert_xpath '(//*[@class="dlist"]/following-sibling::*[@class="paragraph"])[2]/p[text() = "Another new paragraph"]', output, 1 end test "should only grab one literal line following last item if item has no inline definition" do input = <<-EOS term1:: def1 term2:: def2 A new paragraph Another new paragraph EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dd', output, 2 assert_xpath '(//dl/dd)[1]/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dd)[2]/p[text() = "def2"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]', output, 2 assert_xpath '(//*[@class="dlist"]/following-sibling::*[@class="paragraph"])[1]/p[text() = "A new paragraph"]', output, 1 assert_xpath '(//*[@class="dlist"]/following-sibling::*[@class="paragraph"])[2]/p[text() = "Another new paragraph"]', output, 1 end test "should append subsequent paragraph literals to list item as block content" do input = <<-EOS term1:: def1 term2:: def2 literal A new paragraph. EOS output = render_string input assert_xpath '//dl', output, 1 assert_xpath '//dl/dd', output, 2 assert_xpath '(//dl/dd)[1]/p[text() = "def1"]', output, 1 assert_xpath '(//dl/dd)[2]/p[text() = "def2"]', output, 1 assert_xpath '(//dl/dd)[2]/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '(//dl/dd)[2]/p/following-sibling::*[@class="literalblock"]//pre[text() = "literal"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '(//*[@class="dlist"]/following-sibling::*[@class="paragraph"])[1]/p[text() = "A new paragraph."]', output, 1 end end context "Nested lists" do test "single-line adjacent nested elements" do input = <<-EOS term1:: def1 label1::: detail1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl)[1]/dt[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl)[1]/dt[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "single-line adjacent maximum nested elements" do input = <<-EOS term1:: def1 label1::: detail1 name1:::: value1 item1;; price1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 4 assert_xpath '//dl//dl//dl//dl', output, 1 end test "single-line nested elements seperated by blank line at top level" do input = <<-EOS term1:: def1 label1::: detail1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl)[1]/dt[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl)[1]/dt[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "single-line nested elements seperated by blank line at nested level" do input = <<-EOS term1:: def1 label1::: detail1 label2::: detail2 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl)[1]/dt[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl)[1]/dt[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "single-line adjacent nested elements with alternate delimiters" do input = <<-EOS term1:: def1 label1;; detail1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl)[1]/dt[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl)[1]/dt[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line adjacent nested elements" do input = <<-EOS term1:: def1 label1::: detail1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl)[1]/dt[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl)[1]/dt[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line nested elements seperated by blank line at nested level repeated" do input = <<-EOS term1:: def1 label1::: detail1 label2::: detail2 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '(//dl//dl/dt)[1][normalize-space(text()) = "label1"]', output, 1 assert_xpath '(//dl//dl/dt)[1]/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl//dl/dt)[2][normalize-space(text()) = "label2"]', output, 1 assert_xpath '(//dl//dl/dt)[2]/following-sibling::dd/p[text() = "detail2"]', output, 1 end test "multi-line element with indented nested element" do input = <<-EOS term1:: def1 label1;; detail1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt', output, 2 assert_xpath '(//dl)[1]/dd', output, 2 assert_xpath '((//dl)[1]/dt)[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '((//dl)[1]/dt)[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '((//dl)[1]/dt)[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '((//dl)[1]/dt)[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "mixed single and multi-line elements with indented nested elements" do input = <<-EOS term1:: def1 label1::: detail1 term2:: def2 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[text() = "def1"]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 assert_xpath '(//dl)[1]/dt[2][normalize-space(text()) = "term2"]', output, 1 assert_xpath '(//dl)[1]/dt[2]/following-sibling::dd/p[text() = "def2"]', output, 1 end test "multi-line elements with first paragraph folded to text with adjacent nested element" do input = <<-EOS term1:: def1 continued label1::: detail1 EOS output = render_string input assert_xpath '//dl', output, 2 assert_xpath '//dl//dl', output, 1 assert_xpath '(//dl)[1]/dt[1][normalize-space(text()) = "term1"]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[starts-with(text(), "def1")]', output, 1 assert_xpath '(//dl)[1]/dt[1]/following-sibling::dd/p[contains(text(), "continued")]', output, 1 assert_xpath '//dl//dl/dt[normalize-space(text()) = "label1"]', output, 1 assert_xpath '//dl//dl/dt/following-sibling::dd/p[text() = "detail1"]', output, 1 end end context 'Special lists' do test 'should render glossary list with proper semantics' do input = <<-EOS [glossary] term 1:: def 1 term 2:: def 2 EOS output = render_embedded_string input assert_css '.dlist.glossary', output, 1 assert_css '.dlist dt:not([class])', output, 2 end test 'should render horizontal list with proper markup' do input = <<-EOS [horizontal] first term:: definition + more detail second term:: definition EOS output = render_embedded_string input assert_css '.hdlist', output, 1 assert_css '.hdlist table', output, 1 assert_css '.hdlist table colgroup col', output, 2 assert_css '.hdlist table tr', output, 2 assert_xpath '/*[@class="hdlist"]/table/tr[1]/td', output, 2 assert_xpath '/*[@class="hdlist"]/table/tr[1]/td[@class="hdlist1"]', output, 1 assert_xpath '/*[@class="hdlist"]/table/tr[1]/td[@class="hdlist2"]', output, 1 assert_xpath '/*[@class="hdlist"]/table/tr[1]/td[@class="hdlist2"]/p', output, 1 assert_xpath '/*[@class="hdlist"]/table/tr[1]/td[@class="hdlist2"]/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '((//tr)[1]/td)[1][normalize-space(text())="first term"]', output, 1 assert_xpath '((//tr)[1]/td)[2]/p[normalize-space(text())="definition"]', output, 1 assert_xpath '/*[@class="hdlist"]/table/tr[2]/td', output, 2 assert_xpath '((//tr)[2]/td)[1][normalize-space(text())="second term"]', output, 1 assert_xpath '((//tr)[2]/td)[2]/p[normalize-space(text())="definition"]', output, 1 end test 'should render qanda list with proper semantics' do input = <<-EOS [qanda] Question one:: Answer one. Question two:: Answer two. EOS output = render_embedded_string input assert_css '.qlist.qanda', output, 1 assert_css '.qlist ol', output, 1 assert_css '.qlist ol li', output, 2 assert_css '.qlist ol li:nth-child(1) p em', output, 1 assert_css '.qlist ol li:nth-child(1) p', output, 2 end test 'should render bibliography list with proper semantics' do input = <<-EOS [bibliography] - [[[taoup]]] <NAME>. 'The Art of Unix Programming'. Addison-Wesley. ISBN 0-13-142901-9. - [[[walsh-muellner]]] <NAME> & <NAME>. 'DocBook - The Definitive Guide'. O'Reilly & Associates. 1999. ISBN 1-56592-580-7. EOS output = render_embedded_string input assert_css '.ulist.bibliography', output, 1 assert_css '.ulist.bibliography ul', output, 1 assert_css '.ulist.bibliography ul li', output, 2 assert_css '.ulist.bibliography ul li p', output, 2 assert_css '.ulist.bibliography ul li:nth-child(1) p a#taoup', output, 1 assert_xpath '//a/*', output, 0 text = xmlnodes_at_xpath '(//a)[1]/following-sibling::text()', output, 1 assert text.text.start_with?('[taoup] ') end end end context 'Labeled lists redux' do context 'Label without text on same line' do test 'folds text from subsequent line' do input = <<-EOS == Lists term1:: def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 end test 'folds text from first line after blank lines' do input = <<-EOS == Lists term1:: def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 end test 'folds text from first line after blank line and immediately preceding next item' do input = <<-EOS == Lists term1:: def1 term2:: def2 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 2 assert_xpath '(//*[@class="dlist"]//dd)[1]/p[text()="def1"]', output, 1 end test 'paragraph offset by blank lines does not break list if label does not have inline text' do input = <<-EOS == Lists term1:: def1 term2:: def2 EOS output = render_embedded_string input assert_css 'dl', output, 1 assert_css 'dl > dt', output, 2 assert_css 'dl > dd', output, 2 assert_xpath '(//dl/dd)[1]/p[text()="def1"]', output, 1 end test 'folds text from first line after comment line' do input = <<-EOS == Lists term1:: // comment def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 end test 'folds text from line following comment line offset by blank line' do input = <<-EOS == Lists term1:: // comment def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 end test 'folds text from subsequent indented line' do input = <<-EOS == Lists term1:: def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 end test 'folds text from indented line after blank line' do input = <<-EOS == Lists term1:: def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 end test 'folds text that looks like ruler offset by blank line' do input = <<-EOS == Lists term1:: ''' EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p/em[text()="'"]), output, 1 end test 'folds text that looks like ruler offset by blank line and line comment' do input = <<-EOS == Lists term1:: // comment ''' EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p/em[text()="'"]), output, 1 end test 'folds text that looks like ruler and the line following it offset by blank line' do input = <<-EOS == Lists term1:: ''' continued EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p/em[text()="'"]), output, 1 assert_xpath %(//*[@class="dlist"]//dd/p[normalize-space(text())="continued"]), output, 1 end test 'folds text that looks like title offset by blank line' do input = <<-EOS == Lists term1:: .def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()=".def1"]', output, 1 end test 'folds text that looks like title offset by blank line and line comment' do input = <<-EOS == Lists term1:: // comment .def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()=".def1"]', output, 1 end test 'folds text that looks like admonition offset by blank line' do input = <<-EOS == Lists term1:: NOTE: def1 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="NOTE: def1"]', output, 1 end test 'folds text of first literal line offset by blank line appends subsequent literals offset by blank line as blocks' do input = <<-EOS == Lists term1:: def1 literal literal EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]', output, 2 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 2 end test 'folds text of subsequent line and appends following literal line offset by blank line as block if term has no inline definition' do input = <<-EOS == Lists term1:: def1 literal term2:: def2 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 2 assert_xpath '(//*[@class="dlist"]//dd)[1]/p[text()="def1"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[1]/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[1]/p/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 1 end test 'appends literal line attached by continuation as block if item has no inline definition' do input = <<-EOS == Lists term1:: + literal EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]//pre[text()="literal"]', output, 1 end test 'appends literal line attached by continuation as block if item has no inline definition followed by ruler' do input = <<-EOS == Lists term1:: + literal ''' EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]//pre[text()="literal"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::hr', output, 1 end test 'appends line attached by continuation as block if item has no inline definition followed by ruler' do input = <<-EOS == Lists term1:: + para ''' EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/p[text()="para"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::hr', output, 1 end test 'appends line attached by continuation as block if item has no inline definition followed by block' do input = <<-EOS == Lists term1:: + para .... literal .... EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/p[text()="para"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 1 end test 'appends block attached by continuation but not subsequent block not attached by continuation' do input = <<-EOS == Lists term1:: + .... literal .... .... detached .... EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]//pre[text()="literal"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="literalblock"]//pre[text()="detached"]', output, 1 end test 'appends list if item has no inline definition' do input = <<-EOS == Lists term1:: * one * two * three EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd//ul/li', output, 3 end test 'appends list to first term when followed immediately by second term' do input = <<-EOS == Lists term1:: * one * two * three term2:: def2 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 2 assert_xpath '(//*[@class="dlist"]//dd)[1]/p', output, 0 assert_xpath '(//*[@class="dlist"]//dd)[1]//ul/li', output, 3 assert_xpath '(//*[@class="dlist"]//dd)[2]/p[text()="def2"]', output, 1 end test 'appends indented list to first term that is adjacent to second term' do input = <<-EOS == Lists label 1:: definition 1 * one * two * three label 2:: definition 2 paragraph EOS output = render_embedded_string input assert_css '.dlist > dl', output, 1 assert_css '.dlist dt', output, 2 assert_xpath '(//*[@class="dlist"]//dt)[1][normalize-space(text())="label 1"]', output, 1 assert_xpath '(//*[@class="dlist"]//dt)[2][normalize-space(text())="label 2"]', output, 1 assert_css '.dlist dd', output, 2 assert_xpath '(//*[@class="dlist"]//dd)[1]/p[text()="definition 1"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[2]/p[text()="definition 2"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[1]/p/following-sibling::*[@class="ulist"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[1]/p/following-sibling::*[@class="ulist"]//li', output, 3 assert_css '.dlist + .paragraph', output, 1 end test 'appends indented list to first term that is attached by a continuation and adjacent to second term' do input = <<-EOS == Lists label 1:: definition 1 + * one * two * three label 2:: definition 2 paragraph EOS output = render_embedded_string input assert_css '.dlist > dl', output, 1 assert_css '.dlist dt', output, 2 assert_xpath '(//*[@class="dlist"]//dt)[1][normalize-space(text())="label 1"]', output, 1 assert_xpath '(//*[@class="dlist"]//dt)[2][normalize-space(text())="label 2"]', output, 1 assert_css '.dlist dd', output, 2 assert_xpath '(//*[@class="dlist"]//dd)[1]/p[text()="definition 1"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[2]/p[text()="definition 2"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[1]/p/following-sibling::*[@class="ulist"]', output, 1 assert_xpath '(//*[@class="dlist"]//dd)[1]/p/following-sibling::*[@class="ulist"]//li', output, 3 assert_css '.dlist + .paragraph', output, 1 end test 'appends list and paragraph block when line following list attached by continuation' do input = <<-EOS == Lists term1:: * one * two * three + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/ul/li', output, 3 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'first continued line associated with nested list item and second continued line associated with term' do input = <<-EOS == Lists term1:: * one + nested list para + term1 para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/ul/li', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/ul/li/*[@class="paragraph"]/p[text()="nested list para"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="ulist"]/following-sibling::*[@class="paragraph"]/p[text()="term1 para"]', output, 1 end test 'literal line attached by continuation swallows adjacent line that looks like term' do input = <<-EOS == Lists term1:: + literal notnestedterm::: + literal notnestedterm::: EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]', output, 2 assert_xpath %(//*[@class="dlist"]//dd/*[@class="literalblock"]//pre[text()=" literal\nnotnestedterm:::"]), output, 2 end test 'line attached by continuation is appended as paragraph if term has no inline definition' do input = <<-EOS == Lists term1:: + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'appends line as paragraph if attached by continuation following blank line and line comment when term has no inline definition' do input = <<-EOS == Lists term1:: // comment + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'line attached by continuation offset by blank line is appended as paragraph if term has no inline definition' do input = <<-EOS == Lists term1:: + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p', output, 0 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'delimited block breaks list even when term has no inline definition' do input = <<-EOS == Lists term1:: ==== detached ==== EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 0 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="exampleblock"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="exampleblock"]//p[text()="detached"]', output, 1 end test 'attribute line breaks list even when term has no inline definition' do input = <<-EOS == Lists term1:: [verse] detached EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 0 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="verseblock"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="verseblock"]/pre[text()="detached"]', output, 1 end test 'id line breaks list even when term has no inline definition' do input = <<-EOS == Lists term1:: [[id]] detached EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 0 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]/p[text()="detached"]', output, 1 end end context 'Item with text inline' do test 'folds text from inline definition and subsequent line' do input = <<-EOS == Lists term1:: def1 continued EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p[text()="def1\ncontinued"]), output, 1 end test 'folds text from inline definition and subsequent lines' do input = <<-EOS == Lists term1:: def1 continued continued EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p[text()="def1\ncontinued\ncontinued"]), output, 1 end test 'folds text from inline definition and line following comment line' do input = <<-EOS == Lists term1:: def1 // comment continued EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p[text()="def1\ncontinued"]), output, 1 end test 'folds text from inline definition and subsequent indented line' do input = <<-EOS == Lists term1:: def1 continued EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath %(//*[@class="dlist"]//dd/p[text()="def1\ncontinued"]), output, 1 end test 'appends literal line offset by blank line as block if item has inline definition' do input = <<-EOS == Lists term1:: def1 literal EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 1 end test 'appends literal line offset by blank line as block and appends line after continuation as block if item has inline definition' do input = <<-EOS == Lists term1:: def1 literal + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="literalblock"]/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'appends line after continuation as block and literal line offset by blank line as block if item has inline definition' do input = <<-EOS == Lists term1:: def1 + para literal EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/*[@class="paragraph"]/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 1 end test 'appends list if item has inline definition' do input = <<-EOS == Lists term1:: def1 * one * two * three EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="ulist"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="ulist"]/ul/li', output, 3 end test 'appends literal line attached by continuation as block if item has inline definition followed by ruler' do input = <<-EOS == Lists term1:: def1 + literal ''' EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="literalblock"]//pre[text()="literal"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::hr', output, 1 end test 'line offset by blank line breaks list if term has inline definition' do input = <<-EOS == Lists term1:: def1 detached EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]/p[text()="detached"]', output, 1 end test 'nested term with definition does not consume following heading' do input = <<-EOS == Lists term:: def nestedterm;; nesteddef Detached ~~~~~~~~ EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 2 assert_xpath '//*[@class="dlist"]//dd', output, 2 assert_xpath '//*[@class="dlist"]/dl//dl', output, 1 assert_xpath '//*[@class="dlist"]/dl//dl/dt', output, 1 assert_xpath '((//*[@class="dlist"])[1]//dd)[1]/p[text()="def"]', output, 1 assert_xpath '((//*[@class="dlist"])[1]//dd)[1]/p/following-sibling::*[@class="dlist"]', output, 1 assert_xpath '((//*[@class="dlist"])[1]//dd)[1]/p/following-sibling::*[@class="dlist"]//dd/p[text()="nesteddef"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="sect2"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="sect2"]/h3[text()="Detached"]', output, 1 end test 'line attached by continuation is appended as paragraph if term has inline definition followed by detached paragraph' do input = <<-EOS == Lists term1:: def1 + para detached EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="paragraph"]/p[text()="detached"]', output, 1 end test 'line attached by continuation is appended as paragraph if term has inline definition followed by detached block' do input = <<-EOS == Lists term1:: def1 + para **** detached **** EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="sidebarblock"]', output, 1 assert_xpath '//*[@class="dlist"]/following-sibling::*[@class="sidebarblock"]//p[text()="detached"]', output, 1 end test 'line attached by continuation offset by line comment is appended as paragraph if term has inline definition' do input = <<-EOS == Lists term1:: def1 // comment + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'line attached by continuation offset by blank line is appended as paragraph if term has inline definition' do input = <<-EOS == Lists term1:: def1 + para EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 1 assert_xpath '//*[@class="dlist"]//dd', output, 1 assert_xpath '//*[@class="dlist"]//dd/p[text()="def1"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="dlist"]//dd/p/following-sibling::*[@class="paragraph"]/p[text()="para"]', output, 1 end test 'line comment offset by blank line divides lists because item has text' do input = <<-EOS == Lists term1:: def1 // term2:: def2 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 2 end test 'ruler offset by blank line divides lists because item has text' do input = <<-EOS == Lists term1:: def1 ''' term2:: def2 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 2 end test 'block title offset by blank line divides lists and becomes title of second list because item has text' do input = <<-EOS == Lists term1:: def1 .title term2:: def2 EOS output = render_embedded_string input assert_xpath '//*[@class="dlist"]/dl', output, 2 assert_xpath '(//*[@class="dlist"])[2]/*[@class="title"][text()="title"]', output, 1 end end end context 'Callout lists' do test 'listing block with sequential callouts followed by adjacent callout list' do input = <<-EOS [source] ---- require 'asciidoctor' # <1> doc = Asciidoctor::Document.new('Hello, World!') # <2> puts doc.render # <3> ---- <1> Describe the first line <2> Describe the second line <3> Describe the third line EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//programlisting', output, 1 assert_xpath '//programlisting//co', output, 3 assert_xpath '(//programlisting//co)[1][@id = "CO1-1"]', output, 1 assert_xpath '(//programlisting//co)[2][@id = "CO1-2"]', output, 1 assert_xpath '(//programlisting//co)[3][@id = "CO1-3"]', output, 1 assert_xpath '//programlisting/following-sibling::calloutlist/callout', output, 3 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[1][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[2][@arearefs = "CO1-2"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[3][@arearefs = "CO1-3"]', output, 1 end test 'listing block with sequential callouts followed by non-adjacent callout list' do input = <<-EOS [source] ---- require 'asciidoctor' # <1> doc = Asciidoctor::Document.new('Hello, World!') # <2> puts doc.render # <3> ---- Paragraph. <1> Describe the first line <2> Describe the second line <3> Describe the third line EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//programlisting', output, 1 assert_xpath '//programlisting//co', output, 3 assert_xpath '(//programlisting//co)[1][@id = "CO1-1"]', output, 1 assert_xpath '(//programlisting//co)[2][@id = "CO1-2"]', output, 1 assert_xpath '(//programlisting//co)[3][@id = "CO1-3"]', output, 1 assert_xpath '//programlisting/following-sibling::*[1][self::simpara]', output, 1 assert_xpath '//programlisting/following-sibling::calloutlist/callout', output, 3 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[1][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[2][@arearefs = "CO1-2"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[3][@arearefs = "CO1-3"]', output, 1 end test 'listing block with a callout that refers to two different lines' do input = <<-EOS [source] ---- require 'asciidoctor' # <1> doc = Asciidoctor::Document.new('Hello, World!') # <2> puts doc.render # <2> ---- <1> Import the library <2> Where the magic happens EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//programlisting', output, 1 assert_xpath '//programlisting//co', output, 3 assert_xpath '(//programlisting//co)[1][@id = "CO1-1"]', output, 1 assert_xpath '(//programlisting//co)[2][@id = "CO1-2"]', output, 1 assert_xpath '(//programlisting//co)[3][@id = "CO1-3"]', output, 1 assert_xpath '//programlisting/following-sibling::calloutlist/callout', output, 2 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[1][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[2][@arearefs = "CO1-2 CO1-3"]', output, 1 end test 'listing block with non-sequential callouts followed by adjacent callout list' do input = <<-EOS [source] ---- require 'asciidoctor' # <2> doc = Asciidoctor::Document.new('Hello, World!') # <3> puts doc.render # <1> ---- <1> Describe the first line <2> Describe the second line <3> Describe the third line EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//programlisting', output, 1 assert_xpath '//programlisting//co', output, 3 assert_xpath '(//programlisting//co)[1][@id = "CO1-1"]', output, 1 assert_xpath '(//programlisting//co)[2][@id = "CO1-2"]', output, 1 assert_xpath '(//programlisting//co)[3][@id = "CO1-3"]', output, 1 assert_xpath '//programlisting/following-sibling::calloutlist/callout', output, 3 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[1][@arearefs = "CO1-3"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[2][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//programlisting/following-sibling::calloutlist/callout)[3][@arearefs = "CO1-2"]', output, 1 end test 'two listing blocks can share the same callout list' do input = <<-EOS .Import library [source] ---- require 'asciidoctor' # <1> ---- .Use library [source] ---- doc = Asciidoctor::Document.new('Hello, World!') # <2> puts doc.render # <3> ---- <1> Describe the first line <2> Describe the second line <3> Describe the third line EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//programlisting', output, 2 assert_xpath '(//programlisting)[1]//co', output, 1 assert_xpath '(//programlisting)[1]//co[@id = "CO1-1"]', output, 1 assert_xpath '(//programlisting)[2]//co', output, 2 assert_xpath '((//programlisting)[2]//co)[1][@id = "CO1-2"]', output, 1 assert_xpath '((//programlisting)[2]//co)[2][@id = "CO1-3"]', output, 1 assert_xpath '(//calloutlist/callout)[1][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//calloutlist/callout)[2][@arearefs = "CO1-2"]', output, 1 assert_xpath '(//calloutlist/callout)[3][@arearefs = "CO1-3"]', output, 1 end test 'two listing blocks each followed by an adjacent callout list' do input = <<-EOS .Import library [source] ---- require 'asciidoctor' # <1> ---- <1> Describe the first line .Use library [source] ---- doc = Asciidoctor::Document.new('Hello, World!') # <1> puts doc.render # <2> ---- <1> Describe the second line <2> Describe the third line EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//programlisting', output, 2 assert_xpath '(//programlisting)[1]//co', output, 1 assert_xpath '(//programlisting)[1]//co[@id = "CO1-1"]', output, 1 assert_xpath '(//programlisting)[2]//co', output, 2 assert_xpath '((//programlisting)[2]//co)[1][@id = "CO2-1"]', output, 1 assert_xpath '((//programlisting)[2]//co)[2][@id = "CO2-2"]', output, 1 assert_xpath '//calloutlist', output, 2 assert_xpath '(//calloutlist)[1]/callout', output, 1 assert_xpath '((//calloutlist)[1]/callout)[1][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//calloutlist)[2]/callout', output, 2 assert_xpath '((//calloutlist)[2]/callout)[1][@arearefs = "CO2-1"]', output, 1 assert_xpath '((//calloutlist)[2]/callout)[2][@arearefs = "CO2-2"]', output, 1 end test 'callout list with block content' do input = <<-EOS [source] ---- require 'asciidoctor' # <1> doc = Asciidoctor::Document.new('Hello, World!') # <2> puts doc.render # <3> ---- <1> Imports the library as a RubyGem <2> Creates a new document * Scans the lines for known blocks * Converts the lines into blocks <3> Renders the document + You can write this to file rather than printing to stdout. EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//calloutlist', output, 1 assert_xpath '//calloutlist/callout', output, 3 assert_xpath '(//calloutlist/callout)[1]/*', output, 1 assert_xpath '(//calloutlist/callout)[2]/para', output, 1 assert_xpath '(//calloutlist/callout)[2]/itemizedlist', output, 1 assert_xpath '(//calloutlist/callout)[3]/para', output, 1 assert_xpath '(//calloutlist/callout)[3]/simpara', output, 1 end test 'escaped callout should not be interpreted as a callout' do input = <<-EOS [source] ---- require 'asciidoctor' # \\<1> ---- EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//co', output, 0 end test 'literal block with callouts' do input = <<-EOS .... Roses are red <1> Violets are blue <2> .... <1> And so is Ruby <2> But violet is more like purple EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '//literallayout', output, 1 assert_xpath '//literallayout//co', output, 2 assert_xpath '(//literallayout//co)[1][@id = "CO1-1"]', output, 1 assert_xpath '(//literallayout//co)[2][@id = "CO1-2"]', output, 1 assert_xpath '//literallayout/following-sibling::*[1][self::calloutlist]/callout', output, 2 assert_xpath '(//literallayout/following-sibling::*[1][self::calloutlist]/callout)[1][@arearefs = "CO1-1"]', output, 1 assert_xpath '(//literallayout/following-sibling::*[1][self::calloutlist]/callout)[2][@arearefs = "CO1-2"]', output, 1 end test 'callout list with icons enabled' do input = <<-EOS [source] ---- require 'asciidoctor' # <1> doc = Asciidoctor::Document.new('Hello, World!') # <2> puts doc.render # <3> ---- <1> Describe the first line <2> Describe the second line <3> Describe the third line EOS output = render_embedded_string input, :attributes => {'icons' => ''} assert_css '.listingblock code > img', output, 3 (1..3).each do |i| assert_xpath %((/div[@class="listingblock"]//code/img)[#{i}][@src="images/icons/callouts/#{i}.png"][@alt="#{i}"]), output, 1 end assert_css '.colist table td img', output, 3 (1..3).each do |i| assert_xpath %((/div[@class="colist arabic"]//td/img)[#{i}][@src="images/icons/callouts/#{i}.png"][@alt="#{i}"]), output, 1 end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/backends/html5.rb
module Asciidoctor class BaseTemplate # create template matter to insert a style class from the role attribute if specified def role_class attrvalue(:role) end # create template matter to insert a style class from the style attribute if specified def style_class(sibling = true) attrvalue(:style, sibling) end def title_div(opts = {}) %(<% if title? %><div class="title">#{opts.has_key?(:caption) ? '<%= @caption %>' : ''}<%= title %></div><% end %>) end end module HTML5 class DocumentTemplate < BaseTemplate def self.outline(node, to_depth = 2) toc_level = nil sections = node.sections unless sections.empty? toc_level, indent = '' nested = true unless node.is_a?(Document) if node.document.doctype == 'book' indent = ' ' * node.level unless node.level == 0 nested = node.level > 0 else indent = ' ' * node.level end end toc_level << "#{indent}<ol>\n" if nested sections.each do |section| toc_level << "#{indent} <li><a href=\"##{section.id}\">#{!section.special && section.level > 0 ? "#{section.sectnum} " : ''}#{section.attr('caption')}#{section.title}</a></li>\n" if section.level < to_depth && (child_toc_level = outline(section, to_depth)) if section.document.doctype != 'book' || section.level > 0 toc_level << "#{indent} <li>\n#{child_toc_level}\n#{indent} </li>\n" else toc_level << "#{indent}#{child_toc_level}\n" end end end toc_level << "#{indent}</ol>" if nested end toc_level end # Internal: Generate the default stylesheet for CodeRay # # returns the default CodeRay stylesheet as a String def self.default_coderay_stylesheet Helpers.require_library 'coderay' ::CodeRay::Encoders[:html]::CSS.new(:default).stylesheet end def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><!DOCTYPE html> <html lang="<%= attr :lang, 'en' %>"> <head> <meta http-equiv="Content-Type" content="text/html; charset=<%= attr :encoding %>"> <meta name="generator" content="Asciidoctor <%= attr 'asciidoctor-version' %>"> <% if attr? :description %><meta name="description" content="<%= attr :description %>"><% end %> <% if attr? :keywords %><meta name="keywords" content="<%= attr :keywords %>"><% end %> <title><%= doctitle %></title> <% if attr? :toc %> <style> #toc > ol { padding-left: 0; } #toc ol { list-style-type: none; } </style> <% end %> <% unless attr(:stylesheet, '').empty? %> <link rel="stylesheet" href="<%= (attr? :stylesdir) ? File.join((attr :stylesdir), (attr :stylesheet)) : (attr :stylesheet) %>"> <% end %> <% case attr 'source-highlighter' %><% when 'coderay' %> <style> pre.highlight { border: none; background-color: #F8F8F8; } pre.highlight code, pre.highlight pre { color: #333; } pre.highlight span.line-numbers { display: inline-block; margin-right: 4px; padding: 1px 4px; } pre.highlight .line-numbers { background-color: #D5F6F6; color: gray; } pre.highlight .line-numbers pre { color: gray; } <% if (attr 'coderay-css', 'class') == 'class' %><%= template.class.default_coderay_stylesheet %><% end %> </style><% when 'highlightjs' %> <link rel="stylesheet" href="<%= (attr :highlightjsdir, 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3') %>/styles/<%= (attr 'highlightjs-theme', 'default') %>.min.css"> <style> pre code { background-color: #F8F8F8; padding: 0; } </style> <script src="<%= (attr :highlightjsdir, 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3') %>/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad()</script> <% end %> </head> <body#{id} class="<%= doctype %>"<% if attr? 'max-width' %> style="max-width: <%= attr 'max-width' %>;"<% end %>> <% unless noheader %> <div id="header"> <% if has_header? %> <% unless notitle %> <h1><%= @header.title %></h1> <% end %> <% if attr? :author %><span id="author"><%= attr :author %></span><br><% end %> <% if attr? :email %><span id="email" class="monospaced">&lt;<%= attr :email %>&gt;</span><br><% end %> <% if attr? :revnumber %><span id="revnumber">version <%= attr :revnumber %><%= attr?(:revdate) ? ',' : '' %></span><% end %> <% if attr? :revdate %><span id="revdate"><%= attr :revdate %></span><% end %> <% if attr? :revremark %><br><span id="revremark"><%= attr :revremark %></span><% end %> <% end %> <% if attr? :toc %> <div id="toc"> <div id="toctitle"><%= attr 'toc-title' %></div> <%= template.class.outline(self, (attr :toclevels, 2).to_i) %> </div> <% end %> </div> <% end %> <div id="content"> <%= content %> </div> <% if footnotes? %> <div id="footnotes"> <hr> <% footnotes.each do |fn| %> <div class="footnote" id="_footnote_<%= fn.index %>"> <a href="#_footnoteref_<%= fn.index %>"><%= fn.index %></a>. <%= fn.text %> </div> <% end %> </div> <% end %> <div id="footer"> <div id="footer-text"> <% if attr? :revnumber %>Version <%= attr :revnumber %><br><% end %> Last updated <%= attr :docdatetime %> </div> </div> </body> </html> EOS end end class EmbeddedTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% unless notitle || !has_header? %><h1#{id}><%= header.title %></h1> <% end %><%= content %> EOS end end class BlockPreambleTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div id="preamble"> <div class="sectionbody"> <%= content %> </div> </div> EOS end end class SectionTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% if @level == 0 %> <h1#{id}><%= title %></h1> <%= content %> <% else %> <div class="sect<%= @level %>#{role_class}"> <h<%= @level + 1 %>#{id}><% if !@special && (attr? :numbered) && @level < 4 %><%= sectnum %> <% end %><%= attr :caption %><%= title %></h<%= @level + 1 %>> <% if @level == 1 %> <div class="sectionbody"> <%= content %> </div> <% else %> <%= content %> <% end %> </div> <% end %> EOS end end class BlockFloatingTitleTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><h<%= @level + 1 %>#{id} class="#{style_class false}#{role_class}"><%= title %></h<%= @level + 1 %>> EOS end end class BlockDlistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% if attr? :style, 'qanda' %> <div#{id} class="qlist#{style_class}#{role_class}"> #{title_div} <ol> <% content.each do |dt, dd| %> <li> <p><em><%= dt.text %></em></p> <% unless dd.nil? %> <% if dd.text? %> <p><%= dd.text %></p> <% end %> <% if dd.blocks? %> <%= dd.content %> <% end %> <% end %> </li> <% end %> </ol> </div> <% elsif attr? :style, 'horizontal' %> <div#{id} class="hdlist#{role_class}"> #{title_div} <table> <colgroup> <col<% if attr? :labelwidth %> style="width: <%= attr :labelwidth %>%;"<% end %>> <col<% if attr? :itemwidth %> style="width: <%= attr :itemwidth %>%;"<% end %>> </colgroup> <% content.each do |dt, dd| %> <tr> <td class="hdlist1<% if attr? 'strong-option' %> strong<% end %>"> <%= dt.text %> <br> </td> <td class="hdlist2"><% unless dd.nil? %><% if dd.text? %> <p style="margin-top: 0"><%= dd.text %></p><% end %><% if dd.blocks? %> <%= dd.content %><% end %><% end %> </td> </tr> <% end %> </table> </div> <% else %> <div#{id} class="dlist#{style_class}#{role_class}"> #{title_div} <dl> <% content.each do |dt, dd| %> <dt<% if !(attr? :style) %> class="hdlist1"<% end %>> <%= dt.text %> </dt> <% unless dd.nil? %> <dd> <% if dd.text? %> <p><%= dd.text %></p> <% end %> <% if dd.blocks? %> <%= dd.content %> <% end %> </dd> <% end %> <% end %> </dl> </div> <% end %> EOS end end class BlockListingTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="listingblock#{role_class}"> #{title_div :caption => true} <div class="content monospaced"> <% if attr? :style, 'source' %> <pre class="highlight<% if attr? 'source-highlighter', 'coderay' %> CodeRay<% end %>"><code#{attribute('class', :language)}><%= template.preserve_endlines(content, self) %></code></pre> <% else %> <pre><%= template.preserve_endlines(content, self) %></pre> <% end %> </div> </div> EOS end end class BlockLiteralTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="literalblock#{role_class}"> #{title_div} <div class="content monospaced"> <pre><%= template.preserve_endlines(content, self) %></pre> </div> </div> EOS end end class BlockAdmonitionTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="admonitionblock#{role_class}"> <table> <tr> <td class="icon"> <% if attr? :icons %> <img src="<%= icon_uri(attr :name) %>" alt="<%= attr :caption %>"> <% else %> <div class="title"><%= attr :caption %></div> <% end %> </td> <td class="content"> #{title_div} <%= content %> </td> </tr> </table> </div> EOS end end class BlockParagraphTemplate < BaseTemplate def paragraph(id, role, title, content) %(<div#{id && " id=\"#{id}\""} class=\"paragraph#{role && " #{role}"}\"> #{title && "<div class=\"title\">#{title}</div>"} <p>#{content}</p> </div>) end def template # very hot piece of code, optimized for speed @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><%= template.paragraph(@id, (attr 'role'), title? ? title : nil, content) %> EOS end end class BlockSidebarTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="sidebarblock#{role_class}"> <div class="content"> #{title_div} <%= content %> </div> </div> EOS end end class BlockExampleTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="exampleblock#{role_class}"> #{title_div :caption => true} <div class="content"> <%= content %> </div> </div> EOS end end class BlockOpenTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="openblock#{role_class}"> #{title_div} <div class="content"> <%= content %> </div> </div> EOS end end class BlockPassTemplate < BaseTemplate def template :content end end class BlockQuoteTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="quoteblock#{role_class}"> #{title_div} <blockquote> <%= content %> </blockquote> <div class="attribution"> <% if attr? :citetitle %> <cite><%= attr :citetitle %></cite> <% end %> <% if attr? :attribution %> <% if attr? :citetitle %> <br> <% end %> <%= "&#8212; \#{attr :attribution}" %> <% end %> </div> </div> EOS end end class BlockVerseTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="verseblock#{role_class}"> #{title_div} <pre class="content"><%= template.preserve_endlines(content, self) %></pre> <div class="attribution"> <% if attr? :citetitle %> <cite><%= attr :citetitle %></cite> <% end %> <% if attr? :attribution %> <% if attr? :citetitle %> <br> <% end %> <%= "&#8212; \#{attr :attribution}" %> <% end %> </div> </div> EOS end end class BlockUlistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="ulist#{style_class}#{role_class}"> #{title_div} <ul> <% content.each do |item| %> <li> <p><%= item.text %></p> <% if item.blocks? %> <%= item.content %> <% end %> </li> <% end %> </ul> </div> EOS end end class BlockOlistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="olist#{style_class}#{role_class}"> #{title_div} <ol class="<%= attr :style %>"#{attribute('start', :start)}> <% content.each do |item| %> <li> <p><%= item.text %></p> <% if item.blocks? %> <%= item.content %> <% end %> </li> <% end %> </ol> </div> EOS end end class BlockColistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="colist#{style_class}#{role_class}"> #{title_div} <% if attr? :icons %> <table> <% content.each_with_index do |item, i| %> <tr> <td><img src="<%= icon_uri("callouts/\#{i + 1}") %>" alt="<%= i + 1 %>"></td> <td><%= item.text %></td> </tr> <% end %> </table> <% else %> <ol> <% content.each do |item| %> <li> <p><%= item.text %></p> </li> <% end %> </ol> <% end %> </div> EOS end end class BlockTableTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><table#{id} class="tableblock frame-<%= attr :frame, 'all' %> grid-<%= attr :grid, 'all'%>#{role_class}" style="<% if !(attr? 'autowidth-option') %>width: <%= attr :tablepcwidth %>%; <% end %><% if attr? :float %>float: <%= attr :float %>; <% end %>"> <% if title? %> <caption class="title"><% unless @caption.nil? %><%= @caption %><% end %><%= title %></caption> <% end %> <% if (attr :rowcount) >= 0 %> <colgroup> <% if attr? 'autowidth-option' %> <% @columns.each do %> <col> <% end %> <% else %> <% @columns.each do |col| %> <col style="width: <%= col.attr :colpcwidth %>%;"> <% end %> <% end %> </colgroup> <% [:head, :foot, :body].select {|tsec| !@rows[tsec].empty? }.each do |tsec| %> <t<%= tsec %>> <% @rows[tsec].each do |row| %> <tr> <% row.each do |cell| %> <<%= tsec == :head ? 'th' : 'td' %> class="tableblock halign-<%= cell.attr :halign %> valign-<%= cell.attr :valign %>"#{attribute('colspan', 'cell.colspan')}#{attribute('rowspan', 'cell.rowspan')}><% if tsec == :head %><%= cell.text %><% else %><% case cell.attr(:style) when :asciidoc %><div><%= cell.content %></div><% when :verse %><div class="verse"><%= template.preserve_endlines(cell.text, self) %></div><% when :literal %><div class="literal monospaced"><pre><%= template.preserve_endlines(cell.text, self) %></pre></div><% when :header %><% cell.content.each do |text| %><p class="tableblock header"><%= text %></p><% end %><% else %><% cell.content.each do |text| %><p class="tableblock"><%= text %></p><% end %><% end %><% end %></<%= tsec == :head ? 'th' : 'td' %>> <% end %> </tr> <% end %> </t<%= tsec %>> <% end %> <% end %> </table> EOS end end class BlockImageTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div#{id} class="imageblock#{style_class}#{role_class}"<% if (attr? :align) || (attr? :float) %> style="<% if attr? :align %>text-align: <%= attr :align %><% if attr? :float %>; <% end %><% end %><% if attr? :float %>float: <%= attr :float %><% end %>"<% end %>> <div class="content"> <% if attr? :link %> <a class="image" href="<%= attr :link %>"><img src="<%= image_uri(attr :target) %>" alt="<%= attr :alt %>"#{attribute('width', :width)}#{attribute('height', :height)}></a> <% else %> <img src="<%= image_uri(attr :target) %>" alt="<%= attr :alt %>"#{attribute('width', :width)}#{attribute('height', :height)}> <% end %> </div> #{title_div :caption => true} </div> EOS end end class BlockRulerTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><hr> EOS end end class BlockPageBreakTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><div style="page-break-after: always"></div> EOS end end class InlineBreakTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><%= "\#@text<br>" %> EOS end end class InlineCalloutTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% if attr? :icons %><img src="<%= icon_uri("callouts/\#@text") %>" alt="<%= @text %>"><% else %><b>&lt;<%= @text %>&gt;</b><% end %> EOS end end class InlineQuotedTemplate < BaseTemplate QUOTED_TAGS = { :emphasis => ['<em>', '</em>'], :strong => ['<strong>', '</strong>'], :monospaced => ['<tt>', '</tt>'], :superscript => ['<sup>', '</sup>'], :subscript => ['<sub>', '</sub>'], :double => ['&#8220;', '&#8221;'], :single => ['&#8216;', '&#8217;'] #:none => ['', ''] } def quote(text, type, role) start_tag, end_tag = QUOTED_TAGS[type] || ['', ''] if role "#{start_tag}<span class=\"#{role}\">#{text}</span>#{end_tag}" else "#{start_tag}#{text}#{end_tag}" end end def template # very hot piece of code, optimized for speed @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><%= template.quote(@text, @type, attr('role')) %> EOS end end class InlineAnchorTemplate < BaseTemplate def anchor(target, text, type, document, window = nil) case type when :xref text = document.references[:ids].fetch(target, "[#{target}]") if text.nil? %(<a href="##{target}">#{text}</a>) when :ref %(<a id="#{target}"></a>) when :bibref %(<a id="#{target}"></a>[#{target}]) when :link %(<a href="#{target}"#{window && " target=\"#{window}\""}>#{text}</a>) end end def template # hot piece of code, optimized for speed @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><%= template.anchor(@target, @text, @type, @document, @type == :link ? attr('window') : nil) %> EOS end end class InlineImageTemplate < BaseTemplate def template # care is taken here to avoid a space inside the optional <a> tag @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><span class="image#{role_class}"> <% if attr? :link %><a class="image" href="<%= attr :link %>"><% end %><img src="<%= image_uri(@target) %>" alt="<%= attr :alt %>"#{attribute('width', :width)}#{attribute('height', :height)}#{attribute('title', :title)}><% if attr? :link%></a><% end %> </span> EOS end end class InlineFootnoteTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% if @type == :xref %><span class="footnoteref">[<a class="footnote" href="#_footnote_<%= attr :index %>" title="View footnote."><%= attr :index %></a>]</span><% else %><span class="footnote"<% if @id %> id="_footnote_<%= @id %>"<% end %>>[<a id="_footnoteref_<%= attr :index %>" class="footnote" href="#_footnote_<%= attr :index %>" title="View footnote."><%= attr :index %></a>]</span><% end %> EOS end end class InlineIndextermTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><%= "\#{@type == :visible ? @text : ''}" %> EOS end end end # module HTML5 end # module Asciidoctor
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/links_test.rb
require 'test_helper' context 'Links' do test 'qualified url inline with text' do assert_xpath "//a[@href='http://asciidoc.org'][text() = 'http://asciidoc.org']", render_string("The AsciiDoc project is located at http://asciidoc.org.") end test 'qualified url with label' do assert_xpath "//a[@href='http://asciidoc.org'][text() = 'AsciiDoc']", render_string("We're parsing http://asciidoc.org[AsciiDoc] markup") end test 'qualified url with label containing escaped right square bracket' do assert_xpath "//a[@href='http://asciidoc.org'][text() = '[Ascii]Doc']", render_string("We're parsing http://asciidoc.org[[Ascii\\]Doc] markup") end test 'qualified url with label using link macro' do assert_xpath "//a[@href='http://asciidoc.org'][text() = 'AsciiDoc']", render_string("We're parsing link:http://asciidoc.org[AsciiDoc] markup") end test 'qualified url using macro syntax with multi-line label inline with text' do assert_xpath %{//a[@href='http://asciidoc.org'][text() = 'AsciiDoc\nmarkup']}, render_string("We're parsing link:http://asciidoc.org[AsciiDoc\nmarkup]") end test 'qualified url surrounded by angled brackets' do assert_xpath '//a[@href="http://asciidoc.org"][text()="http://asciidoc.org"]', render_string('<http://asciidoc.org> is the project page for AsciiDoc.'), 1 end test 'qualified url surrounded by round brackets' do assert_xpath '//a[@href="http://asciidoc.org"][text()="http://asciidoc.org"]', render_string('(http://asciidoc.org) is the project page for AsciiDoc.'), 1 end test 'qualified url adjacent to text in square brackets' do assert_xpath '//a[@href="http://asciidoc.org"][text()="AsciiDoc"]', render_string(']http://asciidoc.org[AsciiDoc] project page.'), 1 end test 'qualified url adjacent to text in round brackets' do assert_xpath '//a[@href="http://asciidoc.org"][text()="AsciiDoc"]', render_string(')http://asciidoc.org[AsciiDoc] project page.'), 1 end test 'qualified url using invalid link macro should not create link' do assert_xpath '//a', render_string('link:http://asciidoc.org is the project page for AsciiDoc.'), 0 end test 'escaped inline qualified url should not create link' do assert_xpath '//a', render_string('\http://asciidoc.org is the project page for AsciiDoc.'), 0 end test 'escaped inline qualified url using macro syntax should not create link' do assert_xpath '//a', render_string('\http://asciidoc.org[AsciiDoc] is the key to good docs.'), 0 end test 'inline qualified url followed by an endline should not include endline in link' do assert_xpath '//a[@href="http://github.com/asciidoctor"]', render_string("The source code for Asciidoctor can be found at http://github.com/asciidoctor\nwhich is a GitHub organization."), 1 end test 'qualified url divided by endline using macro syntax should not create link' do assert_xpath '//a', render_string("The source code for Asciidoctor can be found at link:http://github.com/asciidoctor\n[]which is a GitHub organization."), 0 end test 'qualified url containing whitespace using macro syntax should not create link' do assert_xpath '//a', render_string('I often need to refer to the chapter on link:http://asciidoc.org?q=attribute references[Attribute References].'), 0 end test 'qualified url containing an encoded space using macro syntax should create a link' do assert_xpath '//a', render_string('I often need to refer to the chapter on link:http://asciidoc.org?q=attribute%20references[Attribute References].'), 1 end test 'inline quoted qualified url should not consume surrounding angled brackets' do assert_xpath '//a[@href="http://github.com/asciidoctor"]', render_string('Asciidoctor GitHub organization: <**http://github.com/asciidoctor**>'), 1 end test 'inline ref' do doc = document_from_string 'Here you can read about tigers.[[tigers]]' output = doc.render assert_equal '[tigers]', doc.references[:ids]['tigers'] assert_xpath '//a[@id = "tigers"]', output, 1 assert_xpath '//a[@id = "tigers"]/child::text()', output, 0 end test 'inline ref with reftext' do doc = document_from_string 'Here you can read about tigers.[[tigers,Tigers]]' output = doc.render assert_equal 'Tigers', doc.references[:ids]['tigers'] assert_xpath '//a[@id = "tigers"]', output, 1 assert_xpath '//a[@id = "tigers"]/child::text()', output, 0 end test 'escaped inline ref' do doc = document_from_string 'Here you can read about tigers.\[[tigers]]' output = doc.render assert !doc.references[:ids].has_key?('tigers') assert_xpath '//a[@id = "tigers"]', output, 0 end test 'xref using angled bracket syntax' do doc = document_from_string '<<tigers>>' doc.references[:ids]['tigers'] = '[tigers]' assert_xpath '//a[@href="#tigers"][text() = "[tigers]"]', doc.render, 1 end test 'xref using angled bracket syntax with label' do assert_xpath '//a[@href="#tigers"][text() = "About Tigers"]', render_string('<<tigers,About Tigers>>'), 1 end test 'xref using angled bracket syntax with quoted label' do assert_xpath '//a[@href="#tigers"][text() = "About Tigers"]', render_string('<<tigers,"About Tigers">>'), 1 end test 'xref using angled bracket syntax inline with text' do assert_xpath '//a[@href="#tigers"][text() = "about tigers"]', render_string('Want to learn <<tigers,about tigers>>?'), 1 end test 'xref using angled bracket syntax with multi-line label inline with text' do assert_xpath %{//a[@href="#tigers"][text() = "about\ntigers"]}, render_string("Want to learn <<tigers,about\ntigers>>?"), 1 end test 'xref using macro syntax' do doc = document_from_string 'xref:tigers[]' doc.references[:ids]['tigers'] = '[tigers]' assert_xpath '//a[@href="#tigers"][text() = "[tigers]"]', doc.render, 1 end test 'xref using macro syntax with label' do assert_xpath '//a[@href="#tigers"][text() = "About Tigers"]', render_string('xref:tigers[About Tigers]'), 1 end test 'xref using macro syntax inline with text' do assert_xpath '//a[@href="#tigers"][text() = "about tigers"]', render_string('Want to learn xref:tigers[about tigers]?'), 1 end test 'xref using macro syntax with multi-line label inline with text' do assert_xpath %{//a[@href="#tigers"][text() = "about\ntigers"]}, render_string("Want to learn xref:tigers[about\ntigers]?"), 1 end test 'xref using invalid macro syntax does not create link' do doc = document_from_string 'xref:tigers' doc.references[:ids]['tigers'] = '[tigers]' assert_xpath '//a', doc.render, 0 end test 'xref creates link for unknown reference' do doc = document_from_string '<<tigers>>' assert_xpath '//a[@href="#tigers"][text() = "[tigers]"]', doc.render, 1 end test 'xref shows label from title of target for forward and backward references in html backend' do input = <<-EOS == Section A <\<_section_b>> == Section B <\<_section_a>> EOS output = render_embedded_string input assert_xpath '//h2[@id="_section_a"][text()="Section A"]', output, 1 assert_xpath '//a[@href="#_section_a"][text()="Section A"]', output, 1 assert_xpath '//h2[@id="_section_b"][text()="Section B"]', output, 1 assert_xpath '//a[@href="#_section_b"][text()="Section B"]', output, 1 end test 'anchor creates reference' do doc = document_from_string "[[tigers]]Tigers roam here." assert_equal({'tigers' => '[tigers]'}, doc.references[:ids]) end test 'anchor with label creates reference' do doc = document_from_string "[[tigers,Tigers]]Tigers roam here." assert_equal({'tigers' => 'Tigers'}, doc.references[:ids]) end test 'anchor with quoted label creates reference' do doc = document_from_string %([["tigers","Tigers roam here"]]Tigers roam here.) assert_equal({'tigers' => "Tigers roam here"}, doc.references[:ids]) end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/section.rb
<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/section.rb<gh_stars>0 module Asciidoctor # Public: Methods for managing sections of AsciiDoc content in a document. # The section responds as an Array of content blocks by delegating # block-related methods to its @blocks Array. # # Examples # # section = Asciidoctor::Section.new # section.title = 'Section 1' # section.id = 'sect1' # # section.size # => 0 # # section.id # => "sect1" # # section << new_block # section.size # => 1 class Section < AbstractBlock # Public: Get/Set the Integer index of this section within the parent block attr_accessor :index # Public: Get/Set the section name of this section attr_accessor :sectname # Public: Get/Set the flag to indicate whether this is a special section or a child of one attr_accessor :special # Public: Initialize an Asciidoctor::Section object. # # parent - The parent Asciidoc Object. def initialize(parent = nil, level = nil) super(parent, :section) if level.nil? && !parent.nil? @level = parent.level + 1 end if parent.is_a?(Section) && parent.special @special = true else @special = false end @index = 0 end # Public: The name of this section, an alias of the section title alias :name :title # Public: Generate a String id for this section. # # The generated id is prefixed with value of the 'idprefix' attribute, which # is an underscore by default. # # Section id synthesis can be disabled by undefining the 'sectids' attribute. # # If the generated id is already in use in the document, a count is appended # until a unique id is found. # # Examples # # section = Section.new(parent) # section.title = "Foo" # section.generate_id # => "_foo" # # another_section = Section.new(parent) # another_section.title = "Foo" # another_section.generate_id # => "_foo_1" def generate_id if @document.attr? 'sectids' separator = @document.attr('idseparator', '_') base_id = @document.attr('idprefix', '_') + title.downcase.gsub(/&#[0-9]+;/, separator). gsub(/\W+/, separator).tr_s(separator, separator).chomp(separator) gen_id = base_id cnt = 2 while @document.references[:ids].has_key? gen_id gen_id = "#{base_id}#{separator}#{cnt}" cnt += 1 end @document.register(:ids, [gen_id, title]) gen_id else nil end end # Public: Get the rendered String content for this Section and all its child # Blocks. def render Debug.debug { "Now rendering section for #{self}" } @document.playback_attributes @attributes renderer.render('section', self) end # Public: Get the String section content by aggregating rendered section blocks. # # Examples # # section = Section.new # section << 'foo' # section << 'bar' # section << 'baz' # section.content # "<div class=\"paragraph\"><p>foo</p></div>\n<div class=\"paragraph\"><p>bar</p></div>\n<div class=\"paragraph\"><p>baz</p></div>" def content @blocks.map {|b| b.render }.join end # Public: Get the section number for the current Section # # The section number is a unique, dot separated String # where each entry represents one level of nesting and # the value of each entry is the 1-based index of # the Section amongst its sibling Sections # # delimiter - the delimiter to separate the number for each level # append - the String to append at the end of the section number # or Boolean to indicate the delimiter should not be # appended to the final level # (default: nil) # # Examples # # sect1 = Section.new(document) # sect1.level = 1 # sect1_1 = Section.new(sect1) # sect1_1.level = 2 # sect1_2 = Section.new(sect1) # sect1_2.level = 2 # sect1 << sect1_1 # sect1 << sect1_2 # sect1_1_1 = Section.new(sect1_1) # sect1_1_1.level = 3 # sect1_1 << sect1_1_1 # # sect1.sectnum # # => 1. # # sect1_1.sectnum # # => 1.1. # # sect1_2.sectnum # # => 1.2. # # sect1_1_1.sectnum # # => 1.1.1. # # sect1_1_1.sectnum(',', false) # # => 1,1,1 # # Returns the section number as a String def sectnum(delimiter = '.', append = nil) append ||= (append == false ? '' : delimiter) if !@level.nil? && @level > 1 && @parent.is_a?(Section) "#{@parent.sectnum(delimiter)}#{@index + 1}#{append}" else "#{@index + 1}#{append}" end end def to_s if @title if @level && @index %[#{super.to_s} - #{sectnum} #@title [blocks:#{@blocks.size}]] else %[#{super.to_s} - #@title [blocks:#{@blocks.size}]] end else super.to_s end end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/backends/docbook45.rb
module Asciidoctor class BaseTemplate def tag(name, key) type = key.is_a?(Symbol) ? :attr : :var key = key.to_s if type == :attr # example: <% if attr? 'foo' %><bar><%= attr 'foo' %></bar><% end %> %(<% if attr? '#{key}' %><#{name}><%= attr '#{key}' %></#{name}><% end %>) else # example: <% unless foo.to_s.empty? %><bar><%= foo %></bar><% end %> %(<% unless #{key}.to_s.empty? %><#{name}><%= #{key} %></#{name}><% end %>) end end def title_tag(optional = true) if optional %q{<%= title? ? "<title>#{title}</title>" : '' %>} else %q{<title><%= title %></title>} end end def common_attrs(id, role, reftext) %(#{id && " id=\"#{id}\""}#{role && " role=\"#{role}\""}#{reftext && " xreflabel=\"#{reftext}\""}) end def common_attrs_erb %q{<%= template.common_attrs(@id, (attr 'role'), (attr 'reftext')) %>} end end module DocBook45 class DocumentTemplate < BaseTemplate def docinfo <<-EOF <% if has_header? && !notitle %> #{tag 'title', '@header.title'} <% end %> <% if attr? :revdate %> <date><%= attr :revdate %></date> <% else %> <date><%= attr :docdate %></date> <% end %> <% if has_header? %> <% if attr? :author %> <author> #{tag 'firstname', :firstname} #{tag 'othername', :middlename} #{tag 'surname', :lastname} #{tag 'email', :email} </author> #{tag 'authorinitials', :authorinitials} <% end %> <% if (attr? :revnumber) || (attr? :revremark) %> <revhistory> #{tag 'revision', :revnumber} #{tag 'date', :revdate} #{tag 'authorinitials', :authorinitials} #{tag 'revremark', :revremark} </revhistory> <% end %> <% end %> EOF end def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE <%= doctype %> PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"> <% if attr? :toc %><?asciidoc-toc?><% end %> <% if attr? :numbered %><?asciidoc-numbered?><% end %> <% if doctype == 'book' %> <book<% unless attr? :nolang %> lang="<%= attr :lang, 'en' %>"<% end %>> <bookinfo> #{docinfo} </bookinfo> <%= content %> </book> <% else %> <article<% unless attr? :nolang %> lang="<%= attr :lang, 'en' %>"<% end %>> <articleinfo> #{docinfo} </articleinfo> <%= content %> </article> <% end %> EOF end end class EmbeddedTemplate < BaseTemplate def template :content end end class BlockPreambleTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><% if @document.doctype == 'book' %> <preface#{common_attrs_erb}> <title><%= title %></title> <%= content %> </preface> <% else %> <%= content %> <% end %> EOF end end class SectionTemplate < BaseTemplate def section(sec) if sec.special tag = sec.level <= 1 ? sec.sectname : 'section' else tag = sec.document.doctype == 'book' && sec.level <= 1 ? 'chapter' : 'section' end %(<#{tag}#{common_attrs(sec.id, (sec.attr 'role'), (sec.attr 'reftext'))}> #{sec.title? ? "<title>#{sec.title}</title>" : nil} #{sec.content} </#{tag}>) end def template # hot piece of code, optimized for speed @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><%= template.section(self) %> EOF end end class BlockFloatingTitleTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><bridgehead#{common_attrs_erb} renderas="sect<%= @level %>"><%= title %></bridgehead> EOS end end class BlockParagraphTemplate < BaseTemplate def paragraph(id, role, reftext, title, content) if title %(<formalpara#{common_attrs(id, role, reftext)}> <title>#{title}</title> <para>#{content}</para> </formalpara>) else %(<simpara#{common_attrs(id, role, reftext)}>#{content}</simpara>) end end def template # very hot piece of code, optimized for speed @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><%= template.paragraph(@id, (attr 'role'), (attr 'reftext'), title? ? title : nil, content) %> EOF end end class BlockAdmonitionTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><<%= attr :name %>#{common_attrs_erb}> #{title_tag} <% if blocks? %> <%= content %> <% else %> <simpara><%= content.chomp %></simpara> <% end %> </<%= attr :name %>> EOF end end class BlockUlistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><% if attr? :style, 'bibliography' %> <bibliodiv#{common_attrs_erb}> #{title_tag} <% content.each do |li| %> <bibliomixed> <bibliomisc><%= li.text %></bibliomisc> <% if li.blocks? %> <%= li.content %> <% end %> </bibliomixed> <% end %> </bibliodiv> <% else %> <itemizedlist#{common_attrs_erb}> #{title_tag} <% content.each do |li| %> <listitem> <simpara><%= li.text %></simpara> <% if li.blocks? %> <%= li.content %> <% end %> </listitem> <% end %> </itemizedlist> <% end %> EOF end end class BlockOlistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><orderedlist#{common_attrs_erb}#{attribute('numeration', :style)}> #{title_tag} <% content.each do |li| %> <listitem> <simpara><%= li.text %></simpara> <% if li.blocks? %> <%= li.content %> <% end %> </listitem> <% end %> </orderedlist> EOF end end class BlockColistTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><calloutlist#{common_attrs_erb}> #{title_tag} <% content.each do |li| %> <callout arearefs="<%= li.attr :coids %>"> <para><%= li.text %></para> <% if li.blocks? %> <%= li.content %> <% end %> </callout> <% end %> </calloutlist> EOF end end class BlockDlistTemplate < BaseTemplate LIST_TAGS = { 'labeled' => { :list => 'variablelist', :entry => 'varlistentry', :term => 'term', :item => 'listitem' }, 'qanda' => { :list => 'qandaset', :entry => 'qandaentry', :term => 'question', :item => 'answer' }, 'glossary' => { :list => nil, :entry => 'glossentry', :term => 'glossterm', :item => 'glossdef' } } def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><% tags = (template.class::LIST_TAGS[attr :style] || template.class::LIST_TAGS['labeled']) %> <% if tags[:list] %><<%= tags[:list] %>#{common_attrs_erb}><% end %> #{title_tag} <% content.each do |dt, dd| %> <<%= tags[:entry] %>> <<%= tags[:term] %>> <%= dt.text %> </<%= tags[:term] %>> <% unless dd.nil? %> <<%= tags[:item] %>> <% if dd.text? %> <simpara><%= dd.text %></simpara> <% end %> <% if dd.blocks? %> <%= dd.content %> <% end %> </<%= tags[:item] %>> <% end %> </<%= tags[:entry] %>> <% end %> <% if tags[:list] %></<%= tags[:list] %>><% end %> EOF end end class BlockOpenTemplate < BaseTemplate def template :content end end class BlockListingTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><% if !title? %> <% if attr? :style, 'source' %> <programlisting#{common_attrs_erb}#{attribute('language', :language)} linenumbering="<%= (attr? :linenums) ? 'numbered' : 'unnumbered' %>"><%= template.preserve_endlines(content, self) %></programlisting> <% else %> <screen#{common_attrs_erb}><%= template.preserve_endlines(content, self) %></screen> <% end %> <% else %> <formalpara#{common_attrs_erb}> #{title_tag false} <para> <% if attr :style, 'source' %> <programlisting language="<%= attr :language %>" linenumbering="<%= (attr? :linenums) ? 'numbered' : 'unnumbered' %>"><%= template.preserve_endlines(content, self) %></programlisting> <% else %> <screen><%= template.preserve_endlines(content, self) %></screen> <% end %> </para> </formalpara> <% end %> EOF end end class BlockLiteralTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><% if !title? %> <literallayout#{common_attrs_erb} class="monospaced"><%= template.preserve_endlines(content, self) %></literallayout> <% else %> <formalpara#{common_attrs_erb}> #{title_tag false} <para> <literallayout class="monospaced"><%= template.preserve_endlines(content, self) %></literallayout> </para> </formalpara> <% end %> EOF end end class BlockExampleTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><example#{common_attrs_erb}> #{title_tag} <%= content %> </example> EOF end end class BlockSidebarTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><sidebar#{common_attrs_erb}> #{title_tag} <%= content %> </sidebar> EOF end end class BlockQuoteTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><blockquote#{common_attrs_erb}> #{title_tag} <% if (attr? :attribution) || (attr? :citetitle) %> <attribution> <% if attr? :attribution %> <%= attr(:attribution) %> <% end %> #{tag 'citetitle', :citetitle} </attribution> <% end %> <% if !@buffer.nil? %> <simpara><%= content %></simpara> <% else %> <%= content %> <% end %> </blockquote> EOF end end class BlockVerseTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><blockquote#{common_attrs_erb}> #{title_tag} <% if (attr? :attribution) || (attr? :citetitle) %> <attribution> <% if attr? :attribution %> <%= attr(:attribution) %> <% end %> #{tag 'citetitle', :citetitle} </attribution> <% end %> <literallayout><%= content %></literallayout> </blockquote> EOF end end class BlockPassTemplate < BaseTemplate def template :content end end class BlockTableTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><<%= title? ? 'table' : 'informaltable'%>#{common_attrs_erb} frame="<%= attr :frame, 'all'%>" rowsep="<%= ['none', 'cols'].include?(attr :grid) ? 0 : 1 %>" colsep="<%= ['none', 'rows'].include?(attr :grid) ? 0 : 1 %>"> #{title_tag} <% if attr? :width %> <?dbhtml table-width="<%= attr :width %>"?> <?dbfo table-width="<%= attr :width %>"?> <?dblatex table-width="<%= attr :width %>"?> <% end %> <tgroup cols="<%= attr :colcount %>"> <% @columns.each do |col| %> <colspec colname="col_<%= col.attr :colnumber %>" colwidth="<%= col.attr((attr? :width) ? :colabswidth : :colpcwidth) %>*"/> <% end %> <% [:head, :foot, :body].select {|tblsec| !rows[tblsec].empty? }.each do |tblsec| %> <t<%= tblsec %>> <% @rows[tblsec].each do |row| %> <row> <% row.each do |cell| %> <entry#{attribute('align', 'cell.attr :halign')}#{attribute('valign', 'cell.attr :valign')}<% if cell.colspan %> namest="col_<%= cell.column.attr :colnumber %>" nameend="col_<%= (cell.column.attr :colnumber) + cell.colspan - 1 %>"<% end %><% if cell.rowspan %> morerows="<%= cell.rowspan - 1 %>"<% end %>><% if tblsec == :head %><%= cell.text %><% else %><% case cell.attr(:style) when :asciidoc %><%= cell.content %><% when :verse %><literallayout><%= template.preserve_endlines(cell.text, self) %></literallayout><% when :literal %><literallayout class="monospaced"><%= template.preserve_endlines(cell.text, self) %></literallayout><% when :header %><% cell.content.each do |text| %><simpara><emphasis role="strong"><%= text %></emphasis></simpara><% end %><% else %><% cell.content.each do |text| %><simpara><%= text %></simpara><% end %><% %><% end %><% end %></entry> <% end %> </row> <% end %> </t<%= tblsec %>> <% end %> </tgroup> </<%= title? ? 'table' : 'informaltable'%>> EOS end end class BlockImageTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><%#encoding:UTF-8%><figure#{common_attrs_erb}> #{title_tag} <mediaobject> <imageobject> <imagedata fileref="<%= image_uri(attr :target) %>"#{attribute('contentwidth', :width)}#{attribute('contentdepth', :height)}/> </imageobject> <textobject><phrase><%= attr :alt %></phrase></textobject> </mediaobject> </figure> EOF end end class BlockRulerTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><simpara><?asciidoc-hr?></simpara> EOF end end class BlockPageBreakTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><simpara><?asciidoc-pagebreak?></simpara> EOF end end class InlineBreakTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><%= @text %><?asciidoc-br?> EOF end end class InlineQuotedTemplate < BaseTemplate QUOTED_TAGS = { :emphasis => ['<emphasis>', '</emphasis>'], :strong => ['<emphasis role="strong">', '</emphasis>'], :monospaced => ['<literal>', '</literal>'], :superscript => ['<superscript>', '</superscript>'], :subscript => ['<subscript>', '</subscript>'], :double => ['&#8220;', '&#8221;'], :single => ['&#8216;', '&#8217;'] #:none => ['', ''] } def quote(text, type, role) start_tag, end_tag = QUOTED_TAGS[type] || ['', ''] if role "#{start_tag}<phrase role=\"#{role}\">#{text}</phrase>#{end_tag}" else "#{start_tag}#{text}#{end_tag}" end end def template # very hot piece of code, optimized for speed @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><%= template.quote(@text, @type, attr('role')) %> EOF end end class InlineAnchorTemplate < BaseTemplate def anchor(target, text, type) case type when :ref %(<anchor id="#{target}" xreflabel="#{text}"/>) when :xref text.nil? ? %(<xref linkend="#{target}"/>) : %(<link linkend="#{target}">#{text}</link>) when :link %(<ulink url="#{target}">#{text}</ulink>) when :bibref %(<anchor id="#{target}" xreflabel="[#{target}]"/>[#{target}]) end end def template # hot piece of code, optimized for speed @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><%= template.anchor(@target, @text, @type) %> EOS end end class InlineImageTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><inlinemediaobject> <imageobject> <imagedata fileref="<%= image_uri(@target) %>"#{attribute('width', :width)}#{attribute('depth', :height)}/> </imageobject> <textobject><phrase><%= attr :alt %></phrase></textobject> </inlinemediaobject> EOF end end class InlineFootnoteTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% if @type == :xref %><footnoteref linkend="<%= @target %>"/><% else %><footnote#{id}><simpara><%= @text %></simpara></footnote><% end %> EOS end end class InlineCalloutTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOF <%#encoding:UTF-8%><co#{id}/> EOF end end class InlineIndextermTemplate < BaseTemplate def template @template ||= @eruby.new <<-EOS <%#encoding:UTF-8%><% if @type == :visible %><indexterm><primary><%= @text %></primary></indexterm><%= @text %><% else %><% terms = (attr :terms); numterms = terms.size %><% if numterms > 2 %><indexterm> <primary><%= terms[0] %></primary><secondary><%= terms[1] %></secondary><tertiary><%= terms[2] %></tertiary> </indexterm> <% end %><% if numterms > 1 %><indexterm> <primary><%= terms[numterms - 2] %></primary><secondary><%= terms[numterms - 1] %></secondary> </indexterm> <% end %><indexterm> <primary><%= terms[numterms - 1] %></primary> </indexterm><% end %> EOS end end end # module DocBook45 end # module Asciidoctor
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/cli/invoker.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin module Asciidoctor module Cli # Public Invocation class for starting Asciidoctor via CLI class Invoker attr_reader :options attr_reader :document attr_reader :code attr_reader :timings def initialize(*options) @document = nil @out = nil @err = nil @code = 0 @timings = {} options = options.flatten if !options.empty? && options.first.is_a?(Cli::Options) @options = options.first elsif options.first.is_a? Hash @options = Cli::Options.new(options) else @options = Cli::Options.parse!(options) # hmmm if @options.is_a?(Integer) @code = @options @options = nil end end end def invoke! return if @options.nil? begin @timings = {} infile = @options[:input_file] outfile = @options[:output_file] if infile == '-' # allow use of block to supply stdin, particularly useful for tests input = block_given? ? yield : STDIN else input = File.new(infile) end start = Time.now @document = Asciidoctor.load(input, @options) timings[:parse] = Time.now - start start = Time.now output = @document.render timings[:render] = Time.now - start if @options[:verbose] puts "Time to read and parse source: #{timings[:parse]}" puts "Time to render document: #{timings[:render]}" puts "Total time to read, parse and render: #{timings.reduce(0) {|sum, (_, v)| sum += v}}" end if outfile == '/dev/null' # output nothing elsif outfile == '-' || (infile == '-' && (outfile.nil? || outfile.empty?)) (@out || $stdout).puts output else if outfile.nil? || outfile.empty? if @options[:destination_dir] destination_dir = File.expand_path(@options[:destination_dir]) else destination_dir = @document.base_dir end outfile = File.join(destination_dir, "#{@document.attributes['docname']}#{@document.attributes['outfilesuffix']}") else outfile = @document.normalize_asset_path outfile end # this assignment is primarily for testing or other post analysis @document.attributes['outfile'] = outfile @document.attributes['outdir'] = File.dirname(outfile) File.open(outfile, 'w') {|file| file.write output } end rescue Exception => e raise e if @options[:trace] || SystemExit === e err = (@err || $stderr) err.print "#{e.class}: " if e.class != RuntimeError err.puts e.message err.puts ' Use --trace for backtrace' @code = 1 end end def redirect_streams(out, err = nil) @out = out @err = err end def read_output !@out.nil? ? @out.string : '' end def read_error !@err.nil? ? @err.string : '' end def reset_streams @out = nil @err = nil end end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/blocks_test.rb
require 'test_helper' require 'pathname' context "Blocks" do context 'Line Breaks' do test "ruler" do output = render_string("'''") assert_xpath '//*[@id="content"]/hr', output, 1 assert_xpath '//*[@id="content"]/*', output, 1 end test "ruler between blocks" do output = render_string("Block above\n\n'''\n\nBlock below") assert_xpath '//*[@id="content"]/hr', output, 1 assert_xpath '//*[@id="content"]/hr/preceding-sibling::*', output, 1 assert_xpath '//*[@id="content"]/hr/following-sibling::*', output, 1 end test "page break" do output = render_embedded_string("page 1\n\n<<<\n\npage 2") assert_xpath '/*[@style="page-break-after: always"]', output, 1 assert_xpath '/*[@style="page-break-after: always"]/preceding-sibling::div/p[text()="page 1"]', output, 1 assert_xpath '/*[@style="page-break-after: always"]/following-sibling::div/p[text()="page 2"]', output, 1 end end context 'Comments' do test 'line comment between paragraphs offset by blank lines' do input = <<-EOS first paragraph // line comment second paragraph EOS output = render_embedded_string input assert_no_match(/line comment/, output) assert_xpath '//p', output, 2 end test 'adjacent line comment between paragraphs' do input = <<-EOS first line // line comment second line EOS output = render_embedded_string input assert_no_match(/line comment/, output) assert_xpath '//p', output, 1 assert_xpath "//p[1][text()='first line\nsecond line']", output, 1 end test 'comment block between paragraphs offset by blank lines' do input = <<-EOS first paragraph //// block comment //// second paragraph EOS output = render_embedded_string input assert_no_match(/block comment/, output) assert_xpath '//p', output, 2 end test 'adjacent comment block between paragraphs' do input = <<-EOS first paragraph //// block comment //// second paragraph EOS output = render_embedded_string input assert_no_match(/block comment/, output) assert_xpath '//p', output, 2 end test "can render with block comment at end of document with trailing endlines" do input = <<-EOS paragraph //// block comment //// EOS output = render_embedded_string input assert_no_match(/block comment/, output) end test "trailing endlines after block comment at end of document does not create paragraph" do input = <<-EOS paragraph //// block comment //// EOS d = document_from_string input assert_equal 1, d.blocks.size assert_xpath '//p', d.render, 1 end test 'line starting with three slashes should not be line comment' do input = <<-EOS /// not a line comment EOS output = render_embedded_string input assert !output.strip.empty?, "Line should be emitted => #{input.rstrip}" end end context "Example Blocks" do test "can render example block" do input = <<-EOS ==== This is an example of an example block. How crazy is that? ==== EOS output = render_string input assert_xpath '//*[@class="exampleblock"]//p', output, 2 end test "assigns sequential numbered caption to example block with title" do input = <<-EOS .Writing Docs with AsciiDoc ==== Here's how you write AsciiDoc. You just write. ==== .Writing Docs with DocBook ==== Here's how you write DocBook. You futz with XML. ==== EOS doc = document_from_string input output = doc.render assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Example 1. Writing Docs with AsciiDoc"]', output, 1 assert_xpath '(//*[@class="exampleblock"])[2]/*[@class="title"][text()="Example 2. Writing Docs with DocBook"]', output, 1 assert_equal 2, doc.attributes['example-number'] end test "assigns sequential character caption to example block with title" do input = <<-EOS :example-number: @ .Writing Docs with AsciiDoc ==== Here's how you write AsciiDoc. You just write. ==== .Writing Docs with DocBook ==== Here's how you write DocBook. You futz with XML. ==== EOS doc = document_from_string input output = doc.render assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Example A. Writing Docs with AsciiDoc"]', output, 1 assert_xpath '(//*[@class="exampleblock"])[2]/*[@class="title"][text()="Example B. Writing Docs with DocBook"]', output, 1 assert_equal 'B', doc.attributes['example-number'] end test "explicit caption is used if provided" do input = <<-EOS [caption="Look! "] .Writing Docs with AsciiDoc ==== Here's how you write AsciiDoc. You just write. ==== EOS doc = document_from_string input output = doc.render assert_xpath '(//*[@class="exampleblock"])[1]/*[@class="title"][text()="Look! Writing Docs with AsciiDoc"]', output, 1 assert !doc.attributes.has_key?('example-number') end test 'automatic caption can be turned off and on and modified' do input = <<-EOS .first example ==== an example ==== :caption: .second example ==== another example ==== :caption!: :example-caption: Exhibit .third example ==== yet another example ==== EOS output = render_embedded_string input assert_xpath '/*[@class="exampleblock"]', output, 3 assert_xpath '(/*[@class="exampleblock"])[1]/*[@class="title"][starts-with(text(), "Example ")]', output, 1 assert_xpath '(/*[@class="exampleblock"])[2]/*[@class="title"][text()="second example"]', output, 1 assert_xpath '(/*[@class="exampleblock"])[3]/*[@class="title"][starts-with(text(), "Exhibit ")]', output, 1 end end context 'Admonition Blocks' do test 'caption block-level attribute should be used as caption' do input = <<-EOS :tip-caption: Pro Tip [caption="Pro Tip"] TIP: Override the caption of an admonition block using an attribute entry EOS output = render_embedded_string input assert_xpath '/*[@class="admonitionblock"]//*[@class="icon"]/*[@class="title"][text()="Pro Tip"]', output, 1 end test 'can override caption of admonition block using document attribute' do input = <<-EOS :tip-caption: Pro Tip TIP: Override the caption of an admonition block using an attribute entry EOS output = render_embedded_string input assert_xpath '/*[@class="admonitionblock"]//*[@class="icon"]/*[@class="title"][text()="Pro Tip"]', output, 1 end test 'blank caption document attribute should not blank admonition block caption' do input = <<-EOS :caption: TIP: Override the caption of an admonition block using an attribute entry EOS output = render_embedded_string input assert_xpath '/*[@class="admonitionblock"]//*[@class="icon"]/*[@class="title"][text()="Tip"]', output, 1 end end context "Preformatted Blocks" do test 'should separate adjacent paragraphs and listing into blocks' do input = <<-EOS paragraph 1 ---- listing content ---- paragraph 2 EOS output = render_embedded_string input assert_xpath '/*[@class="paragraph"]/p', output, 2 assert_xpath '/*[@class="listingblock"]', output, 1 assert_xpath '(/*[@class="paragraph"]/following-sibling::*)[1][@class="listingblock"]', output, 1 end test "should preserve endlines in literal block" do input = <<-EOS .... line one line two line three .... EOS [true, false].each {|compact| output = render_string input, :compact => compact assert_xpath '//pre', output, 1 assert_xpath '//pre/text()', output, 1 text = xmlnodes_at_xpath('//pre/text()', output, 1).text lines = text.lines.entries assert_equal 5, lines.size expected = "line one\n\nline two\n\nline three".lines.entries assert_equal expected, lines blank_lines = output.scan(/\n[[:blank:]]*\n/).size if compact assert_equal 2, blank_lines else assert blank_lines > 2 end } end test "should preserve endlines in listing block" do input = <<-EOS [source] ---- line one line two line three ---- EOS [true, false].each {|compact| output = render_string input, :compact => compact assert_xpath '//pre/code', output, 1 assert_xpath '//pre/code/text()', output, 1 text = xmlnodes_at_xpath('//pre/code/text()', output, 1).text lines = text.lines.entries assert_equal 5, lines.size expected = "line one\n\nline two\n\nline three".lines.entries assert_equal expected, lines blank_lines = output.scan(/\n[[:blank:]]*\n/).size if compact assert_equal 2, blank_lines else assert blank_lines > 2 end } end test "should preserve endlines in verse block" do input = <<-EOS [verse] ____ line one line two line three ____ EOS [true, false].each {|compact| output = render_string input, :compact => compact assert_xpath '//*[@class="verseblock"]/pre', output, 1 assert_xpath '//*[@class="verseblock"]/pre/text()', output, 1 text = xmlnodes_at_xpath('//*[@class="verseblock"]/pre/text()', output, 1).text lines = text.lines.entries assert_equal 5, lines.size expected = "line one\n\nline two\n\nline three".lines.entries assert_equal expected, lines blank_lines = output.scan(/\n[[:blank:]]*\n/).size if compact assert_equal 2, blank_lines else assert blank_lines > 2 end } end test 'should process block with CRLF endlines' do input = <<-EOS [source]\r ----\r source line 1\r source line 2\r ----\r EOS output = render_embedded_string input assert_no_match(/\[source\]/, output) assert_xpath '/*[@class="listingblock"]//pre', output, 1 assert_xpath '/*[@class="listingblock"]//pre/code', output, 1 assert_xpath %(/*[@class="listingblock"]//pre/code[text()="source line 1\nsource line 2"]), output, 1 end end context "Open Blocks" do test "can render open block" do input = <<-EOS -- This is an open block. It can span multiple lines. -- EOS output = render_string input assert_xpath '//*[@class="openblock"]//p', output, 2 end test "open block can contain another block" do input = <<-EOS -- This is an open block. It can span multiple lines. ____ It can hold great quotes like this one. ____ -- EOS output = render_string input assert_xpath '//*[@class="openblock"]//p', output, 3 assert_xpath '//*[@class="openblock"]//*[@class="quoteblock"]', output, 1 end end context 'Passthrough Blocks' do test 'can parse a passthrough block' do input = <<-EOS ++++ This is a passthrough block. ++++ EOS block = block_from_string input assert !block.nil? assert_equal 1, block.buffer.size assert_equal 'This is a passthrough block.', block.buffer.first end test 'performs passthrough subs on a passthrough block' do input = <<-EOS :type: passthrough ++++ This is a '{type}' block. http://asciidoc.org ++++ EOS expected = %(This is a 'passthrough' block.\n<a href="http://asciidoc.org">http://asciidoc.org</a>) output = render_embedded_string input assert_equal expected, output.strip end test 'passthrough block honors explicit subs list' do input = <<-EOS :type: passthrough [subs="attributes, quotes"] ++++ This is a '{type}' block. http://asciidoc.org ++++ EOS expected = %(This is a <em>passthrough</em> block.\nhttp://asciidoc.org) output = render_embedded_string input assert_equal expected, output.strip end end context 'Metadata' do test 'block title above section gets carried over to first block in section' do input = <<-EOS .Title == Section paragraph EOS output = render_string input assert_xpath '//*[@class="paragraph"]', output, 1 assert_xpath '//*[@class="paragraph"]/*[@class="title"][text() = "Title"]', output, 1 assert_xpath '//*[@class="paragraph"]/p[text() = "paragraph"]', output, 1 end test 'block title above document title gets carried over to preamble' do input = <<-EOS .Block title = Document Title preamble EOS output = render_string input assert_xpath '//*[@id="preamble"]//*[@class="paragraph"]/*[@class="title"][text()="Block title"]', output, 1 end test 'block title above document title gets carried over to first block in first section if no preamble' do input = <<-EOS .Block title = Document Title == First Section paragraph EOS output = render_string input assert_xpath '//*[@class="sect1"]//*[@class="paragraph"]/*[@class="title"][text() = "Block title"]', output, 1 end end context "Images" do test "can render block image with alt text" do input = <<-EOS image::images/tiger.png[Tiger] EOS output = render_string input assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1 end test "can render block image with auto-generated alt text" do input = <<-EOS image::images/tiger.png[] EOS output = render_string input assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="tiger"]', output, 1 end test "can render block image with alt text and height and width" do input = <<-EOS image::images/tiger.png[Tiger, 200, 300] EOS output = render_string input assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"][@width="200"][@height="300"]', output, 1 end test "can render block image with link" do input = <<-EOS image::images/tiger.png[Tiger, link='http://en.wikipedia.org/wiki/Tiger'] EOS output = render_string input assert_xpath '//*[@class="imageblock"]//a[@class="image"][@href="http://en.wikipedia.org/wiki/Tiger"]/img[@src="images/tiger.png"][@alt="Tiger"]', output, 1 end test "can render block image with caption" do input = <<-EOS .The AsciiDoc Tiger image::images/tiger.png[Tiger] EOS doc = document_from_string input output = doc.render assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1 assert_xpath '//*[@class="imageblock"]/*[@class="title"][text() = "Figure 1. The AsciiDoc Tiger"]', output, 1 assert_equal 1, doc.attributes['figure-number'] end test 'should pass through image that is a uri reference' do input = <<-EOS :imagesdir: images image::http://asciidoc.org/images/tiger.png[Tiger] EOS output = render_string input assert_xpath '//*[@class="imageblock"]//img[@src="http://asciidoc.org/images/tiger.png"][@alt="Tiger"]', output, 1 end test 'can resolve image relative to imagesdir' do input = <<-EOS :imagesdir: images image::tiger.png[Tiger] EOS output = render_string input assert_xpath '//*[@class="imageblock"]//img[@src="images/tiger.png"][@alt="Tiger"]', output, 1 end test 'embeds base64-encoded data uri for image when data-uri attribute is set' do input = <<-EOS :data-uri: :imagesdir: fixtures image::dot.gif[Dot] EOS doc = document_from_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'docdir' => File.dirname(__FILE__)} assert_equal 'fixtures', doc.attributes['imagesdir'] output = doc.render assert_xpath '//*[@class="imageblock"]//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1 end # this test will cause a warning to be printed to the console (until we have a message facility) test 'cleans reference to ancestor directories before reading image if safe mode level is at least SAFE' do input = <<-EOS :data-uri: :imagesdir: ../fixtures image::dot.gif[Dot] EOS doc = document_from_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'docdir' => File.dirname(__FILE__)} assert_equal '../fixtures', doc.attributes['imagesdir'] output = doc.render assert_xpath '//*[@class="imageblock"]//img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Dot"]', output, 1 end end context 'Admonition icons' do test 'can resolve icon relative to default iconsdir' do input = <<-EOS :icons: [TIP] You can use icons for admonitions by setting the 'icons' attribute. EOS output = render_string input, :safe => Asciidoctor::SafeMode::SERVER assert_xpath '//*[@class="admonitionblock"]//*[@class="icon"]/img[@src="images/icons/tip.png"][@alt="Tip"]', output, 1 end test 'can resolve icon relative to custom iconsdir' do input = <<-EOS :icons: :iconsdir: icons [TIP] You can use icons for admonitions by setting the 'icons' attribute. EOS output = render_string input, :safe => Asciidoctor::SafeMode::SERVER assert_xpath '//*[@class="admonitionblock"]//*[@class="icon"]/img[@src="icons/tip.png"][@alt="Tip"]', output, 1 end test 'embeds base64-encoded data uri of icon when data-uri attribute is set and safe mode level is less than SECURE' do input = <<-EOS :icons: :iconsdir: fixtures :icontype: gif :data-uri: [TIP] You can use icons for admonitions by setting the 'icons' attribute. EOS output = render_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'docdir' => File.dirname(__FILE__)} assert_xpath '//*[@class="admonitionblock"]//*[@class="icon"]/img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Tip"]', output, 1 end test 'does not embed base64-encoded data uri of icon when safe mode level is SECURE or greater' do input = <<-EOS :icons: :iconsdir: fixtures :icontype: gif :data-uri: [TIP] You can use icons for admonitions by setting the 'icons' attribute. EOS output = render_string input, :attributes => {'icons' => ''} assert_xpath '//*[@class="admonitionblock"]//*[@class="icon"]/img[@src="fixtures/tip.gif"][@alt="Tip"]', output, 1 end test 'cleans reference to ancestor directories before reading icon if safe mode level is at least SAFE' do input = <<-EOS :icons: :iconsdir: ../fixtures :icontype: gif :data-uri: [TIP] You can use icons for admonitions by setting the 'icons' attribute. EOS output = render_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'docdir' => File.dirname(__FILE__)} assert_xpath '//*[@class="admonitionblock"]//*[@class="icon"]/img[@src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="][@alt="Tip"]', output, 1 end end context 'Image paths' do test 'restricts access to ancestor directories when safe mode level is at least SAFE' do input = <<-EOS image::asciidoctor.png[Asciidoctor] EOS basedir = File.expand_path File.dirname(__FILE__) block = block_from_string input, :attributes => {'docdir' => basedir} doc = block.document assert doc.safe >= Asciidoctor::SafeMode::SAFE assert_equal File.join(basedir, 'images'), block.normalize_asset_path('images') assert_equal File.join(basedir, 'etc/images'), block.normalize_asset_path("#{disk_root}etc/images") assert_equal File.join(basedir, 'images'), block.normalize_asset_path('../../images') end test 'does not restrict access to ancestor directories when safe mode is disabled' do input = <<-EOS image::asciidoctor.png[Asciidoctor] EOS basedir = File.expand_path File.dirname(__FILE__) block = block_from_string input, :safe => Asciidoctor::SafeMode::UNSAFE, :attributes => {'docdir' => basedir} doc = block.document assert doc.safe == Asciidoctor::SafeMode::UNSAFE assert_equal File.join(basedir, 'images'), block.normalize_asset_path('images') absolute_path = "#{disk_root}etc/images" assert_equal absolute_path, block.normalize_asset_path(absolute_path) assert_equal File.expand_path(File.join(basedir, '../../images')), block.normalize_asset_path('../../images') end end context 'Source code' do test 'should support fenced code block using backticks' do input = <<-EOS ``` puts "Hello, World!" ``` EOS output = render_embedded_string input assert_css '.listingblock', output, 1 assert_css '.listingblock pre code', output, 1 assert_css '.listingblock pre code:not([class])', output, 1 end test 'should support fenced code block using tildes' do input = <<-EOS ~~~ puts "Hello, World!" ~~~ EOS output = render_embedded_string input assert_css '.listingblock', output, 1 assert_css '.listingblock pre code', output, 1 assert_css '.listingblock pre code:not([class])', output, 1 end test 'should support fenced code blocks with languages' do input = <<-EOS ```ruby puts "Hello, World!" ``` ~~~ javascript alert("Hello, World!") ~~~ EOS output = render_embedded_string input assert_css '.listingblock', output, 2 assert_css '.listingblock pre code.ruby', output, 1 assert_css '.listingblock pre code.javascript', output, 1 end test 'should highlight source if source-highlighter attribute is coderay' do input = <<-EOS :source-highlighter: coderay [source, ruby] ---- require 'coderay' html = CodeRay.scan("puts 'Hello, world!'", :ruby).div(:line_numbers => :table) ---- EOS output = render_string input, :safe => Asciidoctor::SafeMode::SAFE assert_xpath '//pre[@class="highlight CodeRay"]/code[@class="ruby"]//span[@class = "constant"][text() = "CodeRay"]', output, 1 assert_match(/\.CodeRay \{/, output) end test 'should highlight source inline if source-highlighter attribute is coderay and coderay-css is style' do input = <<-EOS :source-highlighter: coderay :coderay-css: style [source, ruby] ---- require 'coderay' html = CodeRay.scan("puts 'Hello, world!'", :ruby).div(:line_numbers => :table) ---- EOS output = render_string input, :safe => Asciidoctor::SafeMode::SAFE assert_xpath '//pre[@class="highlight CodeRay"]/code[@class="ruby"]//span[@style = "color:#036;font-weight:bold"][text() = "CodeRay"]', output, 1 assert_no_match(/\.CodeRay \{/, output) end test 'should include remote highlight.js assets if source-highlighter attribute is highlightjs' do input = <<-EOS :source-highlighter: highlightjs [source, javascript] ---- <link rel="stylesheet" href="styles/default.css"> <script src="highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> ---- EOS output = render_string input, :safe => Asciidoctor::SafeMode::SAFE assert_match(/<link .*highlight\.js/, output) assert_match(/<script .*highlight\.js/, output) assert_match(/hljs.initHighlightingOnLoad/, output) end test 'document cannot turn on source highlighting if safe mode is at least SERVER' do input = <<-EOS :source-highlighter: coderay EOS doc = document_from_string input, :safe => Asciidoctor::SafeMode::SERVER assert doc.attributes['source-highlighter'].nil? end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/helpers.rb
<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/helpers.rb module Asciidoctor module Helpers # Internal: Prior to invoking Kernel#require, issues a warning urging a # manual require if running in a threaded environment. # # name - the String name of the library to require. # # returns false if the library is detected on the load path or the return # value of delegating to Kernel#require def self.require_library(name) if Thread.list.size > 1 main_script = "#{name}.rb" main_script_path_segment = "/#{name}.rb" if !$LOADED_FEATURES.detect {|p| p == main_script || p.end_with?(main_script_path_segment) }.nil? return false else warn "WARN: asciidoctor is autoloading '#{name}' in threaded environment. " + "The use of an explicit require '#{name}' statement is recommended." end end require name end # Public: A generic capture output routine to be used in templates #def self.capture_output(*args, &block) # Proc.new { block.call(*args) } #end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/errors.rb
<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/errors.rb # Base project exception module Asciidoctor class ProjectError < StandardError; end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/block.rb
module Asciidoctor # Public: Methods for managing blocks of Asciidoc content in a section. # # Examples # # block = Asciidoctor::Block.new(document, :paragraph, ["`This` is a <test>"]) # block.content # => ["<em>This</em> is a &lt;test&gt;"] class Block < AbstractBlock # Public: Create alias for context to be consistent w/ AsciiDoc alias :blockname :context # Public: Get/Set the original Array content for this section block. attr_accessor :buffer # Public: Get/Set the caption for this block attr_accessor :caption # Public: Initialize an Asciidoctor::Block object. # # parent - The parent Asciidoc Object. # context - The Symbol context name for the type of content. # buffer - The Array buffer of source data (default: nil). def initialize(parent, context, buffer = nil) super(parent, context) @buffer = buffer end # Public: Get the rendered String content for this Block. If the block # has child blocks, the content method should cause them to be # rendered and returned as content that can be included in the # parent block's template. def render Debug.debug { "Now rendering #{@context} block for #{self}" } @document.playback_attributes @attributes out = renderer.render("block_#{@context}", self) @document.callouts.next_list if @context == :colist out end def splain(parent_level = 0) parent_level += 1 Debug.puts_indented(parent_level, "Block id: #{id}") unless self.id.nil? Debug.puts_indented(parent_level, "Block title: #{title}") unless self.title.nil? Debug.puts_indented(parent_level, "Block caption: #{caption}") unless self.caption.nil? Debug.puts_indented(parent_level, "Block level: #{level}") unless self.level.nil? Debug.puts_indented(parent_level, "Block context: #{context}") unless self.context.nil? Debug.puts_indented(parent_level, "Blocks: #{@blocks.count}") if buffer.is_a? Enumerable buffer.each_with_index do |buf, i| Debug.puts_indented(parent_level, "v" * (60 - parent_level*2)) Debug.puts_indented(parent_level, "Buffer ##{i} is a #{buf.class}") Debug.puts_indented(parent_level, "Name is #{buf.title rescue 'n/a'}") if buf.respond_to? :splain buf.splain(parent_level) else Debug.puts_indented(parent_level, "Buffer: #{buf}") end Debug.puts_indented(parent_level, "^" * (60 - parent_level*2)) end else if buffer.respond_to? :splain buffer.splain(parent_level) else Debug.puts_indented(parent_level, "Buffer: #{@buffer}") end end @blocks.each_with_index do |block, i| Debug.puts_indented(parent_level, "v" * (60 - parent_level*2)) Debug.puts_indented(parent_level, "Block ##{i} is a #{block.class}") Debug.puts_indented(parent_level, "Name is #{block.title rescue 'n/a'}") block.splain(parent_level) if block.respond_to? :splain Debug.puts_indented(parent_level, "^" * (60 - parent_level*2)) end nil end # Public: Get an HTML-ified version of the source buffer, with special # Asciidoc characters and entities converted to their HTML equivalents. # # Examples # # doc = Asciidoctor::Document.new # block = Asciidoctor::Block.new(doc, :paragraph, # ['`This` is what happens when you <meet> a stranger in the <alps>!']) # block.content # => ["<em>This</em> is what happens when you &lt;meet&gt; a stranger in the &lt;alps&gt;!"] def content case @context when :preamble, :open, :example, :sidebar @blocks.map {|b| b.render }.join # lists get iterated in the template (for now) # list items recurse into this block when their text and content methods are called when :ulist, :olist, :dlist, :colist @buffer when :listing, :literal apply_literal_subs(@buffer) when :pass apply_passthrough_subs(@buffer) when :quote, :verse, :admonition if !@buffer.nil? apply_normal_subs(@buffer) else @blocks.map {|b| b.render }.join end else apply_normal_subs(@buffer) end end def to_s "#{super.to_s} - #@context [blocks:#{(@blocks || []).size}]" end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/sections_test.rb
<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/sections_test.rb # encoding: UTF-8 require 'test_helper' context 'Sections' do context 'Ids' do test 'synthetic id is generated by default' do sec = block_from_string('== Section One') assert_equal '_section_one', sec.id end test 'synthetic id replaces non-word characters with underscores' do sec = block_from_string("== We're back!") assert_equal '_we_re_back', sec.id end test 'synthetic id removes repeating underscores' do sec = block_from_string('== Section $ One') assert_equal '_section_one', sec.id end test 'synthetic id prefix can be customized' do sec = block_from_string(":idprefix: id_\n\n== Section One") assert_equal 'id_section_one', sec.id end test 'synthetic id prefix can be set to blank' do sec = block_from_string(":idprefix:\n\n== Section One") assert_equal 'section_one', sec.id end test 'synthetic id separator can be customized' do sec = block_from_string(":idseparator: -\n\n== Section One") assert_equal '_section-one', sec.id end test 'synthetic id separator can be set to blank' do sec = block_from_string(":idseparator:\n\n== Section One") assert_equal '_sectionone', sec.id end test 'synthetic ids can be disabled' do sec = block_from_string(":sectids!:\n\n== Section One\n") assert sec.id.nil? end test 'explicit id in anchor above section title overrides synthetic id' do sec = block_from_string("[[one]]\n== Section One") assert_equal 'one', sec.id end test 'explicit id can be defined using an inline anchor' do sec = block_from_string("== Section One [[one]] ==") assert_equal 'one', sec.id assert_equal 'Section One', sec.title end test 'title substitutions are applied before generating id' do sec = block_from_string("== Section{sp}One\n") assert_equal '_section_one', sec.id end test 'synthetic ids are unique' do input = <<-EOS == Some section text == Some section text EOS doc = document_from_string input assert_equal '_some_section', doc.blocks[0].id assert_equal '_some_section_2', doc.blocks[1].id end end context "document title (level 0)" do test "document title with multiline syntax" do title = "My Title" chars = "=" * title.length assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars) assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars + "\n") end test "document title with multiline syntax, give a char" do title = "My Title" chars = "=" * (title.length + 1) assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars) assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars + "\n") end test "document title with multiline syntax, take a char" do title = "My Title" chars = "=" * (title.length - 1) assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars) assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string(title + "\n" + chars + "\n") end test "not enough chars for a multiline document title" do title = "My Title" chars = "=" * (title.length - 2) assert_xpath '//h1', render_string(title + "\n" + chars), 0 assert_xpath '//h1', render_string(title + "\n" + chars + "\n"), 0 end test "too many chars for a multiline document title" do title = "My Title" chars = "=" * (title.length + 2) assert_xpath '//h1', render_string(title + "\n" + chars), 0 assert_xpath '//h1', render_string(title + "\n" + chars + "\n"), 0 end test "document title with multiline syntax cannot begin with a dot" do title = ".My Title" chars = "=" * title.length assert_xpath '//h1', render_string(title + "\n" + chars), 0 end test "document title with single-line syntax" do assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string("= My Title") end test "document title with symmetric syntax" do assert_xpath "//h1[not(@id)][text() = 'My Title']", render_string("= My Title =") end end context "level 1" do test "with multiline syntax" do assert_xpath "//h2[@id='_my_section'][text() = 'My Section']", render_string("My Section\n-----------") end test "heading title with multiline syntax cannot begin with a dot" do title = ".My Title" chars = "-" * title.length assert_xpath '//h2', render_string(title + "\n" + chars), 0 end test "with single-line syntax" do assert_xpath "//h2[@id='_my_title'][text() = 'My Title']", render_string("== My Title") end test "with single-line symmetric syntax" do assert_xpath "//h2[@id='_my_title'][text() = 'My Title']", render_string("== My Title ==") end test "with single-line non-matching symmetric syntax" do assert_xpath "//h2[@id='_my_title'][text() = 'My Title ===']", render_string("== My Title ===") end test "with non-word character" do assert_xpath "//h2[@id='_where_s_the_love'][text() = \"Where#{[8217].pack('U*')}s the love?\"]", render_string("== Where's the love?") end test "with sequential non-word characters" do assert_xpath "//h2[@id='_what_the_is_this'][text() = 'What the \#@$ is this?']", render_string('== What the #@$ is this?') end test "with trailing whitespace" do assert_xpath "//h2[@id='_my_title'][text() = 'My Title']", render_string("== My Title ") end test "with custom blank idprefix" do assert_xpath "//h2[@id='my_title'][text() = 'My Title']", render_string(":idprefix:\n\n== My Title ") end test "with custom non-blank idprefix" do assert_xpath "//h2[@id='ref_my_title'][text() = 'My Title']", render_string(":idprefix: ref_\n\n== My Title ") end test 'with multibyte characters' do input = <<-EOS == Asciidoctor in 中文 EOS output = render_string input assert_xpath '//h2[@id="_asciidoctor_in"][text()="Asciidoctor in 中文"]', output end end context "level 2" do test "with multiline syntax" do assert_xpath "//h3[@id='_my_section'][text() = 'My Section']", render_string(":fragment:\nMy Section\n~~~~~~~~~~~") end test "with single line syntax" do assert_xpath "//h3[@id='_my_title'][text() = 'My Title']", render_string(":fragment:\n=== My Title") end end context "level 3" do test "with multiline syntax" do assert_xpath "//h4[@id='_my_section'][text() = 'My Section']", render_string(":fragment:\nMy Section\n^^^^^^^^^^") end test "with single line syntax" do assert_xpath "//h4[@id='_my_title'][text() = 'My Title']", render_string(":fragment:\n==== My Title") end end context "level 4" do test "with multiline syntax" do assert_xpath "//h5[@id='_my_section'][text() = 'My Section']", render_string(":fragment:\nMy Section\n++++++++++") end test "with single line syntax" do assert_xpath "//h5[@id='_my_title'][text() = 'My Title']", render_string(":fragment:\n===== My Title") end end context 'Floating Title' do test 'should create floating title if style is float' do input = <<-EOS [float] = Plain Ol' Heading not in section EOS output = render_embedded_string input assert_xpath '/h1[@id="_plain_ol_heading"]', output, 1 assert_xpath '/h1[@class="float"]', output, 1 assert_xpath %(/h1[@class="float"][text()="Plain Ol' Heading"]), output, 1 assert_xpath '/h1/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '/h1/following-sibling::*[@class="paragraph"]/p', output, 1 assert_xpath '/h1/following-sibling::*[@class="paragraph"]/p[text()="not in section"]', output, 1 end test 'should create floating title if style is discrete' do input = <<-EOS [discrete] === Plain Ol' Heading not in section EOS output = render_embedded_string input assert_xpath '/h3', output, 1 assert_xpath '/h3[@id="_plain_ol_heading"]', output, 1 assert_xpath '/h3[@class="discrete"]', output, 1 assert_xpath %(/h3[@class="discrete"][text()="Plain Ol' Heading"]), output, 1 assert_xpath '/h3/following-sibling::*[@class="paragraph"]', output, 1 assert_xpath '/h3/following-sibling::*[@class="paragraph"]/p', output, 1 assert_xpath '/h3/following-sibling::*[@class="paragraph"]/p[text()="not in section"]', output, 1 end test 'floating title should be a block with context floating_title' do input = <<-EOS [float] === Plain Ol' Heading not in section EOS doc = document_from_string input floatingtitle = doc.blocks.first assert floatingtitle.is_a?(Asciidoctor::Block) assert !floatingtitle.is_a?(Asciidoctor::Section) assert_equal :floating_title, floatingtitle.context end test 'should not include floating title in toc' do input = <<-EOS :toc: == Section One [float] === Miss Independent == Section Two EOS output = render_string input assert_xpath '//*[@id="toc"]', output, 1 assert_xpath %(//*[@id="toc"]//a[contains(text(), " Section ")]), output, 2 assert_xpath %(//*[@id="toc"]//a[text()="Miss Independent"]), output, 0 end test 'should not set id on floating title if sectids attribute is unset' do input = <<-EOS [float] === Plain Ol' Heading not in section EOS output = render_embedded_string input, :attributes => {'sectids' => nil} assert_xpath '/h3', output, 1 assert_xpath '/h3[@id="_plain_ol_heading"]', output, 0 assert_xpath '/h3[@class="float"]', output, 1 end test 'should use explicit id for floating title if specified' do input = <<-EOS [[free]] [float] == Plain Ol' Heading not in section EOS output = render_embedded_string input assert_xpath '/h2', output, 1 assert_xpath '/h2[@id="free"]', output, 1 assert_xpath '/h2[@class="float"]', output, 1 end test 'should add role to class attribute on floating title' do input = <<-EOS [float, role="isolated"] == Plain Ol' Heading not in section EOS output = render_embedded_string input assert_xpath '/h2', output, 1 assert_xpath '/h2[@id="_plain_ol_heading"]', output, 1 assert_xpath '/h2[@class="float isolated"]', output, 1 end end context 'Section Numbering' do test 'should create section number with one entry for level 1' do sect1 = Asciidoctor::Section.new(nil) sect1.level = 1 assert_equal '1.', sect1.sectnum end test 'should create section number with two entries for level 2' do sect1 = Asciidoctor::Section.new(nil) sect1.level = 1 sect1_1 = Asciidoctor::Section.new(sect1) sect1 << sect1_1 assert_equal '1.1.', sect1_1.sectnum end test 'should create section number with three entries for level 3' do sect1 = Asciidoctor::Section.new(nil) sect1.level = 1 sect1_1 = Asciidoctor::Section.new(sect1) sect1 << sect1_1 sect1_1_1 = Asciidoctor::Section.new(sect1_1) sect1_1 << sect1_1_1 assert_equal '1.1.1.', sect1_1_1.sectnum end test 'should create section number for second section in level' do sect1 = Asciidoctor::Section.new(nil) sect1.level = 1 sect1_1 = Asciidoctor::Section.new(sect1) sect1 << sect1_1 sect1_2 = Asciidoctor::Section.new(sect1) sect1 << sect1_2 assert_equal '1.2.', sect1_2.sectnum end test 'sectnum should use specified delimiter and append string' do sect1 = Asciidoctor::Section.new(nil) sect1.level = 1 sect1_1 = Asciidoctor::Section.new(sect1) sect1 << sect1_1 sect1_1_1 = Asciidoctor::Section.new(sect1_1) sect1_1 << sect1_1_1 assert_equal '1,1,1,', sect1_1_1.sectnum(',') assert_equal '1:1:1', sect1_1_1.sectnum(':', false) end test 'should render section numbers when numbered attribute is set' do input = <<-EOS = Title :numbered: == Section_1 text === Section_1_1 text ==== Section_1_1_1 text == Section_2 text === Section_2_1 text === Section_2_2 text EOS output = render_string input assert_xpath '//h2[@id="_section_1"][starts-with(text(), "1. ")]', output, 1 assert_xpath '//h3[@id="_section_1_1"][starts-with(text(), "1.1. ")]', output, 1 assert_xpath '//h4[@id="_section_1_1_1"][starts-with(text(), "1.1.1. ")]', output, 1 assert_xpath '//h2[@id="_section_2"][starts-with(text(), "2. ")]', output, 1 assert_xpath '//h3[@id="_section_2_1"][starts-with(text(), "2.1. ")]', output, 1 assert_xpath '//h3[@id="_section_2_2"][starts-with(text(), "2.2. ")]', output, 1 end test 'blocks should have level' do input = <<-EOS = Title preamble == Section 1 paragraph === Section 1.1 paragraph EOS doc = document_from_string input assert_equal 0, doc.blocks[0].level assert_equal 1, doc.blocks[1].level assert_equal 1, doc.blocks[1].blocks[0].level assert_equal 2, doc.blocks[1].blocks[1].level assert_equal 2, doc.blocks[1].blocks[1].blocks[0].level end end context 'Special sections' do test 'should assign sectname and caption to appendix section' do input = <<-EOS [appendix] == Attribute Options Details EOS output = block_from_string input assert_equal 'appendix', output.sectname assert_equal 'Appendix A: ', output.attr('caption') end test 'should render appendix title prefixed with caption' do input = <<-EOS [appendix] == Attribute Options Details EOS output = render_embedded_string input assert_xpath '//h2[text()="Appendix A: Attribute Options"]', output, 1 end test 'should increment appendix number for each appendix section' do input = <<-EOS [appendix] == Attribute Options Details [appendix] == Migration Details EOS output = render_embedded_string input assert_xpath '(//h2)[1][text()="Appendix A: Attribute Options"]', output, 1 assert_xpath '(//h2)[2][text()="Appendix B: Migration"]', output, 1 end test 'should not number level 4 section' do input = <<-EOS :numbered: == Level_1 === Level_2 ==== Level_3 ===== Level_4 text EOS output = render_embedded_string input assert_xpath '//h5', output, 1 assert_xpath '//h5[text()="Level_4"]', output, 1 end test 'should not number special sections or subsections' do input = <<-EOS :numbered: == Section One [appendix] == Attribute Options Details [appendix] == Migration Details === Gotchas Details [glossary] == Glossary Terms EOS output = render_embedded_string input assert_xpath '(//h2)[1][text()="1. Section One"]', output, 1 assert_xpath '(//h2)[2][text()="Appendix A: Attribute Options"]', output, 1 assert_xpath '(//h2)[3][text()="Appendix B: Migration"]', output, 1 assert_xpath '(//h3)[1][text()="Gotchas"]', output, 1 assert_xpath '(//h2)[4][text()="Glossary"]', output, 1 end test 'should not number special sections or subsections in toc' do input = <<-EOS :numbered: :toc: == Section One [appendix] == Attribute Options Details [appendix] == Migration Details === Gotchas Details [glossary] == Glossary Terms EOS output = render_string input assert_xpath '//*[@id="toc"]/ol//li/a[text()="1. Section One"]', output, 1 assert_xpath '//*[@id="toc"]/ol//li/a[text()="Appendix A: Attribute Options"]', output, 1 assert_xpath '//*[@id="toc"]/ol//li/a[text()="Appendix B: Migration"]', output, 1 assert_xpath '//*[@id="toc"]/ol//li/a[text()="Gotchas"]', output, 1 assert_xpath '//*[@id="toc"]/ol//li/a[text()="Glossary"]', output, 1 end end context "heading patterns in blocks" do test "should not interpret a listing block as a heading" do input = <<-EOS Section ------- ---- code ---- fin. EOS output = render_string input assert_xpath "//h2", output, 1 end test "should not interpret an open block as a heading" do input = <<-EOS Section ------- -- ha -- fin. EOS output = render_string input assert_xpath "//h2", output, 1 end test "should not interpret an attribute list as a heading" do input = <<-EOS Section ======= preamble [TIP] ==== This should be a tip, not a heading. ==== EOS output = render_string input assert_xpath "//*[@class='admonitionblock']//p[text() = 'This should be a tip, not a heading.']", output, 1 end test "should not match a heading in a labeled list" do input = <<-EOS Section ------- term1:: + ---- list = [1, 2, 3]; ---- term2:: == not a heading term3:: def // fin. EOS output = render_string input assert_xpath "//h2", output, 1 assert_xpath "//dl", output, 1 end test "should not match a heading in a bulleted list" do input = <<-EOS Section ------- * first + ---- list = [1, 2, 3]; ---- + * second == not a heading * third fin. EOS output = render_string input assert_xpath "//h2", output, 1 assert_xpath "//ul", output, 1 end test "should not match a heading in a block" do input = <<-EOS ==== == not a heading ==== EOS output = render_string input assert_xpath "//h2", output, 0 assert_xpath "//*[@class='exampleblock']//p[text() = '== not a heading']", output, 1 end end context 'Table of Contents' do test 'should render table of contents if toc attribute is set' do input = <<-EOS Article ======= :toc: == Section One It was a dark and stormy night... == Section Two They couldn't believe their eyes when... === Interlude While they were waiting... == Section Three That's all she wrote! EOS output = render_string input assert_xpath '//*[@id="toc"]', output, 1 assert_xpath '//*[@id="toc"]/*[@id="toctitle"][text()="Table of Contents"]', output, 1 assert_xpath '//*[@id="toc"]/ol', output, 1 assert_xpath '//*[@id="toc"]//ol', output, 2 assert_xpath '//*[@id="toc"]/ol/li', output, 4 assert_xpath '//*[@id="toc"]/ol/li[1]/a[@href="#_section_one"][text()="1. Section One"]', output, 1 assert_xpath '//*[@id="toc"]/ol/li/ol/li', output, 1 assert_xpath '//*[@id="toc"]/ol/li/ol/li/a[@href="#_interlude"][text()="2.1. Interlude"]', output, 1 end end context "book doctype" do test "document title with level 0 headings" do input = <<-EOS Book ==== :doctype: book = Chapter One It was a dark and stormy night... = Chapter Two They couldn't believe their eyes when... == Interlude While they were waiting... = Chapter Three That's all she wrote! EOS output = render_string(input) assert_xpath '//h1', output, 4 assert_xpath '//h2', output, 1 assert_xpath '//h1[@id="_chapter_one"][text() = "Chapter One"]', output, 1 assert_xpath '//h1[@id="_chapter_two"][text() = "Chapter Two"]', output, 1 assert_xpath '//h1[@id="_chapter_three"][text() = "Chapter Three"]', output, 1 end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/renderer.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin module Asciidoctor # Public: Methods for rendering Asciidoc Documents, Sections, and Blocks # using eRuby templates. class Renderer attr_reader :compact # Public: Initialize an Asciidoctor::Renderer object. # def initialize(options={}) @debug = !!options[:debug] @views = {} @compact = options[:compact] backend = options[:backend] case backend when 'html5', 'docbook45' eruby = load_eruby options[:eruby] #Helpers.require_library 'asciidoctor/backends/' + backend require 'asciidoctor/backends/' + backend # Load up all the template classes that we know how to render for this backend BaseTemplate.template_classes.each do |tc| if tc.to_s.downcase.include?('::' + backend + '::') # optimization view_name, view_backend = self.class.extract_view_mapping(tc) if view_backend == backend @views[view_name] = tc.new(view_name, eruby) end end end else Debug.debug { "No built-in templates for backend: #{backend}" } end # If user passed in a template dir, let them override our base templates if template_dir = options.delete(:template_dir) Helpers.require_library 'tilt' template_glob = '*' if (engine = options[:template_engine]) template_glob = "*.#{engine}" # example: templates/haml if File.directory? File.join(template_dir, engine) template_dir = File.join template_dir, engine end end # example: templates/html5 or templates/haml/html5 if File.directory? File.join(template_dir, options[:backend]) template_dir = File.join template_dir, options[:backend] end view_opts = { :erb => { :trim => '<>' }, :haml => { :attr_wrapper => '"', :ugly => true, :escape_attrs => false }, :slim => { :disable_escape => true, :sort_attrs => false, :pretty => false } } if backend == 'html5' view_opts[:haml][:format] = view_opts[:slim][:format] = :html5 end Debug.debug { msg = [] msg << "Views going in are like so:" msg << @views.map {|k, v| "#{k}: #{v}"} msg << '=' * 60 msg * "\n" } slim_loaded = false helpers = nil # Grab the files in the top level of the directory (we're not traversing) Dir.glob(File.join(template_dir, template_glob)). select{|f| File.file? f }.each do |template| basename = File.basename(template) if basename == 'helpers.rb' helpers = template next end name_parts = basename.split('.') next if name_parts.size < 2 view_name = name_parts.first ext_name = name_parts.last if ext_name == 'slim' && !slim_loaded # slim doesn't get loaded by Tilt Helpers.require_library 'slim' end next unless Tilt.registered? ext_name @views[view_name] = Tilt.new(template, nil, view_opts[ext_name.to_sym]) end require helpers unless helpers.nil? Debug.debug { msg = [] msg << "Views going in are like so:" msg << @views.map {|k, v| "#{k}: #{v}"} msg << '=' * 60 msg * "\n" } end @render_stack = [] end # Public: Render an Asciidoc object with a specified view template. # # view - the String view template name. # object - the Object to be used as an evaluation scope. # locals - the optional Hash of locals to be passed to Tilt (default {}) (also ignored, really) def render(view, object, locals = {}) @render_stack.push([view, object]) if !@views.has_key? view raise "Couldn't find a view in @views for #{view}" else Debug.debug { "View for #{view} is #{@views[view]}, object is #{object}" } end ret = @views[view].render(object, locals) if @debug prefix = '' STDERR.puts '=' * 80 STDERR.puts "Rendering:" @render_stack.each do |stack_view, stack_obj| obj_info = case stack_obj when Section; "SECTION #{stack_obj.title}" when Block; if stack_obj.context == :dlist dt_list = stack_obj.buffer.map{|dt,dd| dt.content.strip}.join(', ') "BLOCK :dlist (#{dt_list})" #else # "BLOCK #{stack_obj.context.inspect}" end else stack_obj.class end STDERR.puts "#{prefix}#{stack_view}: #{obj_info}" prefix << ' ' end STDERR.puts '-' * 80 #STDERR.puts ret.inspect STDERR.puts '=' * 80 STDERR.puts end @render_stack.pop ret end def views readonly_views = @views.dup readonly_views.freeze readonly_views end # Internal: Load the eRuby implementation # # name - the String name of the eRuby implementation (default: 'erb') # # returns the eRuby implementation class def load_eruby(name) if name.nil? || !['erb', 'erubis'].include?(name) name = 'erb' end Helpers.require_library name if name == 'erb' ::ERB elsif name == 'erubis' ::Erubis::FastEruby end end # Internal: Extracts the view name and backend from a qualified Ruby class # # The purpose of this method is to determine the view name and backend to # which a built-in template class maps. We can make certain assumption since # we have control over these class names. The Asciidoctor:: prefix and # Template suffix are stripped as the first step in the conversion. # # qualified_class - The Class or String qualified class name from which to extract the view name and backend # # Examples # # Renderer.extract_view_mapping(Asciidoctor::HTML5::DocumentTemplate) # # => ['document', 'html5'] # # Renderer.extract_view_mapping(Asciidoctor::DocBook45::BlockSidebarTemplate) # # => ['block_sidebar', 'docbook45'] # # Returns A two-element String Array mapped as [view_name, backend], where backend may be nil def self.extract_view_mapping(qualified_class) view_name, backend = qualified_class.to_s. gsub(/^Asciidoctor::/, ''). gsub(/Template$/, ''). split('::').reverse view_name = camelcase_to_underscore(view_name) backend = backend.downcase unless backend.nil? [view_name, backend] end # Internal: Convert a CamelCase word to an underscore-delimited word # # Examples # # Renderer.camelcase_to_underscore('BlockSidebar') # # => 'block_sidebar' # # Renderer.camelcase_to_underscore('BlockUlist') # # => 'block_ulist' # # Returns the String converted from CamelCase to underscore-delimited def self.camelcase_to_underscore(str) str.gsub(/([[:upper:]]+)([[:upper:]][[:alpha:]])/, '\1_\2'). gsub(/([[:lower:]])([[:upper:]])/, '\1_\2').downcase end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/substituters.rb
<gh_stars>0 module Asciidoctor # Public: Methods to perform substitutions on lines of AsciiDoc text. This module # is intented to be mixed-in to Section and Block to provide operations for performing # the necessary substitutions. module Substituters COMPOSITE_SUBS = { :none => [], :normal => [:specialcharacters, :quotes, :attributes, :replacements, :macros, :post_replacements], :verbatim => [:specialcharacters, :callouts] } SUB_OPTIONS = COMPOSITE_SUBS.keys + COMPOSITE_SUBS[:normal] # Internal: A String Array of passthough (unprocessed) text captured from this block attr_reader :passthroughs # Public: Apply the specified substitutions to the lines of text # # lines - The lines of text to process. Can be a String or a String Array # subs - The substitutions to perform. Can be a Symbol or a Symbol Array (default: COMPOSITE_SUBS[:normal]) # # returns Either a String or String Array, whichever matches the type of the first argument def apply_subs(lines, subs = COMPOSITE_SUBS[:normal]) if subs.nil? subs = [] elsif subs.is_a? Symbol subs = [subs] end if !subs.empty? # QUESTION is this most efficient operation? subs = subs.map {|key| COMPOSITE_SUBS.has_key?(key) ? COMPOSITE_SUBS[key] : key }.flatten end return lines if subs.empty? multiline = lines.is_a?(Array) text = multiline ? lines.join : lines passthroughs = subs.include?(:macros) text = extract_passthroughs(text) if passthroughs subs.each {|type| case type when :specialcharacters text = sub_specialcharacters(text) when :quotes text = sub_quotes(text) when :attributes text = sub_attributes(text.lines.entries).join when :replacements text = sub_replacements(text) when :macros text = sub_macros(text) when :callouts text = sub_callouts(text) when :post_replacements text = sub_post_replacements(text) else puts "asciidoctor: WARNING: unknown substitution type #{type}" end } text = restore_passthroughs(text) if passthroughs multiline ? text.lines.entries : text end # Public: Apply normal substitutions. # # lines - The lines of text to process. Can be a String or a String Array # # returns - A String with normal substitutions performed def apply_normal_subs(lines) apply_subs(lines.is_a?(Array) ? lines.join : lines) end # Public: Apply substitutions for titles. # # title - The String title to process # # returns - A String with title substitutions performed def apply_title_subs(title) apply_subs(title, [:specialcharacters, :quotes, :replacements, :macros, :attributes, :post_replacements]) end # Public: Apply substitutions for titles # # lines - A String Array containing the lines of text process # # returns - A String with literal (verbatim) substitutions performed def apply_literal_subs(lines) if @document.attributes['basebackend'] == 'html' && attr('style') == 'source' && @document.attributes['source-highlighter'] == 'coderay' && attr?('language') sub_callouts(highlight_source(lines.join)) else apply_subs(lines.join, COMPOSITE_SUBS[:verbatim]) end end # Public: Apply substitutions for header metadata and attribute assignments # # text - String containing the text process # # returns - A String with header substitutions performed def apply_header_subs(text) apply_subs(text, [:specialcharacters, :attributes]) end # Public: Apply substitutions for passthrough text # # lines - A String Array containing the lines of text process # # returns - A String Array with passthrough substitutions performed def apply_passthrough_subs(lines) if attr? 'subs' subs = resolve_subs(attr('subs')) else subs = [:attributes, :macros] end apply_subs(lines.join, subs) end # Internal: Extract the passthrough text from the document for reinsertion after processing. # # text - The String from which to extract passthrough fragements # # returns - The text with the passthrough region substituted with placeholders def extract_passthroughs(text) result = text.dup result.gsub!(REGEXP[:pass_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end if m[1] == '$$' subs = [:specialcharacters] elsif !m[3].nil? && !m[3].empty? subs = resolve_subs(m[3]) else subs = [] end # TODO move unescaping closing square bracket to an operation @passthroughs << {:text => m[2] || m[4].gsub('\]', ']'), :subs => subs} index = @passthroughs.size - 1 "\x0#{index}\x0" } unless !(result.include?('+++') || result.include?('$$') || result.include?('pass:')) result.gsub!(REGEXP[:pass_lit]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[2].start_with? '\\' next "#{m[1]}#{m[2][1..-1]}" end @passthroughs << {:text => m[3], :subs => [:specialcharacters], :literal => true} index = @passthroughs.size - 1 "#{m[1]}\x0#{index}\x0" } unless !result.include?('`') result end # Internal: Restore the passthrough text by reinserting into the placeholder positions # # text - The String text into which to restore the passthrough text # # returns The String text with the passthrough text restored def restore_passthroughs(text) return text if @passthroughs.nil? || @passthroughs.empty? || !text.include?("\x0") text.gsub(REGEXP[:pass_placeholder]) { pass = @passthroughs[$1.to_i]; text = apply_subs(pass[:text], pass.fetch(:subs, [])) pass[:literal] ? Inline.new(self, :quoted, text, :type => :monospaced).render : text } end # Public: Substitute special characters (i.e., encode XML) # # Special characters are defined in the Asciidoctor::SPECIAL_CHARS Array constant # # text - The String text to process # # returns The String text with special characters replaced def sub_specialcharacters(text) # this syntax only available in Ruby 1.9 #text.gsub(SPECIAL_CHARS_PATTERN, SPECIAL_CHARS) text.gsub(SPECIAL_CHARS_PATTERN) { SPECIAL_CHARS[$&] } end # Public: Substitute quoted text (includes emphasis, strong, monospaced, etc) # # text - The String text to process # # returns The String text with quoted text rendered using the backend templates def sub_quotes(text) result = text.dup QUOTE_SUBS.each {|type, scope, pattern| result.gsub!(pattern) { transform_quoted_text($~, type, scope) } } result end # Public: Substitute replacement characters (e.g., copyright, trademark, etc) # # text - The String text to process # # returns The String text with the replacement characters substituted def sub_replacements(text) result = text.dup REPLACEMENTS.each {|pattern, replacement| result.gsub!(pattern, replacement) } result end # Public: Substitute attribute references # # Attribute references are in the format {name}. # # If an attribute referenced in the line is missing, the line is dropped. # # text - The String text to process # # returns The String text with the attribute references replaced with attribute values #-- # NOTE it's necessary to perform this substitution line-by-line # so that a missing key doesn't wipe out the whole block of data def sub_attributes(data) return data if data.nil? || data.empty? # normalizes data type to an array (string becomes single-element array) lines = Array(data) result = lines.map {|line| reject = false subject = line.dup subject.gsub!(REGEXP[:attr_ref]) { # alias match for Ruby 1.8.7 compat m = $~ key = m[2].downcase # escaped attribute if !$1.empty? || !$3.empty? "{#$2}" elsif m[2].start_with?('counter:') args = m[2].split(':') @document.counter(args[1], args[2]) elsif m[2].start_with?('counter2:') args = m[2].split(':') @document.counter(args[1], args[2]) '' elsif document.attributes.has_key? key @document.attributes[key] elsif INTRINSICS.has_key? key INTRINSICS[key] else Debug.debug { "Missing attribute: #{m[2]}, line marked for removal" } reject = true break '{undefined}' end } if subject.include?('{') !reject ? subject : nil }.compact data.is_a?(String) ? result.join : result end # Public: Substitute inline macros (e.g., links, images, etc) # # Replace inline macros, which may span multiple lines, in the provided text # # text - The String text to process # # returns The String with the inline macros rendered using the backend templates def sub_macros(text) return text if text.nil? || text.empty? result = text.dup # some look ahead assertions to cut unnecessary regex calls found = {} found[:square_bracket] = result.include?('[') found[:round_bracket] = result.include?('(') found[:colon] = result.include?(':') found[:macroish] = (found[:square_bracket] && found[:colon]) found[:macroish_short_form] = (found[:square_bracket] && found[:colon] && result.include?(':[')) found[:uri] = (found[:colon] && result.include?('://')) link_attrs = @document.attributes.has_key?('linkattrs') if found[:macroish] && result.include?('image:') # image:filename.png[Alt Text] result.gsub!(REGEXP[:image_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end target = sub_attributes(m[1]) @document.register(:images, target) attrs = parse_attributes(m[2], ['alt', 'width', 'height']) if !attrs.has_key?('alt') || attrs['alt'].empty? attrs['alt'] = File.basename(target, File.extname(target)) end Inline.new(self, :image, nil, :target => target, :attributes => attrs).render } end if found[:macroish_short_form] || found[:round_bracket] # indexterm:[Tigers,Big cats] # (((Tigers,Big cats))) result.gsub!(REGEXP[:indexterm_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end terms = (m[1] || m[2]).strip.tr("\n", ' ').gsub('\]', ']').split(REGEXP[:csv_delimiter]) document.register(:indexterms, [*terms]) Inline.new(self, :indexterm, text, :attributes => {'terms' => terms}).render } # indexterm2:[Tigers] # ((Tigers)) result.gsub!(REGEXP[:indexterm2_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end text = (m[1] || m[2]).strip.tr("\n", ' ').gsub('\]', ']') document.register(:indexterms, [text]) Inline.new(self, :indexterm, text, :type => :visible).render } end if found[:uri] # inline urls, target[text] (optionally prefixed with link: and optionally surrounded by <>) result.gsub!(REGEXP[:link_inline]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[2].start_with? '\\' next "#{m[1]}#{m[2][1..-1]}#{m[3]}" # not a valid macro syntax w/o trailing square brackets # we probably shouldn't even get here...our regex is doing too much elsif m[1] == 'link:' && m[3].nil? next m[0] end prefix = (m[1] != 'link:' ? m[1] : '') target = m[2] # strip the <> around the link if prefix.end_with? '&lt;' prefix = prefix[0..-5] end if target.end_with? '&gt;' target = target[0..-5] end @document.register(:links, target) attrs = nil #text = !m[3].nil? ? sub_attributes(m[3].gsub('\]', ']')) : '' if !m[3].to_s.empty? if link_attrs && (m[3].start_with?('"') || m[3].include?(',')) attrs = parse_attributes(sub_attributes(m[3].gsub('\]', ']'))) text = attrs[1] else text = sub_attributes(m[3].gsub('\]', ']')) end else text = '' end "#{prefix}#{Inline.new(self, :anchor, (!text.empty? ? text : target), :type => :link, :target => target, :attributes => attrs).render}" } end if found[:macroish] && result.include?('link:') # inline link macros, link:target[text] result.gsub!(REGEXP[:link_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end target = m[1] @document.register(:links, target) attrs = nil #text = sub_attributes(m[2].gsub('\]', ']')) if link_attrs && (m[2].start_with?('"') || m[2].include?(',')) attrs = parse_attributes(sub_attributes(m[2].gsub('\]', ']'))) text = attrs[1] else text = sub_attributes(m[2].gsub('\]', ']')) end Inline.new(self, :anchor, (!text.empty? ? text : target), :type => :link, :target => target, :attributes => attrs).render } end if found[:macroish_short_form] && result.include?('footnote') result.gsub!(REGEXP[:footnote_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end if m[1] == 'footnote' # hmmmm text = restore_passthroughs(m[2]) id = nil index = @document.counter('footnote-number') @document.register(:footnotes, Document::Footnote.new(index, id, text)) type = nil target = nil else id, text = m[2].split(REGEXP[:csv_delimiter], 2) if !text.nil? # hmmmm text = restore_passthroughs(text) index = @document.counter('footnote-number') @document.register(:footnotes, Document::Footnote.new(index, id, text)) type = :ref target = nil else footnote = @document.references[:footnotes].find {|fn| fn.id == id } target = id id = nil index = footnote.index text = footnote.text type = :xref end end Inline.new(self, :footnote, text, :attributes => {'index' => index}, :id => id, :target => target, :type => type).render } end if found[:macroish] || result.include?('&lt;&lt;') result.gsub!(REGEXP[:xref_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end if !m[1].nil? id, reftext = m[1].split(REGEXP[:csv_delimiter], 2) id.sub!(REGEXP[:dbl_quoted], '\2') reftext.sub!(REGEXP[:m_dbl_quoted], '\2') unless reftext.nil? else id = m[2] reftext = !m[3].empty? ? m[3] : nil end Inline.new(self, :anchor, reftext, :type => :xref, :target => id).render } end if found[:square_bracket] && result.include?('[[[') result.gsub!(REGEXP[:biblio_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end id = reftext = m[1] Inline.new(self, :anchor, reftext, :type => :bibref, :target => id).render } end if found[:square_bracket] && result.include?('[[') result.gsub!(REGEXP[:anchor_macro]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next m[0][1..-1] end id, reftext = m[1].split(REGEXP[:csv_delimiter]) id.sub!(REGEXP[:dbl_quoted], '\2') if reftext.nil? reftext = "[#{id}]" else reftext.sub!(REGEXP[:m_dbl_quoted], '\2') end # NOTE the reftext should also match what's in our references dic if !@document.references[:ids].has_key? id Debug.debug { "Missing reference for anchor #{id}" } end Inline.new(self, :anchor, reftext, :type => :ref, :target => id).render } end result end # Public: Substitute callout references # # text - The String text to process # # returns The String with the callout references rendered using the backend templates def sub_callouts(text) text.gsub(REGEXP[:callout_render]) { # alias match for Ruby 1.8.7 compat m = $~ # honor the escape if m[0].start_with? '\\' next "&lt;#{m[1]}&gt;" end Inline.new(self, :callout, m[1], :id => document.callouts.read_next_id).render } end # Public: Substitute post replacements # # text - The String text to process # # returns The String with the post replacements rendered using the backend templates def sub_post_replacements(text) if @document.attr? 'hardbreaks' lines = text.lines.entries return text if lines.size == 1 last = lines.pop "#{lines.map {|line| Inline.new(self, :break, line.rstrip.chomp(LINE_BREAK), :type => :line).render } * "\n"}\n#{last}" else text.gsub(REGEXP[:line_break]) { Inline.new(self, :break, $1, :type => :line).render } end end # Internal: Transform (render) a quoted text region # # match - The MatchData for the quoted text region # type - The quoting type (single, double, strong, emphasis, monospaced, etc) # scope - The scope of the quoting (constrained or unconstrained) # # returns The rendered text for the quoted text region def transform_quoted_text(match, type, scope) if match[0].start_with? '\\' match[0][1..-1] elsif scope == :constrained "#{match[1]}#{Inline.new(self, :quoted, match[3], :type => type, :attributes => parse_attributes(match[2])).render}" else Inline.new(self, :quoted, match[2], :type => type, :attributes => parse_attributes(match[1])).render end end # Internal: Parse the attributes in the attribute line # # attrline - A String of unprocessed attributes (key/value pairs) # posattrs - The keys for positional attributes # # returns nil if attrline is nil, an empty Hash if attrline is empty, otherwise a Hash of parsed attributes def parse_attributes(attrline, posattrs = ['role']) return nil if attrline.nil? return {} if attrline.empty? AttributeList.new(attrline, self).parse(posattrs) end # Internal: Resolve the list of comma-delimited subs against the possible options. # # subs - A comma-delimited String of substitution aliases # # returns An Array of Symbols representing the substitution operation def resolve_subs(subs) candidates = subs.split(',').map {|sub| sub.strip.to_sym} resolved = candidates & SUB_OPTIONS if (invalid = candidates - resolved).size > 0 puts "asciidoctor: WARNING: invalid passthrough macro substitution operation#{invalid.size > 1 ? 's' : ''}: #{invalid * ', '}" end resolved end # Public: Highlight the source code if a source highlighter is defined # on the document, otherwise return the text unprocessed # # source - the source code String to highlight # # returns the highlighted source code, if a source highlighter is defined # on the document, otherwise the unprocessed text def highlight_source(source) Helpers.require_library 'coderay' ::CodeRay::Duo[attr('language', 'text').to_sym, :html, { :css => @document.attributes.fetch('coderay-css', 'class').to_sym, :line_numbers => (attr?('linenums') ? @document.attributes.fetch('coderay-linenums-mode', 'table').to_sym : nil), :line_number_anchors => false}].highlight(source).chomp end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/lexer.rb
<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/lexer.rb<gh_stars>0 module Asciidoctor # Public: Methods to parse lines of AsciiDoc into an object hierarchy # representing the structure of the document. All methods are class methods and # should be invoked from the Lexer class. The main entry point is ::next_block. # No Lexer instances shall be discovered running around. (Any attempt to # instantiate a Lexer will be futile). # # The object hierarchy created by the Lexer consists of zero or more Section # and Block objects. Section objects may be nested and a Section object # contains zero or more Block objects. Block objects may be nested, but may # only contain other Block objects. Block objects which represent lists may # contain zero or more ListItem objects. # # Examples # # # Create a Reader for the AsciiDoc lines and retrieve the next block from it. # # Lexer::next_block requires a parent, so we begin by instantiating an empty Document. # # doc = Document.new # reader = Reader.new lines # block = Lexer.next_block(reader, doc) # block.class # # => Asciidoctor::Block class Lexer BlockMatchData = Struct.new(:name, :tip, :terminator) # Public: Make sure the Lexer object doesn't get initialized. # # Raises RuntimeError if this constructor is invoked. def initialize raise 'Au contraire, mon frere. No lexer instances will be running around.' end # Public: Parses AsciiDoc source read from the Reader into the Document # # This method is the main entry-point into the Lexer when parsing a full document. # It first looks for and, if found, processes the document title. It then # proceeds to iterate through the lines in the Reader, parsing the document # into nested Sections and Blocks. # # reader - the Reader holding the source lines of the document # document - the empty Document into which the lines will be parsed # options - a Hash of options to control processing # # returns the Document object def self.parse(reader, document, options = {}) block_attributes = parse_document_header(reader, document) unless options[:header_only] while reader.has_more_lines? new_section, block_attributes = next_section(reader, document, block_attributes) document << new_section unless new_section.nil? end end document end # Public: Parses the document header of the AsciiDoc source read from the Reader # # Reads the AsciiDoc source from the Reader until the end of the document # header is reached. The Document object is populated with information from # the header (document title, document attributes, etc). The document # attributes are then saved to establish a save point to which to rollback # after parsing is complete. # # This method assumes that there are no blank lines at the start of the document, # which are automatically removed by the reader. # # returns the Hash of orphan block attributes captured above the header def self.parse_document_header(reader, document) # capture any lines of block-level metadata and plow away any comment lines # that precede first block block_attributes = parse_block_metadata_lines(reader, document) # check if the first line is the document title # if so, add a header to the document and parse the header metadata if is_next_line_document_title?(reader, block_attributes) document.id, document.title, _, _ = parse_section_title(reader) # QUESTION: should this be encapsulated in document? if document.id.nil? && block_attributes.has_key?('id') document.id = block_attributes.delete('id') end parse_header_metadata(reader, document) end if document.attributes.has_key? 'doctitle' document.title = document.attributes['doctitle'] end document.clear_playback_attributes block_attributes document.save_attributes # NOTE these are the block-level attributes (not document attributes) that # precede the first line of content (document title, first section or first block) block_attributes end # Public: Return the next section from the Reader. # # This method process block metadata, content and subsections for this # section and returns the Section object and any orphaned attributes. # # If the parent is a Document and has a header (document title), then # this method will put any non-section blocks at the start of document # into a preamble Block. If there are no such blocks, the preamble is # dropped. # # Since we are reading line-by-line, there's a chance that metadata # that should be associated with the following block gets consumed. # To deal with this case, the method returns a running Hash of # "orphaned" attributes that get passed to the next Section or Block. # # reader - the source Reader # parent - the parent Section or Document of this new section # attributes - a Hash of metadata that was left orphaned from the # previous Section. # # Examples # # source # # => "Greetings\n---------\nThis is my doc.\n\nSalutations\n-----------\nIt is awesome." # # reader = Reader.new source.lines.entries # # create empty document to parent the section # # and hold attributes extracted from header # doc = Document.new # # Lexer.next_section(reader, doc).first.title # # => "Greetings" # # Lexer.next_section(reader, doc).first.title # # => "Salutations" # # returns a two-element Array containing the Section and Hash of orphaned attributes def self.next_section(reader, parent, attributes = {}) preamble = false # check if we are at the start of processing the document # NOTE we could drop a hint in the attributes to indicate # that we are at a section title (so we don't have to check) if parent.is_a?(Document) && parent.blocks.empty? && (parent.has_header? || !is_next_line_section?(reader, attributes)) if parent.has_header? preamble = Block.new(parent, :preamble) parent << preamble end section = parent current_level = 0 if parent.attributes.has_key? 'fragment' expected_next_levels = nil # small tweak to allow subsequent level-0 sections for book doctype elsif parent.doctype == 'book' expected_next_levels = [0, 1] else expected_next_levels = [1] end else section = initialize_section(reader, parent, attributes) # clear attributes, except for title which carries over # section title to next block of content attributes = attributes.delete_if {|k, v| k != 'title'} current_level = section.level expected_next_levels = [current_level + 1] end reader.skip_blank_lines # Parse lines belonging to this section and its subsections until we # reach the end of this section level # # 1. first look for metadata thingies (anchor, attribute list, block title line, etc) # 2. then look for a section, recurse if found # 3. then process blocks # # We have to parse all the metadata lines before continuing with the loop, # otherwise subsequent metadata lines get interpreted as block content while reader.has_more_lines? parse_block_metadata_lines(reader, section, attributes) next_level = is_next_line_section? reader, attributes if next_level doctype = parent.document.doctype if next_level == 0 && doctype != 'book' puts "asciidoctor: ERROR: line #{reader.lineno + 1}: only book doctypes can contain level 0 sections" end if next_level > current_level || (section.is_a?(Document) && next_level == 0) unless expected_next_levels.nil? || expected_next_levels.include?(next_level) puts "asciidoctor: WARNING: line #{reader.lineno + 1}: section title out of sequence: " + "expected #{expected_next_levels.size > 1 ? 'levels' : 'level'} #{expected_next_levels * ' or '}, " + "got level #{next_level}" end # the attributes returned are those that are orphaned new_section, attributes = next_section(reader, section, attributes) section << new_section else # close this section (and break out of the nesting) to begin a new one break end else # just take one block or else we run the risk of overrunning section boundaries new_block = next_block(reader, section, attributes, :parse_metadata => false) if !new_block.nil? (preamble || section) << new_block attributes = {} else # don't clear attributes if we don't find a block because they may # be trailing attributes that didn't get associated with a block end end reader.skip_blank_lines end # prune the preamble if it has no content if preamble && preamble.blocks.empty? section.delete_at(0) end # The attributes returned here are orphaned attributes that fall at the end # of a section that need to get transfered to the next section # see "trailing block attributes transfer to the following section" in # test/attributes_test.rb for an example [section != parent ? section : nil, attributes.dup] end # Public: Return the next Section or Block object from the Reader. # # Begins by skipping over blank lines to find the start of the next Section # or Block. Processes each line of the reader in sequence until a Section or # Block is found or the reader has no more lines. # # Uses regular expressions from the Asciidoctor module to match Section # and Block delimiters. The ensuing lines are then processed according # to the type of content. # # reader - The Reader from which to retrieve the next block # parent - The Document, Section or Block to which the next block belongs # # Returns a Section or Block object holding the parsed content of the processed lines def self.next_block(reader, parent, attributes = {}, options = {}) # Skip ahead to the block content skipped = reader.skip_blank_lines # bail if we've reached the end of the section content return nil unless reader.has_more_lines? if options[:text] && skipped > 0 options.delete(:text) end Debug.debug { msg = [] msg << '/' * 64 msg << 'next_block() - First two lines are:' msg.concat reader.peek_lines(2) msg << '/' * 64 msg * "\n" } parse_metadata = options[:parse_metadata] || true parse_sections = options[:parse_sections] || false document = parent.document context = parent.is_a?(Block) ? parent.context : nil block = nil while reader.has_more_lines? && block.nil? if parse_metadata && parse_block_metadata_line(reader, document, attributes, options) reader.advance next elsif parse_sections && context.nil? && is_next_line_section?(reader, attributes) block, attributes = next_section(reader, parent, attributes) break end this_line = reader.get_line block_context = nil terminator = nil if delimited_blk_match = is_delimited_block?(this_line, true) block_context = delimited_blk_match.name terminator = delimited_blk_match.terminator end # NOTE we're letting break lines (ruler, page_break, etc) have attributes if !options[:text] && block_context.nil? && (match = this_line.match(REGEXP[:break_line])) block = Block.new(parent, BREAK_LINES[match[0][0..2]]) reader.skip_blank_lines elsif !options[:text] && block_context.nil? && (match = this_line.match(REGEXP[:image_blk])) block = Block.new(parent, :image) AttributeList.new(document.sub_attributes(match[2])).parse_into(attributes, ['alt', 'width', 'height']) target = block.sub_attributes(match[1]) if !target.to_s.empty? attributes['target'] = target document.register(:images, target) attributes['alt'] ||= File.basename(target, File.extname(target)) block.title = attributes['title'] if block.title? && !attributes.has_key?('caption') && !block.attr?('caption') number = document.counter('figure-number') attributes['caption'] = "#{document.attributes['figure-caption']} #{number}. " Document::AttributeEntry.new('figure-number', number).save_to(attributes) end else # drop the line if target resolves to nothing block = nil end reader.skip_blank_lines elsif block_context == :open # an open block is surrounded by '--' lines and has zero or more blocks inside buffer = Reader.new reader.grab_lines_until(:terminator => terminator) # Strip lines off end of block - not implemented yet # while buffer.has_more_lines? && buffer.last.strip.empty? # buffer.pop # end block = Block.new(parent, block_context) while buffer.has_more_lines? new_block = next_block(buffer, block) block.blocks << new_block unless new_block.nil? end # needs to come before list detection elsif block_context == :sidebar # sidebar is surrounded by '****' (4 or more '*' chars) lines # FIXME violates DRY because it's a duplication of quote parsing block = Block.new(parent, block_context) buffer = Reader.new reader.grab_lines_until(:terminator => terminator) while buffer.has_more_lines? new_block = next_block(buffer, block) block.blocks << new_block unless new_block.nil? end elsif block_context.nil? && (match = this_line.match(REGEXP[:colist])) block = Block.new(parent, :colist) attributes['style'] = 'arabic' items = [] block.buffer = items reader.unshift_line this_line expected_index = 1 begin # might want to move this check to a validate method if match[1].to_i != expected_index puts "asciidoctor: WARNING: line #{reader.lineno + 1}: callout list item index: expected #{expected_index} got #{match[1]}" end list_item = next_list_item(reader, block, match) expected_index += 1 if !list_item.nil? items << list_item coids = document.callouts.callout_ids(items.size) if !coids.empty? list_item.attributes['coids'] = coids else puts "asciidoctor: WARNING: line #{reader.lineno}: no callouts refer to list item #{items.size}" end end end while reader.has_more_lines? && match = reader.peek_line.match(REGEXP[:colist]) document.callouts.next_list elsif block_context.nil? && (match = this_line.match(REGEXP[:ulist])) AttributeList.rekey(attributes, ['style']) reader.unshift_line this_line block = next_outline_list(reader, :ulist, parent) elsif block_context.nil? && (match = this_line.match(REGEXP[:olist])) AttributeList.rekey(attributes, ['style']) reader.unshift_line this_line block = next_outline_list(reader, :olist, parent) # QUESTION move this logic to next_outline_list? if !(attributes.has_key? 'style') && !(block.attributes.has_key? 'style') marker = block.buffer.first.marker if marker.start_with? '.' # first one makes more sense, but second on is AsciiDoc-compliant #attributes['style'] = (ORDERED_LIST_STYLES[block.level - 1] || ORDERED_LIST_STYLES.first).to_s attributes['style'] = (ORDERED_LIST_STYLES[marker.length - 1] || ORDERED_LIST_STYLES.first).to_s else style = ORDERED_LIST_STYLES.detect{|s| marker.match(ORDERED_LIST_MARKER_PATTERNS[s]) } attributes['style'] = (style || ORDERED_LIST_STYLES.first).to_s end end elsif block_context.nil? && (match = this_line.match(REGEXP[:dlist])) reader.unshift_line this_line block = next_labeled_list(reader, match, parent) AttributeList.rekey(attributes, ['style']) elsif block_context == :table # table is surrounded by lines starting with a | followed by 3 or more '=' chars AttributeList.rekey(attributes, ['style']) table_reader = Reader.new reader.grab_lines_until(:terminator => terminator, :skip_line_comments => true) block = next_table(table_reader, parent, attributes) block.title = attributes['title'] if block.title? && !attributes.has_key?('caption') && !block.attr?('caption') number = document.counter('table-number') attributes['caption'] = "#{document.attributes['table-caption']} #{number}. " Document::AttributeEntry.new('table-number', number).save_to(attributes) end # FIXME violates DRY because it's a duplication of other block parsing elsif block_context == :example # example is surrounded by lines with 4 or more '=' chars AttributeList.rekey(attributes, ['style']) if admonition_style = ADMONITION_STYLES.detect {|s| attributes['style'] == s} block = Block.new(parent, :admonition) attributes['name'] = admonition_name = admonition_style.downcase attributes['caption'] ||= document.attributes["#{admonition_name}-caption"] else block = Block.new(parent, block_context) block.title = attributes['title'] if block.title? && !attributes.has_key?('caption') && !block.attr?('caption') number = document.counter('example-number') attributes['caption'] = "#{document.attributes['example-caption']} #{number}. " Document::AttributeEntry.new('example-number', number).save_to(attributes) end end buffer = Reader.new reader.grab_lines_until(:terminator => terminator) while buffer.has_more_lines? new_block = next_block(buffer, block) block.blocks << new_block unless new_block.nil? end # FIXME violates DRY w/ non-delimited block listing elsif block_context == :listing || block_context == :fenced_code if block_context == :fenced_code attributes['style'] = 'source' lang = this_line[3..-1].strip attributes['language'] = lang unless lang.empty? terminator = terminator[0..2] if terminator.length > 3 else AttributeList.rekey(attributes, ['style', 'language', 'linenums']) end buffer = reader.grab_lines_until(:terminator => terminator) buffer.last.chomp! unless buffer.empty? block = Block.new(parent, :listing, buffer) block.title = attributes['title'] if document.attributes.has_key?('listing-caption') && block.title? && !attributes.has_key?('caption') && !block.attr?('caption') number = document.counter('listing-number') attributes['caption'] = "#{document.attributes['listing-caption']} #{number}. " Document::AttributeEntry.new('listing-number', number).save_to(attributes) end elsif block_context == :quote # multi-line verse or quote is surrounded by a block delimiter AttributeList.rekey(attributes, ['style', 'attribution', 'citetitle']) quote_context = (attributes['style'] == 'verse' ? :verse : :quote) block_reader = Reader.new reader.grab_lines_until(:terminator => terminator) # only quote can have other section elements (as section block) section_body = (quote_context == :quote) if section_body block = Block.new(parent, quote_context) while block_reader.has_more_lines? new_block = next_block(block_reader, block) block.blocks << new_block unless new_block.nil? end else block_reader.chomp_last! block = Block.new(parent, quote_context, block_reader.lines) end elsif block_context == :literal || block_context == :pass # literal is surrounded by '....' (4 or more '.' chars) lines # pass is surrounded by '++++' (4 or more '+' chars) lines buffer = reader.grab_lines_until(:terminator => terminator) buffer.last.chomp! unless buffer.empty? # a literal can masquerade as a listing if attributes[1] == 'listing' block_context = :listing end block = Block.new(parent, block_context, buffer) elsif this_line.match(REGEXP[:lit_par]) # literal paragraph is contiguous lines starting with # one or more space or tab characters # So we need to actually include this one in the grab_lines group reader.unshift_line this_line buffer = reader.grab_lines_until(:preserve_last_line => true, :break_on_blank_lines => true) {|line| # labeled list terms can be indented, but a preceding blank indicates # we are in a list continuation and therefore literals should be strictly literal (context == :dlist && skipped == 0 && line.match(REGEXP[:dlist])) || is_delimited_block?(line) } # trim off the indentation equivalent to the size of the least indented line if !buffer.empty? offset = buffer.map {|line| line.match(REGEXP[:leading_blanks])[1].length }.min if offset > 0 buffer = buffer.map {|l| l.sub(/^\s{1,#{offset}}/, '') } end buffer.last.chomp! end block = Block.new(parent, :literal, buffer) # a literal gets special meaning inside of a definition list if LIST_CONTEXTS.include?(context) attributes['options'] ||= [] # TODO this feels hacky, better way to distinguish from explicit literal block? attributes['options'] << 'listparagraph' end ## these switches based on style need to come immediately before the else ## elsif attributes[1] == 'source' || attributes[1] == 'listing' if attributes[1] == 'source' AttributeList.rekey(attributes, ['style', 'language', 'linenums']) end reader.unshift_line this_line buffer = reader.grab_lines_until(:break_on_blank_lines => true) buffer.last.chomp! unless buffer.empty? block = Block.new(parent, :listing, buffer) elsif attributes[1] == 'literal' reader.unshift_line this_line buffer = reader.grab_lines_until(:break_on_blank_lines => true) buffer.last.chomp! unless buffer.empty? block = Block.new(parent, :literal, buffer) elsif admonition_style = ADMONITION_STYLES.detect{|s| attributes[1] == s} # an admonition preceded by [<TYPE>] and lasts until a blank line reader.unshift_line this_line buffer = reader.grab_lines_until(:break_on_blank_lines => true) buffer.last.chomp! unless buffer.empty? block = Block.new(parent, :admonition, buffer) attributes['style'] = admonition_style attributes['name'] = admonition_name = admonition_style.downcase attributes['caption'] ||= document.attributes["#{admonition_name}-caption"] elsif quote_context = [:quote, :verse].detect{|s| attributes[1] == s.to_s} # single-paragraph verse or quote is preceded by [verse] or [quote], respectively, and lasts until a blank line AttributeList.rekey(attributes, ['style', 'attribution', 'citetitle']) reader.unshift_line this_line buffer = reader.grab_lines_until(:break_on_blank_lines => true) buffer.last.chomp! unless buffer.empty? block = Block.new(parent, quote_context, buffer) # a floating (i.e., discrete) title elsif ['float', 'discrete'].include?(attributes[1]) && is_section_title?(this_line, reader.peek_line) attributes['style'] = attributes[1] reader.unshift_line this_line float_id, float_title, float_level, _ = parse_section_title reader block = Block.new(parent, :floating_title) if float_id.nil? || float_id.empty? # FIXME remove hack of creating throwaway Section to get at the generate_id method tmp_sect = Section.new(parent) tmp_sect.title = float_title block.id = tmp_sect.generate_id else block.id = float_id @document.register(:ids, [float_id, float_title]) end block.level = float_level block.title = float_title # a paragraph - contiguous nonblank/noncontinuation lines else reader.unshift_line this_line buffer = reader.grab_lines_until(:break_on_blank_lines => true, :preserve_last_line => true, :skip_line_comments => true) {|line| is_delimited_block?(line) || line.match(REGEXP[:attr_line]) || # next list item can be directly adjacent to paragraph of previous list item context == :dlist && line.match(REGEXP[:dlist]) # not sure if there are any cases when we need this check for other list types #LIST_CONTEXTS.include?(context) && line.match(REGEXP[context]) } # NOTE we need this logic because the reader is processing line # comments and that might leave us w/ an empty buffer if buffer.empty? reader.get_line break end catalog_inline_anchors(buffer.join, document) if !options[:text] && (admonition = buffer.first.match(Regexp.new('^(' + ADMONITION_STYLES.join('|') + '):\s+'))) buffer[0] = admonition.post_match block = Block.new(parent, :admonition, buffer) attributes['style'] = admonition[1] attributes['name'] = admonition_name = admonition[1].downcase attributes['caption'] ||= document.attributes["#{admonition_name}-caption"] else buffer.last.chomp! block = Block.new(parent, :paragraph, buffer) end end end # when looking for nested content, one or more line comments, comment # blocks or trailing attribute lists could leave us without a block, # so handle accordingly if !block.nil? block.id = attributes['id'] if attributes.has_key?('id') block.title = attributes['title'] unless block.title? block.caption ||= attributes['caption'] unless block.is_a?(Section) # AsciiDoc always use [id] as the reftext in HTML output, # but I'd like to do better in Asciidoctor if block.id && block.title? && !attributes.has_key?('reftext') document.register(:ids, [block.id, block.title]) end block.update_attributes(attributes) if block.context == :listing || block.context == :literal catalog_callouts(block.buffer.join, document) end end block end # Public: Determines whether this line is the start of any of the delimited blocks # # returns the match data if this line is the first line of a delimited block or nil if not def self.is_delimited_block?(line, return_match_data = false) line_len = line.length # optimized for best performance if line_len > 2 if line_len == 3 tip = line.chop tl = 2 else tip = line[0..3] tl = 4 # special case for fenced code blocks tip_alt = tip.chop if tip_alt == '```' || tip_alt == '~~~' tip = tip_alt tl = 3 end end if DELIMITED_BLOCKS.has_key? tip # if tip is the full line if tl == line_len - 1 return_match_data ? BlockMatchData.new(DELIMITED_BLOCKS[tip], tip, tip) : true elsif match = line.match(REGEXP[:any_blk]) return_match_data ? BlockMatchData.new(DELIMITED_BLOCKS[tip], tip, match[0]) : true else nil end else nil end else nil end end # Internal: Parse and construct an outline list Block from the current position of the Reader # # reader - The Reader from which to retrieve the outline list # list_type - A Symbol representing the list type (:olist for ordered, :ulist for unordered) # parent - The parent Block to which this outline list belongs # # Returns the Block encapsulating the parsed outline (unordered or ordered) list def self.next_outline_list(reader, list_type, parent) list_block = Block.new(parent, list_type) items = [] list_block.buffer = items if parent.context == list_type list_block.level = parent.level + 1 else list_block.level = 1 end Debug.debug { "Created #{list_type} block: #{list_block}" } while reader.has_more_lines? && (match = reader.peek_line.match(REGEXP[list_type])) marker = resolve_list_marker(list_type, match[1]) # if we are moving to the next item, and the marker is different # determine if we are moving up or down in nesting if items.size > 0 && marker != items.first.marker # assume list is nested by default, but then check to see if we are # popping out of a nested list by matching an ancestor's list marker this_item_level = list_block.level + 1 p = parent while p.context == list_type if marker == p.buffer.first.marker this_item_level = p.level break end p = p.parent end else this_item_level = list_block.level end if items.size == 0 || this_item_level == list_block.level list_item = next_list_item(reader, list_block, match) elsif this_item_level < list_block.level # leave this block break elsif this_item_level > list_block.level # If this next list level is down one from the # current Block's, append it to content of the current list item items.last.blocks << next_block(reader, list_block) end items << list_item unless list_item.nil? list_item = nil reader.skip_blank_lines end list_block end # Internal: Catalog any callouts found in the text, but don't process them # # text - The String of text in which to look for callouts # document - The current document on which the callouts are stored # # Returns nothing def self.catalog_callouts(text, document) text.scan(REGEXP[:callout_scan]) { # alias match for Ruby 1.8.7 compat m = $~ next if m[0].start_with? '\\' document.callouts.register(m[1]) } end # Internal: Catalog any inline anchors found in the text, but don't process them # # text - The String text in which to look for inline anchors # document - The current document on which the references are stored # # Returns nothing def self.catalog_inline_anchors(text, document) text.scan(REGEXP[:anchor_macro]) { # alias match for Ruby 1.8.7 compat m = $~ next if m[0].start_with? '\\' id, reftext = m[1].split(',') id.sub!(/^("|)(.*)\1$/, '\2') if !reftext.nil? reftext.sub!(/^("|)(.*)\1$/m, '\2') end document.register(:ids, [id, reftext]) } nil end # Internal: Parse and construct a labeled (e.g., definition) list Block from the current position of the Reader # # reader - The Reader from which to retrieve the labeled list # match - The Regexp match for the head of the list # parent - The parent Block to which this labeled list belongs # # Returns the Block encapsulating the parsed labeled list def self.next_labeled_list(reader, match, parent) pairs = [] block = Block.new(parent, :dlist) block.buffer = pairs # allows us to capture until we find a labeled item # that uses the same delimiter (::, :::, :::: or ;;) sibling_pattern = REGEXP[:dlist_siblings][match[2]] begin pairs << next_list_item(reader, block, match, sibling_pattern) end while reader.has_more_lines? && match = reader.peek_line.match(sibling_pattern) block end # Internal: Parse and construct the next ListItem for the current bulleted # (unordered or ordered) list Block, callout lists included, or the next # term ListItem and definition ListItem pair for the labeled list Block. # # First collect and process all the lines that constitute the next list # item for the parent list (according to its type). Next, parse those lines # into blocks and associate them with the ListItem (in the case of a # labeled list, the definition ListItem). Finally, fold the first block # into the item's text attribute according to rules described in ListItem. # # reader - The Reader from which to retrieve the next list item # list_block - The parent list Block of this ListItem. Also provides access to the list type. # match - The match Array which contains the marker and text (first-line) of the ListItem # sibling_trait - The list marker or the Regexp to match a sibling item # # Returns the next ListItem or ListItem pair (depending on the list type) # for the parent list Block. def self.next_list_item(reader, list_block, match, sibling_trait = nil) list_type = list_block.context if list_type == :dlist list_term = ListItem.new(list_block, match[1]) list_item = ListItem.new(list_block, match[3]) has_text = !match[3].to_s.empty? else # Create list item using first line as the text of the list item list_item = ListItem.new(list_block, match[2]) if !sibling_trait sibling_trait = resolve_list_marker(list_type, match[1], list_block.buffer.size, true) end list_item.marker = sibling_trait has_text = true end # first skip the line with the marker / term reader.get_line list_item_reader = Reader.new grab_lines_for_list_item(reader, list_type, sibling_trait, has_text) if list_item_reader.has_more_lines? comment_lines = list_item_reader.consume_line_comments subsequent_line = list_item_reader.peek_line list_item_reader.unshift(*comment_lines) unless comment_lines.empty? if !subsequent_line.nil? continuation_connects_first_block = (subsequent_line == "\n") # if there's no continuation connecting the first block, then # treat the lines as paragraph text (activated when has_text = false) if !continuation_connects_first_block && list_type != :dlist has_text = false end content_adjacent = !subsequent_line.chomp.empty? else continuation_connects_first_block = false content_adjacent = false end # only relevant for :dlist options = {:text => !has_text} while list_item_reader.has_more_lines? new_block = next_block(list_item_reader, list_block, {}, options) list_item.blocks << new_block unless new_block.nil? end list_item.fold_first(continuation_connects_first_block, content_adjacent) end if list_type == :dlist unless list_item.text? || list_item.blocks? list_item = nil end [list_term, list_item] else list_item end end # Internal: Collect the lines belonging to the current list item, navigating # through all the rules that determine what comprises a list item. # # Grab lines until a sibling list item is found, or the block is broken by a # terminator (such as a line comment). Definition lists are more greedy if # they don't have optional inline item text...they want that text # # reader - The Reader from which to retrieve the lines. # list_type - The Symbol context of the list (:ulist, :olist, :colist or :dlist) # sibling_trait - A Regexp that matches a sibling of this list item or String list marker # of the items in this list (default: nil) # has_text - Whether the list item has text defined inline (always true except for labeled lists) # # Returns an Array of lines belonging to the current list item. def self.grab_lines_for_list_item(reader, list_type, sibling_trait = nil, has_text = true) buffer = [] # three states for continuation: :inactive, :active & :frozen # :frozen signifies we've detected sequential continuation lines & # continuation is not permitted until reset continuation = :inactive # if we are within a nested list, we don't throw away the list # continuation marks because they will be processed when grabbing # the lines for those nested lists within_nested_list = false # a detached continuation is a list continuation that follows a blank line # it gets associated with the outermost block detached_continuation = nil while reader.has_more_lines? this_line = reader.get_line # if we've arrived at a sibling item in this list, we've captured # the complete list item and can begin processing it # the remainder of the method determines whether we've reached # the termination of the list break if is_sibling_list_item?(this_line, list_type, sibling_trait) prev_line = buffer.empty? ? nil : buffer.last.chomp if prev_line == LIST_CONTINUATION if continuation == :inactive continuation = :active has_text = true buffer[buffer.size - 1] = "\n" unless within_nested_list end # dealing with adjacent list continuations (which is really a syntax error) if this_line.chomp == LIST_CONTINUATION if continuation != :frozen continuation = :frozen buffer << this_line end this_line = nil next end end # a delimited block immediately breaks the list unless preceded # by a list continuation (they are harsh like that ;0) if match = is_delimited_block?(this_line, true) if continuation == :active buffer << this_line # grab all the lines in the block, leaving the delimiters in place # we're being more strict here about the terminator, but I think that's a good thing buffer.concat reader.grab_lines_until(:terminator => match.terminator, :grab_last_line => true) continuation = :inactive else break end # technically attr_line only breaks if ensuing line is not a list item # which really means attr_line only breaks if it's acting as a block delimiter elsif list_type == :dlist && continuation != :active && this_line.match(REGEXP[:attr_line]) break else if continuation == :active && !this_line.chomp.empty? # literal paragraphs have special considerations (and this is one of # two entry points into one) # if we don't process it as a whole, then a line in it that looks like a # list item will throw off the exit from it if this_line.match(REGEXP[:lit_par]) reader.unshift_line this_line buffer.concat reader.grab_lines_until( :preserve_last_line => true, :break_on_blank_lines => true, :break_on_list_continuation => true) {|line| # we may be in an indented list disguised as a literal paragraph # so we need to make sure we don't slurp up a legitimate sibling list_type == :dlist && is_sibling_list_item?(line, list_type, sibling_trait) } continuation = :inactive # let block metadata play out until we find the block elsif this_line.match(REGEXP[:blk_title]) || this_line.match(REGEXP[:attr_line]) || this_line.match(REGEXP[:attr_entry]) buffer << this_line else if nested_list_type = (within_nested_list ? [:dlist] : NESTABLE_LIST_CONTEXTS).detect {|ctx| this_line.match(REGEXP[ctx]) } within_nested_list = true if nested_list_type == :dlist && $~[3].to_s.empty? # get greedy again has_text = false end end buffer << this_line continuation = :inactive end elsif !prev_line.nil? && prev_line.chomp.empty? # advance to the next line of content if this_line.chomp.empty? reader.skip_blank_lines this_line = reader.get_line # if we hit eof or a sibling, stop reading break if this_line.nil? || is_sibling_list_item?(this_line, list_type, sibling_trait) end if this_line.chomp == LIST_CONTINUATION detached_continuation = buffer.size buffer << this_line else # has_text is only relevant for dlist, which is more greedy until it has text for an item # for all other lists, has_text is always true # in this block, we have to see whether we stay in the list if has_text # slurp up any literal paragraph offset by blank lines if this_line.match(REGEXP[:lit_par]) reader.unshift_line this_line buffer.concat reader.grab_lines_until( :preserve_last_line => true, :break_on_blank_lines => true, :break_on_list_continuation => true) {|line| # we may be in an indented list disguised as a literal paragraph # so we need to make sure we don't slurp up a legitimate sibling list_type == :dlist && is_sibling_list_item?(line, list_type, sibling_trait) } # TODO any way to combine this with the check after skipping blank lines? elsif is_sibling_list_item?(this_line, list_type, sibling_trait) break elsif nested_list_type = NESTABLE_LIST_CONTEXTS.detect {|ctx| this_line.match(REGEXP[ctx]) } buffer << this_line within_nested_list = true if nested_list_type == :dlist && $~[3].to_s.empty? # get greedy again has_text = false end else break end else # only dlist in need of item text, so slurp it up! # pop the blank line so it's not interpretted as a list continuation buffer.pop unless within_nested_list buffer << this_line has_text = true end end else has_text = true if !this_line.chomp.empty? if nested_list_type = (within_nested_list ? [:dlist] : NESTABLE_LIST_CONTEXTS).detect {|ctx| this_line.match(REGEXP[ctx]) } within_nested_list = true if nested_list_type == :dlist && $~[3].to_s.empty? # get greedy again has_text = false end end buffer << this_line end end this_line = nil end reader.unshift_line this_line if !this_line.nil? if detached_continuation buffer.delete_at detached_continuation end # strip trailing blank lines to prevent empty blocks buffer.pop while !buffer.empty? && buffer.last.chomp.empty? # We do need to replace the optional trailing continuation # a blank line would have served the same purpose in the document if !buffer.empty? && buffer.last.chomp == LIST_CONTINUATION buffer.pop end #puts "BUFFER[#{list_type},#{sibling_trait}]>#{buffer.join}<BUFFER" #puts "BUFFER[#{list_type},#{sibling_trait}]>#{buffer}<BUFFER" buffer end # Internal: Initialize a new Section object and assign any attributes provided # # The information for this section is retrieved by parsing the lines at the # current position of the reader. # # reader - the source reader # parent - the parent Section or Document of this Section # attributes - a Hash of attributes to assign to this section (default: {}) def self.initialize_section(reader, parent, attributes = {}) section = Section.new parent section.id, section.title, section.level, _ = parse_section_title(reader) if section.id.nil? && attributes.has_key?('id') section.id = attributes['id'] else # generate an id if one was not *embedded* in the heading line # or as an anchor above the section section.id ||= section.generate_id end if attributes[1] section.sectname = attributes[1] section.special = true document = parent.document if section.sectname == 'appendix' && !attributes.has_key?('caption') && !document.attributes.has_key?('caption') number = document.counter('appendix-number', 'A') attributes['caption'] = "#{document.attributes['appendix-caption']} #{number}: " Document::AttributeEntry.new('appendix-number', number).save_to(attributes) end else section.sectname = "sect#{section.level}" end section.update_attributes(attributes) reader.skip_blank_lines section end # Private: Get the Integer section level based on the characters # used in the ASCII line under the section title. # # line - the String line from under the section title. def self.section_level(line) char = line.chomp.chars.to_a.uniq case char when ['=']; 0 when ['-']; 1 when ['~']; 2 when ['^']; 3 when ['+']; 4 end end #-- # = is level 0, == is level 1, etc. def self.single_line_section_level(line) [line.length - 1, 0].max end # Internal: Checks if the next line on the Reader is a section title # # reader - the source Reader # attributes - a Hash of attributes collected above the current line # # returns the section level if the Reader is positioned at a section title, # false otherwise def self.is_next_line_section?(reader, attributes) return false if !attributes[1].nil? && ['float', 'discrete'].include?(attributes[1]) return false if !reader.has_more_lines? is_section_title?(*reader.peek_lines(2)) end # Internal: Convenience API for checking if the next line on the Reader is the document title # # reader - the source Reader # attributes - a Hash of attributes collected above the current line # # returns true if the Reader is positioned at the document title, false otherwise def self.is_next_line_document_title?(reader, attributes) is_next_line_section?(reader, attributes) == 0 end # Public: Checks if these lines are a section title # # line1 - the first line as a String # line2 - the second line as a String (default: nil) # # returns the section level if these lines are a section title, # false otherwise def self.is_section_title?(line1, line2 = nil) if (level = is_single_line_section_title?(line1)) level elsif (level = is_two_line_section_title?(line1, line2)) level else false end end def self.is_single_line_section_title?(line1) if !line1.nil? && (match = line1.match(REGEXP[:section_title])) single_line_section_level match[1] else false end end def self.is_two_line_section_title?(line1, line2) if !line1.nil? && !line2.nil? && line1.match(REGEXP[:section_name]) && line2.match(REGEXP[:section_underline]) && # chomp so that a (non-visible) endline does not impact calculation (line1.chomp.size - line2.chomp.size).abs <= 1 section_level line2 else false end end # Internal: Parse the section title from the current position of the reader # # Parse a single or double-line section title. After this method is called, # the Reader will be positioned at the line after the section title. # # reader - the source reader, positioned at a section title # # Examples # # reader.lines # # => ["Foo\n", "~~~\n"] # # title, level, id, single = parse_section_title(reader) # # title # # => "Foo" # level # # => 2 # id # # => nil # single # # => false # # line1 # # => "==== Foo\n" # # title, level, id, single = parse_section_title(reader) # # title # # => "Foo" # level # # => 3 # id # # => nil # single # # => true # # returns an Array of [String, Integer, String, Boolean], representing the # id, title, level and line count of the Section, or nil. # #-- # NOTE for efficiency, we don't reuse methods that check for a section title def self.parse_section_title(reader) line1 = reader.get_line sect_id = nil sect_title = nil sect_level = -1 single_line = true if match = line1.match(REGEXP[:section_title]) sect_id = match[3] sect_title = match[2] sect_level = single_line_section_level match[1] else line2 = reader.peek_line if !line2.nil? && (name_match = line1.match(REGEXP[:section_name])) && line2.match(REGEXP[:section_underline]) && # chomp so that a (non-visible) endline does not impact calculation (line1.chomp.size - line2.chomp.size).abs <= 1 if anchor_match = name_match[1].match(REGEXP[:anchor_embedded]) sect_id = anchor_match[2] sect_title = anchor_match[1] else sect_title = name_match[1] end sect_level = section_level line2 single_line = false reader.get_line end end return [sect_id, sect_title, sect_level, single_line] end # Public: Consume and parse the two header lines (line 1 = author info, line 2 = revision info). # # Returns the Hash of header metadata. If a Document object is supplied, the metadata # is applied directly to the attributes of the Document. # # reader - the Reader holding the source lines of the document # document - the Document we are building (default: nil) # # Examples # # parse_header_metadata(Reader.new ["<NAME> <<EMAIL>>\n", "v1.0, 2012-12-21: Coincide w/ end of world.\n"]) # # => {'author' => '<NAME>', 'firstname' => 'Author', 'lastname' => 'Name', 'email' => '<EMAIL>', # # 'revnumber' => '1.0', 'revdate' => '2012-12-21', 'revremark' => 'Coincide w/ end of world.'} def self.parse_header_metadata(reader, document = nil) # NOTE this will discard away any comment lines, but not skip blank lines process_attribute_entries(reader, document) metadata = {} if reader.has_more_lines? && !reader.peek_line.chomp.empty? author_line = reader.get_line if match = author_line.match(REGEXP[:author_info]) metadata['firstname'] = fname = match[1].tr('_', ' ') metadata['author'] = fname metadata['authorinitials'] = fname[0, 1] if !match[2].nil? && !match[3].nil? metadata['middlename'] = mname = match[2].tr('_', ' ') metadata['lastname'] = lname = match[3].tr('_', ' ') metadata['author'] = [fname, mname, lname].join ' ' metadata['authorinitials'] = [fname[0, 1], mname[0, 1], lname[0, 1]].join elsif !match[2].nil? metadata['lastname'] = lname = match[2].tr('_', ' ') metadata['author'] = [fname, lname].join ' ' metadata['authorinitials'] = [fname[0, 1], lname[0, 1]].join end metadata['email'] = match[4] unless match[4].nil? else metadata['author'] = metadata['firstname'] = author_line.strip.squeeze(' ') metadata['authorinitials'] = metadata['firstname'][0, 1] end # NOTE this will discard away any comment lines, but not skip blank lines process_attribute_entries(reader, document) if reader.has_more_lines? && !reader.peek_line.chomp.empty? rev_line = reader.get_line if match = rev_line.match(REGEXP[:revision_info]) metadata['revdate'] = match[2].strip metadata['revnumber'] = match[1].rstrip unless match[1].nil? metadata['revremark'] = match[3].rstrip unless match[3].nil? else # throw it back reader.unshift_line rev_line end end # NOTE this will discard away any comment lines, but not skip blank lines process_attribute_entries(reader, document) reader.skip_blank_lines # apply header subs and assign to document if !document.nil? metadata.map do |key, val| val = document.apply_header_subs(val) document.attributes[key] = val if !document.attributes.has_key?(key) val end end end metadata end # Internal: Parse lines of metadata until a line of metadata is not found. # # This method processes sequential lines containing block metadata, ignoring # blank lines and comments. # # reader - the source reader # parent - the parent to which the lines belong # attributes - a Hash of attributes in which any metadata found will be stored (default: {}) # options - a Hash of options to control processing: (default: {}) # * :text indicates that lexer is only looking for text content # and thus the block title should not be captured # # returns the Hash of attributes including any metadata found def self.parse_block_metadata_lines(reader, parent, attributes = {}, options = {}) while parse_block_metadata_line(reader, parent, attributes, options) # discard the line just processed reader.advance reader.skip_blank_lines end attributes end # Internal: Parse the next line if it contains metadata for the following block # # This method handles lines with the following content: # # * line or block comment # * anchor # * attribute list # * block title # # Any attributes found will be inserted into the attributes argument. # If the line contains block metadata, the method returns true, otherwise false. # # reader - the source reader # parent - the parent of the current line # attributes - a Hash of attributes in which any metadata found will be stored # options - a Hash of options to control processing: (default: {}) # * :text indicates that lexer is only looking for text content # and thus the block title should not be captured # # returns true if the line contains metadata, otherwise false def self.parse_block_metadata_line(reader, parent, attributes, options = {}) return false if !reader.has_more_lines? next_line = reader.peek_line if (commentish = next_line.start_with?('//')) && (match = next_line.match(REGEXP[:comment_blk])) terminator = match[0] reader.grab_lines_until(:skip_first_line => true, :preserve_last_line => true, :terminator => terminator, :preprocess => false) elsif commentish && next_line.match(REGEXP[:comment]) # do nothing, we'll skip it elsif !options[:text] && (match = next_line.match(REGEXP[:attr_entry])) process_attribute_entry(reader, parent, attributes, match) elsif match = next_line.match(REGEXP[:anchor]) id, reftext = match[1].split(',') attributes['id'] = id # AsciiDoc always use [id] as the reftext in HTML output, # but I'd like to do better in Asciidoctor #parent.document.register(:ids, id) if reftext attributes['reftext'] = reftext parent.document.register(:ids, [id, reftext]) end elsif match = next_line.match(REGEXP[:blk_attr_list]) AttributeList.new(parent.document.sub_attributes(match[1]), parent.document).parse_into(attributes) # NOTE title doesn't apply to section, but we need to stash it for the first block # TODO should issue an error if this is found above the document title elsif !options[:text] && (match = next_line.match(REGEXP[:blk_title])) attributes['title'] = match[1] else return false end true end def self.process_attribute_entries(reader, parent, attributes = nil) reader.skip_comment_lines while process_attribute_entry(reader, parent, attributes) # discard line just processed reader.advance reader.skip_comment_lines end end def self.process_attribute_entry(reader, parent, attributes = nil, match = nil) match ||= reader.has_more_lines? ? reader.peek_line.match(REGEXP[:attr_entry]) : nil if match name = match[1] value = match[2].nil? ? '' : match[2] if value.end_with? LINE_BREAK value.chop!.rstrip! while reader.advance next_line = reader.peek_line.strip break if next_line.empty? if next_line.end_with? LINE_BREAK value = "#{value} #{next_line.chop.rstrip}" else value = "#{value} #{next_line}" break end end end if name.end_with?('!') # a nil value signals the attribute should be deleted (undefined) value = nil name = name.chop end name = sanitize_attribute_name(name) accessible = true if !parent.nil? accessible = value.nil? ? parent.document.delete_attribute(name) : parent.document.set_attribute(name, value) end if !attributes.nil? Document::AttributeEntry.new(name, value).save_to(attributes) if accessible end true else false end end # Internal: Resolve the 0-index marker for this list item # # For ordered lists, match the marker used for this list item against the # known list markers and determine which marker is the first (0-index) marker # in its number series. # # For callout lists, return <1>. # # For bulleted lists, return the marker as passed to this method. # # list_type - The Symbol context of the list # marker - The String marker for this list item # ordinal - The position of this list item in the list # validate - Whether to validate the value of the marker # # Returns the String 0-index marker for this list item def self.resolve_list_marker(list_type, marker, ordinal = 0, validate = false) if list_type == :olist && !marker.start_with?('.') resolve_ordered_list_marker(marker, ordinal, validate) elsif list_type == :colist '<1>' else marker end end # Internal: Resolve the 0-index marker for this ordered list item # # Match the marker used for this ordered list item against the # known ordered list markers and determine which marker is # the first (0-index) marker in its number series. # # The purpose of this method is to normalize the implicit numbered markers # so that they can be compared against other list items. # # marker - The marker used for this list item # ordinal - The 0-based index of the list item (default: 0) # validate - Perform validation that the marker provided is the proper # marker in the sequence (default: false) # # Examples # # marker = 'B.' # Lexer::resolve_ordered_list_marker(marker, 1, true) # # => 'A.' # # Returns the String of the first marker in this number series def self.resolve_ordered_list_marker(marker, ordinal = 0, validate = false) number_style = ORDERED_LIST_STYLES.detect {|s| marker.match(ORDERED_LIST_MARKER_PATTERNS[s]) } expected = actual = nil case number_style when :arabic if validate expected = ordinal + 1 actual = marker.to_i end marker = '1.' when :loweralpha if validate expected = ('a'[0].ord + ordinal).chr actual = marker.chomp('.') end marker = 'a.' when :upperalpha if validate expected = ('A'[0].ord + ordinal).chr actual = marker.chomp('.') end marker = 'A.' when :lowerroman if validate # TODO report this in roman numerals; see https://github.com/jamesshipton/roman-numeral/blob/master/lib/roman_numeral.rb expected = ordinal + 1 actual = roman_numeral_to_int(marker.chomp(')')) end marker = 'i)' when :upperroman if validate # TODO report this in roman numerals; see https://github.com/jamesshipton/roman-numeral/blob/master/lib/roman_numeral.rb expected = ordinal + 1 actual = roman_numeral_to_int(marker.chomp(')')) end marker = 'I)' end if validate && expected != actual # FIXME I need a reader reference or line number to report line number puts "asciidoctor: WARNING: list item index: expected #{expected}, got #{actual}" end marker end # Internal: Determine whether the this line is a sibling list item # according to the list type and trait (marker) provided. # # line - The String line to check # list_type - The context of the list (:olist, :ulist, :colist, :dlist) # sibling_trait - The String marker for the list or the Regexp to match a sibling # # Returns a Boolean indicating whether this line is a sibling list item given # the criteria provided def self.is_sibling_list_item?(line, list_type, sibling_trait) if sibling_trait.is_a?(Regexp) matcher = sibling_trait expected_marker = false else matcher = REGEXP[list_type] expected_marker = sibling_trait end if m = line.match(matcher) if expected_marker expected_marker == resolve_list_marker(list_type, m[1]) else true end else false end end # Internal: Parse the table contained in the provided Reader # # table_reader - a Reader containing the source lines of an AsciiDoc table # parent - the parent Block of this Asciidoctor::Table # attributes - attributes captured from above this Block # # returns an instance of Asciidoctor::Table parsed from the provided reader def self.next_table(table_reader, parent, attributes) table = Table.new(parent, attributes) if attributes.has_key? 'cols' table.create_columns(parse_col_specs(attributes['cols'])) explicit_col_specs = true else explicit_col_specs = false end table_reader.skip_blank_lines parser_ctx = Table::ParserContext.new(table, attributes) while table_reader.has_more_lines? line = table_reader.get_line if parser_ctx.format == 'psv' if parser_ctx.starts_with_delimiter? line line = line[1..-1] # push an empty cell spec if boundary at start of line parser_ctx.close_open_cell else next_cell_spec, line = parse_cell_spec(line, :start) # if the cell spec is not null, then we're at a cell boundary if !next_cell_spec.nil? parser_ctx.close_open_cell next_cell_spec else # QUESTION do we not advance to next line? if so, when # will we if we came into this block? end end end while !line.empty? if m = parser_ctx.match_delimiter(line) if parser_ctx.format == 'csv' if parser_ctx.buffer_has_unclosed_quotes?(m.pre_match) # throw it back, it's too small line = parser_ctx.skip_matched_delimiter(m) next end else if m.pre_match.end_with? '\\' line = parser_ctx.skip_matched_delimiter(m, true) next end end if parser_ctx.format == 'psv' next_cell_spec, cell_text = parse_cell_spec(m.pre_match, :end) parser_ctx.push_cell_spec next_cell_spec parser_ctx.buffer << cell_text else parser_ctx.buffer << m.pre_match end line = m.post_match parser_ctx.close_cell else # no other delimiters to see here # suck up this line into the buffer and move on parser_ctx.buffer << line # QUESTION make this an option? (unwrap-option?) if parser_ctx.format == 'csv' parser_ctx.buffer.rstrip!.concat(' ') end line = '' if parser_ctx.format == 'psv' || (parser_ctx.format == 'csv' && parser_ctx.buffer_has_unclosed_quotes?) parser_ctx.keep_cell_open else parser_ctx.close_cell true end end end table_reader.skip_blank_lines unless parser_ctx.cell_open? if !table_reader.has_more_lines? parser_ctx.close_cell true end end table.attributes['colcount'] ||= parser_ctx.col_count if !explicit_col_specs # TODO further encapsulate this logic (into table perhaps?) even_width = (100.0 / parser_ctx.col_count).floor table.columns.each {|c| c.assign_width(0, even_width) } end table.partition_header_footer attributes table end # Internal: Parse the column specs for this table. # # The column specs dictate the number of columns, relative # width of columns, default alignments for cells in each # column, and/or default styles or filters applied to the cells in # the column. # # Every column spec is guaranteed to have a width # # returns a Hash of attributes that specify how to format # and layout the cells in the table. def self.parse_col_specs(records) specs = [] # check for deprecated syntax if m = records.match(REGEXP[:digits]) 1.upto(m[0].to_i) { specs << {'width' => 1} } return specs end records.split(',').each {|record| # TODO might want to use scan rather than this mega-regexp if m = record.match(REGEXP[:table_colspec]) spec = {} if m[2] # make this an operation colspec, rowspec = m[2].split '.' if !colspec.to_s.empty? && Table::ALIGNMENTS[:h].has_key?(colspec) spec['halign'] = Table::ALIGNMENTS[:h][colspec] end if !rowspec.to_s.empty? && Table::ALIGNMENTS[:v].has_key?(rowspec) spec['valign'] = Table::ALIGNMENTS[:v][rowspec] end end # TODO support percentage width spec['width'] = !m[3].nil? ? m[3].to_i : 1 # make this an operation if m[4] && Table::TEXT_STYLES.has_key?(m[4]) spec['style'] = Table::TEXT_STYLES[m[4]] end repeat = !m[1].nil? ? m[1].to_i : 1 1.upto(repeat) { specs << spec.dup } end } specs end # Internal: Parse the cell specs for the current cell. # # The cell specs dictate the cell's alignments, styles or filters, # colspan, rowspan and/or repeating content. # # returns the Hash of attributes that indicate how to layout # and style this cell in the table. def self.parse_cell_spec(line, pos = :start) # the default for the end pos it {} since we # know we're at a delimiter; when the pos # is start, we *may* be at a delimiter and # nil indicates we're not spec = (pos == :end ? {} : nil) rest = line if m = line.match(REGEXP[:table_cellspec][pos]) spec = {} return [spec, line] if m[0].chomp.empty? rest = (pos == :start ? m.post_match : m.pre_match) if m[1] colspec, rowspec = m[1].split '.' colspec = colspec.to_s.empty? ? 1 : colspec.to_i rowspec = rowspec.to_s.empty? ? 1 : rowspec.to_i if m[2] == '+' spec['colspan'] = colspec unless colspec == 1 spec['rowspan'] = rowspec unless rowspec == 1 elsif m[2] == '*' spec['repeatcol'] = colspec unless colspec == 1 end end if m[3] colspec, rowspec = m[3].split '.' if !colspec.to_s.empty? && Table::ALIGNMENTS[:h].has_key?(colspec) spec['halign'] = Table::ALIGNMENTS[:h][colspec] end if !rowspec.to_s.empty? && Table::ALIGNMENTS[:v].has_key?(rowspec) spec['valign'] = Table::ALIGNMENTS[:v][rowspec] end end if m[4] && Table::TEXT_STYLES.has_key?(m[4]) spec['style'] = Table::TEXT_STYLES[m[4]] end end [spec, rest] end # Public: Convert a string to a legal attribute name. # # name - the String name of the attribute # # Returns a String with the legal AsciiDoc attribute name. # # Examples # # sanitize_attribute_name('Foo Bar') # => 'foobar' # # sanitize_attribute_name('foo') # => 'foo' # # sanitize_attribute_name('Foo 3 #-Billy') # => 'foo3-billy' def self.sanitize_attribute_name(name) name.gsub(REGEXP[:illegal_attr_name_chars], '').downcase end # Internal: Converts a Roman numeral to an integer value. # # value - The String Roman numeral to convert # # Returns the Integer for this Roman numeral def self.roman_numeral_to_int(value) value = value.downcase digits = { 'i' => 1, 'v' => 5, 'x' => 10 } result = 0 (0..value.length - 1).each {|i| digit = digits[value[i..i]] if i + 1 < value.length && digits[value[i+1..i+1]] > digit result -= digit else result += digit end } result end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/execute_asciidoctor.rb
require 'bundler/setup' require 'asciidoctor' Dir.glob("#{$srcDir}/**/*.a*").each do |path| if path =~ /.*\.a((sc(iidoc)?)|d(oc)?)$/ Asciidoctor.render_file(path, {:in_place => false, :safe => Asciidoctor::SafeMode::UNSAFE, :attributes => {'backend' => $backend}, :to_dir => $outputDir}) end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/document_test.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin require 'test_helper' context 'Document' do context 'Example document' do test 'document title' do doc = example_document(:asciidoc_index) assert_equal 'AsciiDoc Home Page', doc.doctitle assert_equal 'AsciiDoc Home Page', doc.name assert_equal 14, doc.blocks.size assert_equal :preamble, doc.blocks[0].context assert doc.blocks[1].is_a? ::Asciidoctor::Section end end context 'Default settings' do test 'safe mode level set to SECURE by default' do doc = Asciidoctor::Document.new assert_equal Asciidoctor::SafeMode::SECURE, doc.safe end test 'safe mode level can be set in the constructor' do doc = Asciidoctor::Document.new [], :safe => Asciidoctor::SafeMode::SAFE assert_equal Asciidoctor::SafeMode::SAFE, doc.safe end test 'safe model level cannot be modified' do doc = Asciidoctor::Document.new begin doc.safe = Asciidoctor::SafeMode::UNSAFE flunk 'safe mode property of Asciidoctor::Document should not be writable!' rescue end end end context 'Load APIs' do test 'should load input file' do sample_input_path = fixture_path('sample.asciidoc') doc = Asciidoctor.load(File.new(sample_input_path), :safe => Asciidoctor::SafeMode::SAFE) assert_equal 'Document Title', doc.doctitle assert_equal File.expand_path(sample_input_path), doc.attr('docfile') assert_equal File.expand_path(File.dirname(sample_input_path)), doc.attr('docdir') end test 'should load input file from filename' do sample_input_path = fixture_path('sample.asciidoc') doc = Asciidoctor.load_file(sample_input_path, :safe => Asciidoctor::SafeMode::SAFE) assert_equal 'Document Title', doc.doctitle assert_equal File.expand_path(sample_input_path), doc.attr('docfile') assert_equal File.expand_path(File.dirname(sample_input_path)), doc.attr('docdir') end test 'should load input IO' do input = StringIO.new(<<-EOS) Document Title ============== preamble EOS doc = Asciidoctor.load(input, :safe => Asciidoctor::SafeMode::SAFE) assert_equal 'Document Title', doc.doctitle assert !doc.attr?('docfile') assert_equal doc.base_dir, doc.attr('docdir') end test 'should load input string' do input = <<-EOS Document Title ============== preamble EOS doc = Asciidoctor.load(input, :safe => Asciidoctor::SafeMode::SAFE) assert_equal 'Document Title', doc.doctitle assert !doc.attr?('docfile') assert_equal doc.base_dir, doc.attr('docdir') end test 'should load input string array' do input = <<-EOS Document Title ============== preamble EOS doc = Asciidoctor.load(input.lines.entries, :safe => Asciidoctor::SafeMode::SAFE) assert_equal 'Document Title', doc.doctitle assert !doc.attr?('docfile') assert_equal doc.base_dir, doc.attr('docdir') end end context 'Render APIs' do test 'should render document to string' do sample_input_path = fixture_path('sample.asciidoc') output = Asciidoctor.render_file(sample_input_path, :header_footer => true) assert !output.empty? assert_xpath '/html', output, 1 assert_xpath '/html/head', output, 1 assert_xpath '/html/body', output, 1 assert_xpath '/html/head/title[text() = "Document Title"]', output, 1 assert_xpath '/html/body/*[@id="header"]/h1[text() = "Document Title"]', output, 1 end test 'should render document in place' do sample_input_path = fixture_path('sample.asciidoc') sample_output_path = fixture_path('sample.html') begin Asciidoctor.render_file(sample_input_path, :in_place => true) assert File.exist?(sample_output_path) output = File.read(sample_output_path) assert !output.empty? assert_xpath '/html', output, 1 assert_xpath '/html/head', output, 1 assert_xpath '/html/body', output, 1 assert_xpath '/html/head/title[text() = "Document Title"]', output, 1 assert_xpath '/html/body/*[@id="header"]/h1[text() = "Document Title"]', output, 1 ensure FileUtils::rm(sample_output_path) end end test 'should render document to file' do sample_input_path = fixture_path('sample.asciidoc') sample_output_path = fixture_path('result.html') begin Asciidoctor.render_file(sample_input_path, :to_file => sample_output_path) assert File.exist?(sample_output_path) output = File.read(sample_output_path) assert !output.empty? assert_xpath '/html', output, 1 assert_xpath '/html/head', output, 1 assert_xpath '/html/body', output, 1 assert_xpath '/html/head/title[text() = "Document Title"]', output, 1 assert_xpath '/html/body/*[@id="header"]/h1[text() = "Document Title"]', output, 1 ensure FileUtils::rm(sample_output_path) end end test 'in_place option must not be used with to_file option' do sample_input_path = fixture_path('sample.asciidoc') sample_output_path = fixture_path('result.html') assert_raise ArgumentError do begin Asciidoctor.render_file(sample_input_path, :to_file => sample_output_path, :in_place => true) ensure FileUtils::rm(sample_output_path) if File.exists? sample_output_path end end end test 'in_place option must not be used with to_dir option' do sample_input_path = fixture_path('sample.asciidoc') sample_output_path = fixture_path('result.html') assert_raise ArgumentError do begin Asciidoctor.render_file(sample_input_path, :to_dir => '', :in_place => true) ensure FileUtils::rm(sample_output_path) if File.exists? sample_output_path end end end test 'output should be relative to to_dir option' do sample_input_path = fixture_path('sample.asciidoc') output_dir = File.join(File.dirname(sample_input_path), 'test_output') Dir.mkdir output_dir if !File.exists? output_dir sample_output_path = File.join(output_dir, 'sample.html') begin Asciidoctor.render_file(sample_input_path, :to_dir => output_dir) assert File.exists? sample_output_path ensure FileUtils::rm(sample_output_path) if File.exists? sample_output_path FileUtils::rmdir output_dir end end test 'missing directories should be created if specified' do sample_input_path = fixture_path('sample.asciidoc') output_dir = File.join(File.join(File.dirname(sample_input_path), 'test_output'), 'subdir') sample_output_path = File.join(output_dir, 'sample.html') begin Asciidoctor.render_file(sample_input_path, :to_dir => output_dir, :mkdirs => true) assert File.exists? sample_output_path ensure FileUtils::rm(sample_output_path) if File.exists? sample_output_path FileUtils::rmdir output_dir FileUtils::rmdir File.dirname(output_dir) end end test 'to_file should be relative to to_dir when both given' do sample_input_path = fixture_path('sample.asciidoc') base_dir = File.dirname(sample_input_path) sample_rel_output_path = File.join('test_output', 'result.html') output_dir = File.dirname(File.join(base_dir, sample_rel_output_path)) Dir.mkdir output_dir if !File.exists? output_dir sample_output_path = File.join(base_dir, sample_rel_output_path) begin Asciidoctor.render_file(sample_input_path, :to_dir => base_dir, :to_file => sample_rel_output_path) assert File.exists? sample_output_path ensure FileUtils::rm(sample_output_path) if File.exists? sample_output_path FileUtils::rmdir output_dir end end end context 'Renderer' do test 'built-in HTML5 views are registered by default' do doc = document_from_string '' assert_equal 'html5', doc.attributes['backend'] assert doc.attributes.has_key? 'backend-html5' assert_equal 'html', doc.attributes['basebackend'] assert doc.attributes.has_key? 'basebackend-html' renderer = doc.renderer assert !renderer.nil? views = renderer.views assert !views.nil? assert_equal 30, views.size assert views.has_key? 'document' assert views['document'].is_a?(Asciidoctor::HTML5::DocumentTemplate) assert_equal 'ERB', views['document'].eruby.to_s end test 'built-in DocBook45 views are registered when backend is docbook45' do doc = document_from_string '', :attributes => {'backend' => 'docbook45'} renderer = doc.renderer assert_equal 'docbook45', doc.attributes['backend'] assert doc.attributes.has_key? 'backend-docbook45' assert_equal 'docbook', doc.attributes['basebackend'] assert doc.attributes.has_key? 'basebackend-docbook' assert !renderer.nil? views = renderer.views assert !views.nil? assert_equal 30, views.size assert views.has_key? 'document' assert views['document'].is_a?(Asciidoctor::DocBook45::DocumentTemplate) assert_equal 'ERB', views['document'].eruby.to_s end test 'can set erubis as eRuby implementation' do doc = Asciidoctor::Document.new [], :eruby => 'erubis', :header_footer => true assert $LOADED_FEATURES.detect {|p| p == 'erubis.rb' || p.end_with?('/erubis.rb') }.nil? renderer = doc.renderer assert $LOADED_FEATURES.detect {|p| p == 'erubis.rb' || p.end_with?('/erubis.rb') } views = renderer.views assert !views.nil? assert views.has_key? 'document' assert_equal 'Erubis::FastEruby', views['document'].eruby.to_s assert_equal 'Erubis::FastEruby', views['document'].template.class.to_s end end context 'Structure' do test 'document with no doctitle' do doc = document_from_string('Snorf') assert_nil doc.doctitle assert_nil doc.name assert !doc.has_header? assert_nil doc.header end test 'document with doctitle defined as attribute entry' do input = <<-EOS :doctitle: Document Title preamble == First Section EOS doc = document_from_string input assert_equal 'Document Title', doc.doctitle assert doc.has_header? assert_equal 'Document Title', doc.header.title assert_equal 'Document Title', doc.first_section.title end test 'document with title attribute entry overrides doctitle' do input = <<-EOS = Title :title: Document Title preamble == First Section EOS doc = document_from_string input assert_equal 'Document Title', doc.doctitle assert_equal 'Document Title', doc.title assert doc.has_header? assert_equal 'Title', doc.header.title assert_equal 'Title', doc.first_section.title end test 'document with doctitle attribute entry overrides header title and doctitle' do input = <<-EOS = Title :doctitle: Override preamble == First Section EOS doc = document_from_string input assert_equal 'Override', doc.doctitle assert_nil doc.title assert doc.has_header? assert_equal 'Override', doc.header.title assert_equal 'Override', doc.first_section.title end test 'should recognize document title when preceded by blank lines' do input = <<-EOS :doctype: book = Title preamble == Section 1 text EOS output = render_string input, :safe => Asciidoctor::SafeMode::SAFE assert_css '#header h1', output, 1 assert_css '#content h1', output, 0 end test 'should not choke on empty source' do doc = Asciidoctor::Document.new '' assert doc.blocks.empty? assert_nil doc.doctitle assert !doc.has_header? assert_nil doc.header end test 'should not choke on nil source' do doc = Asciidoctor::Document.new nil assert doc.blocks.empty? assert_nil doc.doctitle assert !doc.has_header? assert_nil doc.header end test 'with metadata' do input = <<-EOS = AsciiDoc <NAME> <<EMAIL>> v8.6.8, 2012-07-12: See changelog. == Version 8.6.8 more info... EOS output = render_string input assert_xpath '//*[@id="header"]/span[@id="author"][text() = "<NAME>"]', output, 1 assert_xpath '//*[@id="header"]/span[@id="email"][contains(text(), "<EMAIL>")]', output, 1 assert_xpath '//*[@id="header"]/span[@id="revnumber"][text() = "version 8.6.8,"]', output, 1 assert_xpath '//*[@id="header"]/span[@id="revdate"][text() = "2012-07-12"]', output, 1 assert_xpath '//*[@id="header"]/span[@id="revremark"][text() = "See changelog."]', output, 1 end test 'with header footer' do result = render_string("= Title\n\npreamble") assert_xpath '/html', result, 1 assert_xpath '//*[@id="header"]', result, 1 assert_xpath '//*[@id="header"]/h1', result, 1 assert_xpath '//*[@id="footer"]', result, 1 assert_xpath '//*[@id="preamble"]', result, 1 end test 'no header footer' do result = render_string("= Title\n\npreamble", :header_footer => false) assert_xpath '/html', result, 0 assert_xpath '/h1', result, 0 assert_xpath '/*[@id="header"]', result, 0 assert_xpath '/*[@id="footer"]', result, 0 assert_xpath '/*[@id="preamble"]', result, 1 end test 'wip enable title when no header footer' do result = render_string("= Title\n\npreamble", :header_footer => false, :attributes => {'notitle!' => ''}) assert_xpath '/html', result, 0 assert_xpath '/h1', result, 1 assert_xpath '/*[@id="header"]', result, 0 assert_xpath '/*[@id="footer"]', result, 0 assert_xpath '/*[@id="preamble"]', result, 1 assert_xpath '(/*)[1]/self::h1', result, 1 assert_xpath '(/*)[2]/self::*[@id="preamble"]', result, 1 end test 'parse header only' do input = <<-EOS = Document Title Author Name :foo: bar preamble EOS doc = document_from_string input, :parse_header_only => true assert_equal 'Document Title', doc.doctitle assert_equal 'Author Name', doc.author assert_equal 'bar', doc.attributes['foo'] # there would be at least 1 block had it parsed beyond the header assert_equal 0, doc.blocks.size end test 'renders footnotes in footer' do input = <<-EOS A footnote footnote:[An example footnote.]; a second footnote with a reference ID footnoteref:[note2,Second footnote.]; finally a reference to the second footnote footnoteref:[note2]. EOS output = render_string input assert_css '#footnotes', output, 1 assert_css '#footnotes .footnote', output, 2 assert_css '#footnotes .footnote#_footnote_1', output, 1 assert_xpath '//div[@id="footnotes"]/div[@id="_footnote_1"]/a[@href="#_footnoteref_1"][text()="1"]', output, 1 text = xmlnodes_at_xpath '//div[@id="footnotes"]/div[@id="_footnote_1"]/text()', output, 1 assert_equal '. An example footnote.', text.text.strip assert_css '#footnotes .footnote#_footnote_2', output, 1 assert_xpath '//div[@id="footnotes"]/div[@id="_footnote_2"]/a[@href="#_footnoteref_2"][text()="2"]', output, 1 text = xmlnodes_at_xpath '//div[@id="footnotes"]/div[@id="_footnote_2"]/text()', output, 1 assert_equal '. Second footnote.', text.text.strip end end context 'Backends and Doctypes' do test 'html5 backend doctype article' do result = render_string("= Title\n\npreamble", :attributes => {'backend' => 'html5'}) assert_xpath '/html', result, 1 assert_xpath '/html/body[@class="article"]', result, 1 assert_xpath '/html//*[@id="header"]/h1[text() = "Title"]', result, 1 assert_xpath '/html//*[@id="preamble"]//p[text() = "preamble"]', result, 1 end test 'html5 backend doctype book' do result = render_string("= Title\n\npreamble", :attributes => {'backend' => 'html5', 'doctype' => 'book'}) assert_xpath '/html', result, 1 assert_xpath '/html/body[@class="book"]', result, 1 assert_xpath '/html//*[@id="header"]/h1[text() = "Title"]', result, 1 assert_xpath '/html//*[@id="preamble"]//p[text() = "preamble"]', result, 1 end test 'docbook45 backend doctype article' do input = <<-EOS = Title preamble == First Section section body EOS result = render_string(input, :attributes => {'backend' => 'docbook45'}) assert_xpath '/article', result, 1 assert_xpath '/article/articleinfo/title[text() = "Title"]', result, 1 assert_xpath '/article/simpara[text() = "preamble"]', result, 1 assert_xpath '/article/section', result, 1 assert_xpath '/article/section[@id = "_first_section"]/title[text() = "First Section"]', result, 1 assert_xpath '/article/section[@id = "_first_section"]/simpara[text() = "section body"]', result, 1 end test 'docbook45 backend doctype article no title' do result = render_string('text', :attributes => {'backend' => 'docbook45'}) assert_xpath '/article', result, 1 assert_xpath '/article/articleinfo/date', result, 1 assert_xpath '/article/simpara[text() = "text"]', result, 1 end test 'docbook45 backend doctype book' do input = <<-EOS = Title preamble == First Chapter chapter body EOS result = render_string(input, :attributes => {'backend' => 'docbook45', 'doctype' => 'book'}) assert_xpath '/book', result, 1 assert_xpath '/book/bookinfo/title[text() = "Title"]', result, 1 assert_xpath '/book/preface/simpara[text() = "preamble"]', result, 1 assert_xpath '/book/chapter', result, 1 assert_xpath '/book/chapter[@id = "_first_chapter"]/title[text() = "First Chapter"]', result, 1 assert_xpath '/book/chapter[@id = "_first_chapter"]/simpara[text() = "chapter body"]', result, 1 end test 'docbook45 backend doctype book no title' do result = render_string('text', :attributes => {'backend' => 'docbook45', 'doctype' => 'book'}) assert_xpath '/book', result, 1 assert_xpath '/book/bookinfo/date', result, 1 assert_xpath '/book/simpara[text() = "text"]', result, 1 end test 'should be able to set backend using :backend option key' do doc = Asciidoctor::Document.new([], :backend => 'html5') assert_equal 'html5', doc.attributes['backend'] end test ':backend option should override backend attribute' do doc = Asciidoctor::Document.new([], :backend => 'html5', :attributes => {'backend' => 'docbook45'}) assert_equal 'html5', doc.attributes['backend'] end test 'should be able to set doctype using :doctype option key' do doc = Asciidoctor::Document.new([], :doctype => 'book') assert_equal 'book', doc.attributes['doctype'] end test ':doctype option should override doctype attribute' do doc = Asciidoctor::Document.new([], :doctype => 'book', :attributes => {'doctype' => 'article'}) assert_equal 'book', doc.attributes['doctype'] end test 'do not override explicit author initials' do input = <<-EOS = AsciiDoc <NAME> <<EMAIL>> :Author Initials: SJR more info... EOS output = render_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '/article/articleinfo/authorinitials[text()="SJR"]', output, 1 end test 'attribute entry can appear immediately after document title' do input = <<-EOS Reference Guide =============== :toc: preamble EOS doc = document_from_string input assert doc.attr?('toc') assert_equal '', doc.attr('toc') end test 'attribute entry can appear before author line under document title' do input = <<-EOS Reference Guide =============== :toc: <NAME> preamble EOS doc = document_from_string input assert doc.attr?('toc') assert_equal '', doc.attr('toc') assert_equal '<NAME>', doc.attr('author') end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/reader.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/reader.rb module Asciidoctor # Public: Methods for retrieving lines from AsciiDoc source files class Reader # Public: Get the document source as a String Array of lines. attr_reader :source # Public: Get the 1-based offset of the current line. attr_reader :lineno # Public: Initialize the Reader object. # # data - The Array of Strings holding the Asciidoc source document. The # original instance of this Array is not modified (default: nil) # document - The document with which this reader is associated. Used to access # document attributes (default: nil) # preprocess - A flag indicating whether to run the preprocessor on these lines. # Only enable for the outer-most Reader. If this argument is true, # a Document object must also be supplied. # (default: false) # block - A block that can be used to retrieve external Asciidoc # data to include in this document. # # Examples # # data = File.readlines(filename) # reader = Asciidoctor::Reader.new data def initialize(data = nil, document = nil, preprocess = false, &block) data = [] if data.nil? # TODO use Struct to track file/lineno info; track as file changes; offset for sub-readers @lineno = 0 if !preprocess @lines = data.is_a?(String) ? data.lines.entries : data.dup @preprocess_source = false elsif !data.empty? # NOTE we assume document is not nil! @document = document @preprocess_source = true @include_block = block_given? ? block : nil normalize_data(data.is_a?(String) ? data.lines.entries : data) else @lines = [] @preprocess_source = false end @source = @lines.dup @next_line_preprocessed = false @unescape_next_line = false @conditionals_stack = [] @skipping = false @eof = false end # Public: Get a copy of the remaining Array of String lines parsed from the source def lines @lines.nil? ? nil : @lines.dup end # Public: Check whether there are any lines left to read. # # If preprocessing is enabled for this Reader, and there are lines remaining, # the next line is preprocessed before checking whether there are more lines. # # Returns true if @lines is empty, or false otherwise. def has_more_lines? if @eof || (@eof = @lines.empty?) false elsif @preprocess_source && !@next_line_preprocessed preprocess_next_line.nil? ? false : !@lines.empty? else true end end # Public: Check whether this reader is empty (contains no lines) # # If preprocessing is enabled for this Reader, and there are lines remaining, # the next line is preprocessed before checking whether there are more lines. # # Returns true if @lines is empty, otherwise false. def empty? !has_more_lines? end # Private: Strip off leading blank lines in the Array of lines. # # Examples # # @lines # => ["\n", "\t\n", "Foo\n", "Bar\n", "\n"] # # skip_blank_lines # => 2 # # @lines # => ["Foo\n", "Bar\n"] # # Returns an Integer of the number of lines skipped def skip_blank_lines skipped = 0 # optimized code for shortest execution path while !(next_line = get_line).nil? if next_line.chomp.empty? skipped += 1 else unshift_line next_line break end end skipped end # Public: Consume consecutive lines containing line- or block-level comments. # # Returns the Array of lines that were consumed # # Examples # @lines # => ["// foo\n", "////\n", "foo bar\n", "////\n", "actual text\n"] # # comment_lines = consume_comments # => ["// foo\n", "////\n", "foo bar\n", "////\n"] # # @lines # => ["actual text\n"] def consume_comments(options = {}) comment_lines = [] preprocess = options.fetch(:preprocess, true) while !(next_line = get_line(preprocess)).nil? if options[:include_blank_lines] && next_line.chomp.empty? comment_lines << next_line elsif (commentish = next_line.start_with?('//')) && (match = next_line.match(REGEXP[:comment_blk])) comment_lines << next_line comment_lines.push(*(grab_lines_until(:terminator => match[0], :grab_last_line => true, :preprocess => false))) elsif commentish && next_line.match(REGEXP[:comment]) comment_lines << next_line else # throw it back unshift_line next_line break end end comment_lines end alias :skip_comment_lines :consume_comments # Public: Consume consecutive lines containing line comments. # # Returns the Array of lines that were consumed # # Examples # @lines # => ["// foo\n", "bar\n"] # # comment_lines = consume_comments # => ["// foo\n"] # # @lines # => ["bar\n"] def consume_line_comments comment_lines = [] # optimized code for shortest execution path while !(next_line = get_line).nil? if next_line.match(REGEXP[:comment]) comment_lines << next_line else unshift_line next_line break end end comment_lines end # Public: Get the next line of source data. Consumes the line returned. # # preprocess - A Boolean flag indicating whether to evaluate preprocessing # directives (macros) before reading line (default: true) # # Returns the String of the next line of the source data if data is present. # Returns nil if there is no more data. def get_line(preprocess = true) if @eof || (@eof = @lines.empty?) @next_line_preprocessed = true nil elsif preprocess && @preprocess_source && !@next_line_preprocessed && preprocess_next_line.nil? @next_line_preprocessed = true nil else @lineno += 1 @next_line_preprocessed = false if @unescape_next_line @unescape_next_line = false @lines.shift[1..-1] else @lines.shift end end end # Public: Advance to the next line by discarding the line at the front of the stack # # Removes the line at the front of the stack without any processing. # # returns a boolean indicating whether there was a line to discard def advance @next_line_preprocessed = false # we assume that we're advancing over a line of known content if @eof || (@eof = @lines.empty?) false else @lineno += 1 @lines.shift true end end # Public: Get the next line of source data. Does not consume the line returned. # # preprocess - A Boolean flag indicating whether to evaluate preprocessing # directives (macros) before reading line (default: true) # # Returns a String dup of the next line of the source data if data is present. # Returns nil if there is no more data. def peek_line(preprocess = true) if !preprocess # QUESTION do we need to dup? @eof || (@eof = @lines.empty?) ? nil : @lines.first.dup elsif has_more_lines? # QUESTION do we need to dup? @lines.first.dup else nil end end # TODO document & test me! def peek_lines(number = 1) lines = [] idx = 0 (1..number).each do if @preprocess_source && !@next_line_preprocessed advanced = preprocess_next_line break if advanced.nil? || @eof || (@eof = @lines.empty?) idx = 0 if advanced end break if idx >= @lines.size # QUESTION do we need to dup? lines << @lines[idx].dup idx += 1 end lines end # Internal: Preprocess the next line until the cursor is at a line of content # # Evaluate preprocessor macros on the next line, continuing to do so until # the cursor arrives at a line of included content. That line is marked as # preprocessed so that preprocessing is not performed multiple times. # # returns a Boolean indicating whether the cursor advanced, or nil if there # are no more lines available. def preprocess_next_line # this return could be happening from a recursive call return nil if @eof || (next_line = @lines.first).nil? if next_line.include?('if') && (match = next_line.match(REGEXP[:ifdef_macro])) if next_line.start_with? '\\' @next_line_preprocessed = true @unescape_next_line = true false else preprocess_conditional_inclusion(*match.captures) end elsif @skipping advance # skip over comment blocks, we don't want to process directives in them skip_comment_lines :include_blank_lines => true, :preprocess => false preprocess_next_line.nil? ? nil : true elsif next_line.include?('include::') && match = next_line.match(REGEXP[:include_macro]) if next_line.start_with? '\\' @next_line_preprocessed = true @unescape_next_line = true false else preprocess_include(match[1]) end else @next_line_preprocessed = true false end end # Internal: Preprocess the directive (macro) to conditionally include content. # # Preprocess the conditional inclusion directive (ifdef, ifndef, ifeval, # endif) under the cursor. If the Reader is currently skipping content, then # simply track the open and close delimiters of any nested conditional # blocks. If the Reader is not skipping, mark whether the condition is # satisfied and continue preprocessing recursively until the next line of # available content is found. # # directive - The conditional inclusion directive (ifdef, ifndef, ifeval, endif) # target - The target, which is the name of one or more attributes that are # used in the condition (blank in the case of the ifeval directive) # delimiter - The conditional delimiter for multiple attributes ('+' means all # attributes must be defined or undefined, ',' means any of the attributes # can be defined or undefined. # text - The text associated with this directive (occurring between the square brackets) # Used for a single-line conditional block in the case of the ifdef or # ifndef directives, and for the conditional expression for the ifeval directive. # # returns a Boolean indicating whether the cursor advanced, or nil if there # are no more lines available. def preprocess_conditional_inclusion(directive, target, delimiter, text) # must have a target before brackets if ifdef or ifndef # must not have text between brackets if endif # don't honor match if it doesn't meet this criteria if ((directive == 'ifdef' || directive == 'ifndef') && target.empty?) || (directive == 'endif' && !text.nil?) @next_line_preprocessed = true return false end if directive == 'endif' stack_size = @conditionals_stack.size if stack_size > 0 pair = @conditionals_stack.last if target.empty? || target == pair[:target] @conditionals_stack.pop @skipping = @conditionals_stack.empty? ? false : @conditionals_stack.last[:skipping] else puts "asciidoctor: ERROR: line #{@lineno + 1}: mismatched macro: endif::#{target}[], expected endif::#{pair[:target]}[]" end else puts "asciidoctor: ERROR: line #{@lineno + 1}: unmatched macro: endif::#{target}[]" end advance return preprocess_next_line.nil? ? nil : true end skip = nil if !@skipping case directive when 'ifdef' case delimiter when nil # if the attribute is undefined, then skip skip = !@document.attributes.has_key?(target) when ',' # if any attribute is defined, then don't skip skip = !target.split(',').detect {|name| @document.attributes.has_key? name } when '+' # if any attribute is undefined, then skip skip = target.split('+').detect {|name| !@document.attributes.has_key? name } end when 'ifndef' case delimiter when nil # if the attribute is defined, then skip skip = @document.attributes.has_key?(target) when ',' # if any attribute is undefined, then don't skip skip = !target.split(',').detect {|name| !@document.attributes.has_key? name } when '+' # if any attribute is defined, then skip skip = target.split('+').detect {|name| @document.attributes.has_key? name } end when 'ifeval' # the text in brackets must match an expression # don't honor match if it doesn't meet this criteria if !target.empty? || !(expr_match = text.strip.match(REGEXP[:eval_expr])) @next_line_preprocessed = true return false end lhs = resolve_expr_val(expr_match[1]) op = expr_match[2] rhs = resolve_expr_val(expr_match[3]) skip = !lhs.send(op.to_sym, rhs) end @skipping = skip end advance # single line conditional inclusion if directive != 'ifeval' && !text.nil? if !@skipping unshift_line "#{text.rstrip}\n" return true end # conditional inclusion block else @conditionals_stack << {:target => target, :skip => skip, :skipping => @skipping} end return preprocess_next_line.nil? ? nil : true end # Internal: Preprocess the directive (macro) to include the target document. # # Preprocess the directive to include the target document. The scenarios # are as follows: # # If SafeMode is SECURE or greater, the directive is ignore and the include # directive line is emitted verbatim. # # Otherwise, if an include handler is specified (currently controlled by a # closure block), pass the target to that block and expect an Array of String # lines in return. # # Otherwise, if the include-depth attribute is greater than 0, normalize the # target path and read the lines onto the beginning of the Array of source # data. # # If none of the above apply, emit the include directive line verbatim. # # target - The name of the source document to include as specified in the # target slot of the include::[] macro # # returns a Boolean indicating whether the line under the cursor has changed. def preprocess_include(target) # if running in SafeMode::SECURE or greater, don't process this directive if @document.safe >= SafeMode::SECURE @next_line_preprocessed = true false # assume that if a block is given, the developer wants # to handle when and how to process the include, even # if the include-depth attribute is 0 elsif @include_block advance # FIXME this borks line numbers @lines.unshift(*@include_block.call(target).map {|l| "#{l.rstrip}\n"}) # FIXME currently we're not checking the upper bound of the include depth elsif @document.attributes.fetch('include-depth', 0).to_i > 0 advance # FIXME this borks line numbers @lines.unshift(*File.readlines(@document.normalize_asset_path(target, 'include file')).map {|l| "#{l.rstrip}\n"}) true else @next_line_preprocessed = true false end end # Public: Push the String line onto the beginning of the Array of source data. # # Since this line was (assumed to be) previously retrieved through the # reader, it is marked as preprocessed. # # returns nil def unshift_line(line) @lines.unshift line @next_line_preprocessed = true @eof = false @lineno -= 1 nil end # Public: Push Array of lines onto the front of the Array of source data, unless `lines` has no non-nil values. # # Returns nil def unshift(*new_lines) size = new_lines.size if size > 0 @lines.unshift(*new_lines) # assume that what we are putting back on is already processed for directives @next_line_preprocessed = true @eof = false @lineno -= size end nil end # Public: Chomp the String on the last line if this reader contains at least one line # # Delegates to chomp! # # Returns nil def chomp_last! @lines.last.chomp! unless @eof || (@eof = @lines.empty?) nil end # Public: Return all the lines from `@lines` until we (1) run out them, # (2) find a blank line with :break_on_blank_lines => true, or (3) find # a line for which the given block evals to true. # # options - an optional Hash of processing options: # * :break_on_blank_lines may be used to specify to break on # blank lines # * :skip_first_line may be used to tell the reader to advance # beyond the first line before beginning the scan # * :preserve_last_line may be used to specify that the String # causing the method to stop processing lines should be # pushed back onto the `lines` Array. # * :grab_last_line may be used to specify that the String # causing the method to stop processing lines should be # included in the lines being returned # # Returns the Array of lines forming the next segment. # # Examples # # reader = Reader.new ["First paragraph\n", "Second paragraph\n", # "Open block\n", "\n", "Can have blank lines\n", # "--\n", "\n", "In a different segment\n"] # # reader.grab_lines_until # => ["First paragraph\n", "Second paragraph\n", "Open block\n"] def grab_lines_until(options = {}, &block) buffer = [] finis = false advance if options[:skip_first_line] # save options to locals for minor optimization terminator = options[:terminator] terminator.chomp! if terminator break_on_blank_lines = options[:break_on_blank_lines] break_on_list_continuation = options[:break_on_list_continuation] skip_line_comments = options[:skip_line_comments] preprocess = options.fetch(:preprocess, true) while !(this_line = get_line(preprocess)).nil? Debug.debug { "Reader processing line: '#{this_line}'" } finis = true if terminator && this_line.chomp == terminator finis = true if !finis && break_on_blank_lines && this_line.strip.empty? finis = true if !finis && break_on_list_continuation && this_line.chomp == LIST_CONTINUATION finis = true if !finis && block && yield(this_line) if finis buffer << this_line if options[:grab_last_line] unshift_line(this_line) if options[:preserve_last_line] break end unless skip_line_comments && this_line.match(REGEXP[:comment]) buffer << this_line end end buffer end # Public: Convert a string to a legal attribute name. # # name - The String holding the Asciidoc attribute name. # # Returns a String with the legal name. # # Examples # # sanitize_attribute_name('Foo Bar') # => 'foobar' # # sanitize_attribute_name('foo') # => 'foo' # # sanitize_attribute_name('Foo 3 #-Billy') # => 'foo3-billy' def sanitize_attribute_name(name) Lexer.sanitize_attribute_name(name) end # Private: Resolve the value of one side of the expression def resolve_expr_val(str) val = str type = nil if val.start_with?('"') && val.end_with?('"') || val.start_with?('\'') && val.end_with?('\'') type = :s val = val[1..-2] end if val.include? '{' val = @document.sub_attributes(val) end if type != :s if val.empty? val = nil elsif val == 'true' val = true elsif val == 'false' val = false elsif val.include?('.') val = val.to_f else val = val.to_i end end val end # Private: Normalize raw input, used for the outermost Reader. # # This method strips whitespace from the end of every line of # the source data and appends a LF (i.e., Unix endline). This # whitespace substitution is very important to how Asciidoctor # works. # # Any leading or trailing blank lines are also removed. # # The normalized lines are assigned to the @lines instance variable. # # data - A String Array of input data to be normalized # # returns nothing def normalize_data(data) # normalize line ending to LF (purging occurrences of CRLF) # this rstrip is *very* important to how Asciidoctor works @lines = data.map {|line| "#{line.rstrip}\n" } @lines.shift && @lineno += 1 while !@lines.first.nil? && @lines.first.chomp.empty? @lines.pop while !@lines.last.nil? && @lines.last.chomp.empty? # Process bibliography references, so they're available when text # before the reference is being rendered. # FIXME we don't have support for bibliography lists yet, so disable for now # plus, this should be done while we are walking lines above #@lines.each do |line| # if biblio = line.match(REGEXP[:biblio]) # @document.register(:ids, biblio[1]) # end #end nil end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/options_test.rb
require 'test_helper' require 'asciidoctor/cli/options' context 'Options' do test 'should return error code 0 when help flag is present' do redirect_streams do |stdout, stderr| exitval = Asciidoctor::Cli::Options.parse!(%w(-h)) assert_equal 0, exitval assert_match(/^Usage:/, stdout.string) end end test 'should return error code 1 when invalid option present' do redirect_streams do |stdout, stderr| exitval = Asciidoctor::Cli::Options.parse!(%w(--foobar)) assert_equal 1, exitval assert_equal 'asciidoctor: invalid option: --foobar', stderr.string.chomp end end test 'should return error code 1 when option has invalid argument' do redirect_streams do |stdout, stderr| exitval = Asciidoctor::Cli::Options.parse!(%w(-b foo input.ad)) assert_equal 1, exitval assert_equal 'asciidoctor: invalid argument: -b foo', stderr.string.chomp end end test 'should return error code 1 when option is missing required argument' do redirect_streams do |stdout, stderr| exitval = Asciidoctor::Cli::Options.parse!(%w(-b)) assert_equal 1, exitval assert_equal 'asciidoctor: option missing argument: -b', stderr.string.chomp end end test 'should emit warning when unparsed options remain' do redirect_streams do |stdout, stderr| options = Asciidoctor::Cli::Options.parse!(%w(-b docbook extra junk test/fixtures/sample.asciidoc)) assert options.is_a? Hash assert_equal 'asciidoctor: WARNING: extra arguments detected (unparsed arguments: \'extra\', \'junk\')', stderr.string.chomp end end test 'basic argument assignment' do options = Asciidoctor::Cli::Options.parse!(%w(-v -s -d book test/fixtures/sample.asciidoc)) assert_equal true, options[:verbose] assert_equal false, options[:header_footer] assert_equal 'book', options[:attributes]['doctype'] assert_equal 'test/fixtures/sample.asciidoc', options[:input_file] end test 'standard attribute assignment' do options = Asciidoctor::Cli::Options.parse!(%w(-a imagesdir=images,icons test/fixtures/sample.asciidoc)) assert_equal 'images', options[:attributes]['imagesdir'] assert_equal '', options[:attributes]['icons'] end test 'multiple attribute arguments' do options = Asciidoctor::Cli::Options.parse!(%w(-a imagesdir=images -a icons test/fixtures/sample.asciidoc)) assert_equal 'images', options[:attributes]['imagesdir'] assert_equal '', options[:attributes]['icons'] end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/invoker_test.rb
require 'test_helper' require 'asciidoctor/cli/options' require 'asciidoctor/cli/invoker' context 'Invoker' do test 'should parse source and render as html5 article by default' do invoker = nil output = nil redirect_streams do |stdout, stderr| invoker = invoke_cli %w(-o -) output = stdout.string end assert !invoker.nil? doc = invoker.document assert !doc.nil? assert_equal 'Document Title', doc.doctitle assert_equal 'Doc Writer', doc.attr('author') assert_equal 'html5', doc.attr('backend') assert_equal '.html', doc.attr('outfilesuffix') assert_equal 'article', doc.attr('doctype') assert doc.blocks? assert_equal :preamble, doc.blocks.first.context assert !output.empty? assert_xpath '/html', output, 1 assert_xpath '/html/head', output, 1 assert_xpath '/html/body', output, 1 assert_xpath '/html/head/title[text() = "Document Title"]', output, 1 assert_xpath '/html/body[@class="article"]/*[@id="header"]/h1[text() = "Document Title"]', output, 1 end test 'should set implicit doc info attributes' do sample_filepath = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'sample.asciidoc')) sample_filedir = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures')) invoker = invoke_cli_to_buffer %w(-o /dev/null), sample_filepath doc = invoker.document assert_equal 'sample', doc.attr('docname') assert_equal sample_filepath, doc.attr('docfile') assert_equal sample_filedir, doc.attr('docdir') assert doc.attr?('docdate') assert doc.attr?('doctime') assert doc.attr?('docdatetime') assert invoker.read_output.empty? end test 'should accept document from stdin and write to stdout' do invoker = invoke_cli_to_buffer(%w(-s), '-') { 'content' } doc = invoker.document assert !doc.attr?('docname') assert !doc.attr?('docfile') assert_equal Dir.pwd, doc.attr('docdir') assert_equal doc.attr('docdate'), doc.attr('localdate') assert_equal doc.attr('doctime'), doc.attr('localtime') assert_equal doc.attr('docdatetime'), doc.attr('localdatetime') assert !doc.attr?('outfile') output = invoker.read_output assert !output.empty? assert_xpath '/*[@class="paragraph"]/p[text()="content"]', output, 1 end test 'should allow docdir to be specified when input is a string' do expected_docdir = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures')) invoker = invoke_cli_to_buffer(%w(-s --base-dir test/fixtures -o /dev/null), '-') { 'content' } doc = invoker.document assert_equal expected_docdir, doc.attr('docdir') assert_equal expected_docdir, doc.base_dir end test 'should display version and exit' do redirect_streams do |stdout, stderr| invoke_cli %w(--version) assert_equal "Asciidoctor #{Asciidoctor::VERSION} [http://asciidoctor.org]", stdout.string.chomp end end test 'should report usage if no input file given' do redirect_streams do |stdout, stderr| invoke_cli [], nil assert_match(/Usage:/, stderr.string) end end test 'should report error if input file does not exist' do redirect_streams do |stdout, stderr| invoker = invoke_cli [], 'missing_file.asciidoc' assert_match(/input file .* missing/, stderr.string) assert_equal 1, invoker.code end end test 'should warn if extra arguments are detected' do redirect_streams do |stdout, stderr| invoker = invoke_cli %w(-o /dev/null extra arguments sample.asciidoc), nil assert_match(/extra arguments detected/, stderr.string) assert_equal 1, invoker.code end end test 'should output to file name based on input file name' do sample_outpath = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'sample.html')) begin invoker = invoke_cli doc = invoker.document assert_equal sample_outpath, doc.attr('outfile') assert File.exist?(sample_outpath) output = File.read(sample_outpath) assert !output.empty? assert_xpath '/html', output, 1 assert_xpath '/html/head', output, 1 assert_xpath '/html/body', output, 1 assert_xpath '/html/head/title[text() = "Document Title"]', output, 1 assert_xpath '/html/body/*[@id="header"]/h1[text() = "Document Title"]', output, 1 ensure FileUtils::rm(sample_outpath) end end test 'should output to file in destination directory if set' do destination_path = File.expand_path(File.join(File.dirname(__FILE__), 'test_output')) sample_outpath = File.join(destination_path, 'sample.html') begin FileUtils::mkdir_p(destination_path) invoker = invoke_cli %w(-D test/test_output) doc = invoker.document assert_equal sample_outpath, doc.attr('outfile') assert File.exist?(sample_outpath) ensure FileUtils::rm(sample_outpath) FileUtils::rmdir(destination_path) end end test 'should output to file specified' do sample_outpath = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'sample-output.html')) begin invoker = invoke_cli %W(-o #{sample_outpath}) doc = invoker.document assert_equal sample_outpath, doc.attr('outfile') assert File.exist?(sample_outpath) ensure FileUtils::rm(sample_outpath) end end test 'should suppress header footer if specified' do invoker = invoke_cli_to_buffer %w(-s -o -) output = invoker.read_output assert_xpath '/html', output, 0 assert_xpath '/*[@id="preamble"]', output, 1 end test 'should not compact output by default' do invoker = invoke_cli_to_buffer(%w(-s -o -), '-') { 'content' } output = invoker.read_output assert_match(/\n[[:blank:]]*\n/, output) end test 'should compact output if specified' do invoker = invoke_cli_to_buffer(%w(-C -s -o -), '-') { 'content' } output = invoker.read_output assert_no_match(/\n[[:blank:]]*\n/, output) end test 'should set backend to html5 if specified' do invoker = invoke_cli_to_buffer %w(-b html5 -o -) doc = invoker.document assert_equal 'html5', doc.attr('backend') assert_equal '.html', doc.attr('outfilesuffix') output = invoker.read_output assert_xpath '/html', output, 1 end test 'should set backend to docbook45 if specified' do invoker = invoke_cli_to_buffer %w(-b docbook45 -o -) doc = invoker.document assert_equal 'docbook45', doc.attr('backend') assert_equal '.xml', doc.attr('outfilesuffix') output = invoker.read_output assert_xpath '/article', output, 1 end test 'should set doctype to article if specified' do invoker = invoke_cli_to_buffer %w(-d article -o -) doc = invoker.document assert_equal 'article', doc.attr('doctype') output = invoker.read_output assert_xpath '/html/body[@class="article"]', output, 1 end test 'should set doctype to book if specified' do invoker = invoke_cli_to_buffer %w(-d book -o -) doc = invoker.document assert_equal 'book', doc.attr('doctype') output = invoker.read_output assert_xpath '/html/body[@class="book"]', output, 1 end test 'should set attribute with value' do invoker = invoke_cli_to_buffer %w(--trace -a idprefix=id -s -o -) doc = invoker.document assert_equal 'id', doc.attr('idprefix') output = invoker.read_output assert_xpath '//h2[@id="idsection_a"]', output, 1 end test 'should not set attribute ending in @ if defined in document' do invoker = invoke_cli_to_buffer %w(--trace -a idprefix=id@ -s -o -) doc = invoker.document assert_equal 'id_', doc.attr('idprefix') output = invoker.read_output assert_xpath '//h2[@id="id_section_a"]', output, 1 end test 'should set attribute with no value' do invoker = invoke_cli_to_buffer %w(-a icons -s -o -) doc = invoker.document assert_equal '', doc.attr('icons') output = invoker.read_output assert_xpath '//*[@class="admonitionblock"]//img[@alt="Note"]', output, 1 end test 'should unset attribute ending in bang' do invoker = invoke_cli_to_buffer %w(-a sectids! -s -o -) doc = invoker.document assert !doc.attr?('sectids') output = invoker.read_output # leave the count loose in case we add more sections assert_xpath '//h2[not(@id)]', output end test 'default mode for cli should be unsafe' do invoker = invoke_cli_to_buffer %w(-o /dev/null) doc = invoker.document assert_equal Asciidoctor::SafeMode::UNSAFE, doc.safe end test 'should set safe mode if specified' do invoker = invoke_cli_to_buffer %w(--safe -o /dev/null) doc = invoker.document assert_equal Asciidoctor::SafeMode::SAFE, doc.safe end test 'should set safe mode to specified level' do levels = { 'unsafe' => Asciidoctor::SafeMode::UNSAFE, 'safe' => Asciidoctor::SafeMode::SAFE, 'server' => Asciidoctor::SafeMode::SERVER, 'secure' => Asciidoctor::SafeMode::SECURE, } levels.each do |name, const| invoker = invoke_cli_to_buffer %W(-S #{name} -o /dev/null) doc = invoker.document assert_equal const, doc.safe end end test 'should set eRuby impl if specified' do invoker = invoke_cli_to_buffer %w(--eruby erubis -o /dev/null) doc = invoker.document assert_equal 'erubis', doc.instance_variable_get('@options')[:eruby] end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/lexer_test.rb
require 'test_helper' context "Lexer" do test "is_section_title?" do assert Asciidoctor::Lexer.is_section_title?('AsciiDoc Home Page', '==================') assert Asciidoctor::Lexer.is_section_title?('=== AsciiDoc Home Page') end test "collect unnamed attribute" do attributes = {} line = 'quote' expected = {1 => 'quote'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect unnamed attribute double-quoted" do attributes = {} line = '"quote"' expected = {1 => 'quote'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect empty unnamed attribute double-quoted" do attributes = {} line = '""' expected = {1 => ''} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect unnamed attribute double-quoted containing escaped quote" do attributes = {} line = '"ba\"zaar"' expected = {1 => 'ba"zaar'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect unnamed attribute single-quoted" do attributes = {} line = '\'quote\'' expected = {1 => 'quote'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect empty unnamed attribute single-quoted" do attributes = {} line = '\'\'' expected = {1 => ''} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect unnamed attribute single-quoted containing escaped quote" do attributes = {} line = '\'ba\\\'zaar\'' expected = {1 => 'ba\'zaar'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect unnamed attribute with dangling delimiter" do attributes = {} line = 'quote , ' expected = {1 => 'quote'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect unnamed attributes" do attributes = {} line = "first, second one, third" expected = {1 => 'first', 2 => 'second one', 3 => 'third'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect named attribute" do attributes = {} line = 'foo=bar' expected = {'foo' => 'bar'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect named attribute double-quoted" do attributes = {} line = 'foo="bar"' expected = {'foo' => 'bar'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test 'collect named attribute with double-quoted empty value' do attributes = {} line = 'height=100,caption="",link="images/octocat.png"' expected = {'height' => '100', 'caption' => '', 'link' => 'images/octocat.png'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect named attribute single-quoted" do attributes = {} line = 'foo=\'bar\'' expected = {'foo' => 'bar'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test 'collect named attribute with single-quoted empty value' do attributes = {} line = "height=100,caption='',link='images/octocat.png'" expected = {'height' => '100', 'caption' => '', 'link' => 'images/octocat.png'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect named attributes unquoted" do attributes = {} line = "first=value, second=two, third=3" expected = {'first' => 'value', 'second' => 'two', 'third' => '3'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect named attributes quoted" do attributes = {} line = "first='value', second=\"value two\", third=three" expected = {'first' => 'value', 'second' => 'value two', 'third' => 'three'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect named attributes quoted containing non-semantic spaces" do attributes = {} line = " first = 'value', second =\"value two\" , third= three " expected = {'first' => 'value', 'second' => 'value two', 'third' => 'three'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect mixed named and unnamed attributes" do attributes = {} line = "first, second=\"value two\", third=three, <NAME>" expected = {1 => 'first', 'second' => 'value two', 'third' => 'three', 4 => '<NAME>'} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect options attribute" do attributes = {} line = "quote, options='opt1,opt2 , opt3'" expected = {1 => 'quote', 'options' => 'opt1,opt2 , opt3', 'opt1-option' => nil, 'opt2-option' => nil, 'opt3-option' => nil} Asciidoctor::AttributeList.new(line).parse_into(attributes) assert_equal expected, attributes end test "collect and rekey unnamed attributes" do attributes = {} line = "first, second one, third, fourth" expected = {1 => 'first', 2 => 'second one', 3 => 'third', 4 => 'fourth', 'a' => 'first', 'b' => 'second one', 'c' => 'third'} Asciidoctor::AttributeList.new(line).parse_into(attributes, ['a', 'b', 'c']) assert_equal expected, attributes end test "rekey positional attributes" do attributes = {1 => 'source', 2 => 'java'} expected = {1 => 'source', 2 => 'java', 'style' => 'source', 'language' => 'java'} Asciidoctor::AttributeList.rekey(attributes, ['style', 'language', 'linenums']) assert_equal expected, attributes end test "parse author first" do metadata, = parse_header_metadata 'Stuart' assert_equal 3, metadata.size assert_equal 'Stuart', metadata['author'] assert_equal 'Stuart', metadata['firstname'] assert_equal 'S', metadata['authorinitials'] end test "parse author first last" do metadata, = parse_header_metadata '<NAME>' assert_equal 4, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Yukihiro', metadata['firstname'] assert_equal 'Matsumoto', metadata['lastname'] assert_equal 'YM', metadata['authorinitials'] end test "parse author first middle last" do metadata, = parse_header_metadata '<NAME>' assert_equal 5, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'David', metadata['firstname'] assert_equal 'Heinemeier', metadata['middlename'] assert_equal 'Hansson', metadata['lastname'] assert_equal 'DHH', metadata['authorinitials'] end test "parse author first middle last email" do metadata, = parse_header_metadata '<NAME> <<EMAIL>>' assert_equal 6, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'David', metadata['firstname'] assert_equal 'Heinemeier', metadata['middlename'] assert_equal 'Hansson', metadata['lastname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'DHH', metadata['authorinitials'] end test "parse author first email" do metadata, = parse_header_metadata 'Stuart <<EMAIL>>' assert_equal 4, metadata.size assert_equal 'Stuart', metadata['author'] assert_equal 'Stuart', metadata['firstname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'S', metadata['authorinitials'] end test "parse author first last email" do metadata, = parse_header_metadata '<NAME> <<EMAIL>>' assert_equal 5, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Stuart', metadata['firstname'] assert_equal 'Rackham', metadata['lastname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'SR', metadata['authorinitials'] end test "parse author with hyphen" do metadata, = parse_header_metadata '<NAME> <<EMAIL>>' assert_equal 5, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Tim', metadata['firstname'] assert_equal 'Berners-Lee', metadata['lastname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'TB', metadata['authorinitials'] end test "parse author with single quote" do metadata, = parse_header_metadata '<NAME> <<EMAIL>>' assert_equal 5, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Stephen', metadata['firstname'] assert_equal 'O\'Grady', metadata['lastname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'SO', metadata['authorinitials'] end test "parse author with dotted initial" do metadata, = parse_header_metadata '<NAME> <<EMAIL>>' assert_equal 6, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Heiko', metadata['firstname'] assert_equal 'W.', metadata['middlename'] assert_equal 'Rupp', metadata['lastname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'HWR', metadata['authorinitials'] end test "parse author with underscore" do metadata, = parse_header_metadata 'Tim_<NAME>' assert_equal 4, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal '<NAME>', metadata['firstname'] assert_equal 'Fella', metadata['lastname'] assert_equal 'TF', metadata['authorinitials'] end test "parse author condenses whitespace" do metadata, = parse_header_metadata ' Stuart Rackham <<EMAIL>>' assert_equal 5, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Stuart', metadata['firstname'] assert_equal 'Rackham', metadata['lastname'] assert_equal '<EMAIL>', metadata['email'] assert_equal 'SR', metadata['authorinitials'] end test "parse invalid author line becomes author" do metadata, = parse_header_metadata ' <NAME>, founder of AsciiDoc <<EMAIL>>' assert_equal 3, metadata.size assert_equal '<NAME>, founder of AsciiDoc <<EMAIL>>', metadata['author'] assert_equal '<NAME>, founder of AsciiDoc <<EMAIL>>', metadata['firstname'] assert_equal 'S', metadata['authorinitials'] end test "parse rev number date remark" do metadata, = parse_header_metadata "Ryan Waldron\nv0.0.7, 2013-12-18: The first release you can stand on" assert_equal 7, metadata.size assert_equal '0.0.7', metadata['revnumber'] assert_equal '2013-12-18', metadata['revdate'] assert_equal 'The first release you can stand on', metadata['revremark'] end test "parse rev date" do metadata, = parse_header_metadata "Ryan Waldron\n2013-12-18" assert_equal 5, metadata.size assert_equal '2013-12-18', metadata['revdate'] end # while compliant w/ AsciiDoc, this is just sloppy parsing test "treats arbitrary text on rev line as revdate" do metadata, = parse_header_metadata "Ryan Waldron\nfoobar\n" assert_equal 5, metadata.size assert_equal 'foobar', metadata['revdate'] end test "parse rev date remark" do metadata, = parse_header_metadata "Ryan Waldron\n2013-12-18: The first release you can stand on" assert_equal 6, metadata.size assert_equal '2013-12-18', metadata['revdate'] assert_equal 'The first release you can stand on', metadata['revremark'] end test "should not mistake attribute entry as rev remark" do metadata, = parse_header_metadata "Joe Cool\n:layout: post\n" assert_not_equal 'layout: post', metadata['revremark'] assert !metadata.has_key?('revdate') end test "parse rev remark only" do metadata, = parse_header_metadata "Joe Cool\n :Must start line with space\n" assert_equal 'Must start line with space', metadata['revremark'] assert_equal '', metadata['revdate'] end test "skip line comments before author" do metadata, = parse_header_metadata "// Asciidoctor\n// release artist\nRyan Waldron" assert_equal 4, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Ryan', metadata['firstname'] assert_equal 'Waldron', metadata['lastname'] assert_equal 'RW', metadata['authorinitials'] end test "skip block comment before author" do metadata, = parse_header_metadata "////\nAsciidoctor\nrelease artist\n////\nRyan Waldron" assert_equal 4, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal 'Ryan', metadata['firstname'] assert_equal 'Waldron', metadata['lastname'] assert_equal 'RW', metadata['authorinitials'] end test "skip block comment before rev" do metadata, = parse_header_metadata "Ryan Waldron\n////\nAsciidoctor\nrelease info\n////\nv0.0.7, 2013-12-18" assert_equal 6, metadata.size assert_equal '<NAME>', metadata['author'] assert_equal '0.0.7', metadata['revnumber'] assert_equal '2013-12-18', metadata['revdate'] end test "attribute entry overrides generated author initials" do blankdoc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new "<NAME> <<EMAIL>>\n:Author Initials: SJR".lines.entries metadata = Asciidoctor::Lexer.parse_header_metadata(reader, blankdoc) assert_equal 'SR', metadata['authorinitials'] assert_equal 'SJR', blankdoc.attributes['authorinitials'] end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/document.rb
module Asciidoctor # Public: Methods for parsing Asciidoc documents and rendering them # using erb templates. # # There are several strategies for getting the title of the document: # # doctitle - value of title attribute, if assigned and non-empty, # otherwise title of first section in document, if present # otherwise nil # name - an alias of doctitle # title - value of the title attribute, or nil if not present # first_section.title - title of first section in document, if present # header.title - title of section level 0 # # Keep in mind that you'll want to honor these document settings: # # notitle - The h1 heading should not be shown # noheader - The header block (h1 heading, author, revision info) should not be shown class Document < AbstractBlock Footnote = Struct.new(:index, :id, :text) AttributeEntry = Struct.new(:name, :value, :negate) do def initialize(name, value, negate = nil) super(name, value, negate.nil? ? value.nil? : false) end def save_to(block_attributes) block_attributes[:attribute_entries] ||= [] block_attributes[:attribute_entries] << self end end # Public A read-only integer value indicating the level of security that # should be enforced while processing this document. The value must be # set in the Document constructor using the :safe option. # # A value of 0 (UNSAFE) disables any of the security features enforced # by Asciidoctor (Ruby is still subject to its own restrictions). # # A value of 1 (SAFE) closely parallels safe mode in AsciiDoc. In particular, # it prevents access to files which reside outside of the parent directory # of the source file and disables any macro other than the include macro. # # A value of 10 (SERVER) disallows the document from setting attributes that # would affect the rendering of the document, in addition to all the security # features of SafeMode::SAFE. For instance, this value disallows changing the # backend or the source-highlighter using an attribute defined in the source # document. This is the most fundamental level of security for server-side # deployments (hence the name). # # A value of 20 (SECURE) disallows the document from attempting to read files # from the file system and including the contents of them into the document, # in addition to all the security features of SafeMode::SECURE. In # particular, it disallows use of the include::[] macro and the embedding of # binary content (data uri), stylesheets and JavaScripts referenced by the # document. (Asciidoctor and trusted extensions may still be allowed to embed # trusted content into the document). # # Since Asciidoctor is aiming for wide adoption, 20 (SECURE) is the default # value and is recommended for server-side deployments. # # A value of 100 (PARANOID) is planned to disallow the use of passthrough # macros and prevents the document from setting any known attributes in # addition to all the security features of SafeMode::SECURE. Please note that # this level is not currently implemented (and therefore not enforced)! attr_reader :safe # Public: Get the Hash of document references attr_reader :references # Public: Get the Hash of document counters attr_reader :counters # Public: Get the Hash of callouts attr_reader :callouts # Public: The section level 0 block attr_reader :header # Public: Base directory for rendering this document. Defaults to directory of the source file. # If the source is a string, defaults to the current directory. attr_reader :base_dir # Public: A reference to the parent document of this nested document. attr_reader :parent_document # Public: Initialize an Asciidoc object. # # data - The Array of Strings holding the Asciidoc source document. (default: []) # options - A Hash of options to control processing, such as setting the safe mode (:safe), # suppressing the header/footer (:header_footer) and attribute overrides (:attributes) # (default: {}) # block - A block that can be used to retrieve external Asciidoc # data to include in this document. # # Examples # # data = File.readlines(filename) # doc = Asciidoctor::Document.new(data) # puts doc.render def initialize(data = [], options = {}, &block) super(self, :document) @renderer = nil if options[:parent] @parent_document = options.delete(:parent) # should we dup here? options[:attributes] = @parent_document.attributes options[:safe] ||= @parent_document.safe options[:base_dir] ||= @parent_document.base_dir @renderer = @parent_document.renderer else @parent_document = nil end @header = nil @references = { :ids => {}, :footnotes => [], :links => [], :images => [], :indexterms => [] } @counters = {} @callouts = Callouts.new @options = options @safe = @options.fetch(:safe, SafeMode::SECURE).to_i @options[:header_footer] = @options.fetch(:header_footer, false) @attributes['asciidoctor'] = '' @attributes['asciidoctor-version'] = VERSION @attributes['sectids'] = '' @attributes['encoding'] = 'UTF-8' @attributes['notitle'] = '' if !@options[:header_footer] # language strings # TODO load these based on language settings @attributes['caution-caption'] = 'Caution' @attributes['important-caption'] = 'Important' @attributes['note-caption'] = 'Note' @attributes['tip-caption'] = 'Tip' @attributes['warning-caption'] = 'Warning' @attributes['appendix-caption'] = 'Appendix' @attributes['example-caption'] = 'Example' @attributes['figure-caption'] = 'Figure' @attributes['table-caption'] = 'Table' @attributes['toc-title'] = 'Table of Contents' @attribute_overrides = options[:attributes] || {} # the only way to set the include-depth attribute is via the document options # 10 is the AsciiDoc default, though currently Asciidoctor only supports 1 level @attribute_overrides['include-depth'] ||= 10 # if the base_dir option is specified, it overrides docdir as the root for relative paths # otherwise, the base_dir is the directory of the source file (docdir) or the current # directory of the input is a string if options[:base_dir].nil? if @attribute_overrides['docdir'] @base_dir = @attribute_overrides['docdir'] = File.expand_path(@attribute_overrides['docdir']) else # perhaps issue a warning here? @base_dir = @attribute_overrides['docdir'] = Dir.pwd end else @base_dir = @attribute_overrides['docdir'] = File.expand_path(options[:base_dir]) end # allow common attributes backend and doctype to be set using options hash unless @options[:backend].nil? @attribute_overrides['backend'] = @options[:backend] end unless @options[:doctype].nil? @attribute_overrides['doctype'] = @options[:doctype] end if @safe >= SafeMode::SERVER # restrict document from setting source-highlighter and backend @attribute_overrides['source-highlighter'] ||= nil @attribute_overrides['backend'] ||= DEFAULT_BACKEND # restrict document from seeing the docdir and trim docfile to relative path if @attribute_overrides.has_key?('docfile') && @parent_document.nil? @attribute_overrides['docfile'] = @attribute_overrides['docfile'][(@attribute_overrides['docdir'].length + 1)..-1] end @attribute_overrides['docdir'] = '' # restrict document from enabling icons if @safe >= SafeMode::SECURE @attribute_overrides['icons'] ||= nil end end @attribute_overrides.delete_if {|key, val| verdict = false # a nil or negative key undefines the attribute if val.nil? || key[-1..-1] == '!' @attributes.delete(key.chomp '!') # otherwise it's an attribute assignment else # a value ending in @ indicates this attribute does not override # an attribute with the same key in the document souce if val.is_a?(String) && val.end_with?('@') val.chop! verdict = true end @attributes[key] = val end verdict } @attributes['backend'] ||= DEFAULT_BACKEND @attributes['doctype'] ||= DEFAULT_DOCTYPE update_backend_attributes if !@parent_document.nil? # don't need to do the extra processing within our own document @reader = Reader.new(data) else @reader = Reader.new(data, self, true, &block) end # dynamic intrinstic attribute values now = Time.new @attributes['localdate'] ||= now.strftime('%Y-%m-%d') @attributes['localtime'] ||= now.strftime('%H:%M:%S %Z') @attributes['localdatetime'] ||= [@attributes['localdate'], @attributes['localtime']] * ' ' # docdate, doctime and docdatetime should default to # localdate, localtime and localdatetime if not otherwise set @attributes['docdate'] ||= @attributes['localdate'] @attributes['doctime'] ||= @attributes['localtime'] @attributes['docdatetime'] ||= @attributes['localdatetime'] @attributes['iconsdir'] ||= File.join(@attributes.fetch('imagesdir', 'images'), 'icons') # Now parse the lines in the reader into blocks Lexer.parse(@reader, self, :header_only => @options.fetch(:parse_header_only, false)) @callouts.rewind Debug.debug { msg = [] msg << "Found #{@blocks.size} blocks in this document:" @blocks.each {|b| msg << b } msg * "\n" } end # Public: Get the named counter and take the next number in the sequence. # # name - the String name of the counter # seed - the initial value as a String or Integer # # returns the next number in the sequence for the specified counter def counter(name, seed = nil) if !@counters.has_key? name if seed.nil? seed = nextval(@attributes.has_key?(name) ? @attributes[name] : 0) elsif seed.to_i.to_s == seed seed = seed.to_i end @counters[name] = seed else @counters[name] = nextval(@counters[name]) end (@attributes[name] = @counters[name]) end # Internal: Get the next value in the sequence. # # Handles both integer and character sequences. # # current - the value to increment as a String or Integer # # returns the next value in the sequence according to the current value's type def nextval(current) if current.is_a?(Integer) current + 1 else intval = current.to_i if intval.to_s != current.to_s (current[0].ord + 1).chr else intval + 1 end end end def register(type, value) case type when :ids if value.is_a?(Array) @references[:ids][value[0]] = (value[1] || '[' + value[0] + ']') else @references[:ids][value] = '[' + value + ']' end when :footnotes, :indexterms @references[type] << value else if @options[:catalog_assets] @references[type] << value end end end def footnotes? not @references[:footnotes].empty? end def footnotes @references[:footnotes] end def nested? !@parent_document.nil? end # Make the raw source for the Document available. def source @reader.source.join if @reader end # Make the raw source lines for the Document available. def source_lines @reader.source if @reader end def doctype @attributes['doctype'] end def backend @attributes['backend'] end # The title explicitly defined in the document attributes def title @attributes['title'] end def title=(title) @header ||= Section.new self @header.title = title end # We need to be able to return some semblance of a title def doctitle if !(title = @attributes.fetch('title', '')).empty? title elsif !(sect = first_section).nil? && sect.title? sect.title else nil end end alias :name :doctitle # Public: Convenience method to retrieve the document attribute 'author' # # returns the full name of the author as a String def author @attributes['author'] end # Public: Convenience method to retrieve the document attribute 'revdate' # # returns the date of last revision for the document as a String def revdate @attributes['revdate'] end def notitle @attributes.has_key? 'notitle' end def noheader @attributes.has_key? 'noheader' end # QUESTION move to AbstractBlock? def first_section has_header? ? @header : (@blocks || []).detect{|e| e.is_a? Section} end def has_header? !@header.nil? end # Internal: Branch the attributes so that the original state can be restored # at a future time. def save_attributes # css-signature cannot be updated after header attributes are processed if @id.nil? && @attributes.has_key?('css-signature') @id = @attributes['css-signature'] end @original_attributes = @attributes.dup end # Internal: Restore the attributes to the previously saved state def restore_attributes @attributes = @original_attributes end # Internal: Delete any attributes stored for playback def clear_playback_attributes(attributes) attributes.delete(:attribute_entries) end # Internal: Replay attribute assignments at the block level def playback_attributes(block_attributes) if block_attributes.has_key? :attribute_entries block_attributes[:attribute_entries].each do |entry| if entry.negate @attributes.delete(entry.name) else @attributes[entry.name] = entry.value end end end end # Public: Set the specified attribute on the document if the name is not locked # # If the attribute is locked, false is returned. Otherwise, the value is # assigned to the attribute name after first performing attribute # substitutions on the value. If the attribute name is 'backend', then the # value of backend-related attributes are updated. # # name - the String attribute name # value - the String attribute value # # returns true if the attribute was set, false if it was not set because it's locked def set_attribute(name, value) if attribute_locked?(name) false else @attributes[name] = apply_attribute_value_subs(value) if name == 'backend' update_backend_attributes() end true end end # Public: Delete the specified attribute from the document if the name is not locked # # If the attribute is locked, false is returned. Otherwise, the attribute is deleted. # # name - the String attribute name # # returns true if the attribute was deleted, false if it was not because it's locked def delete_attribute(name) if attribute_locked?(name) false else @attributes.delete(name) true end end # Public: Determine if the attribute has been locked by being assigned in document options # # key - The attribute key to check # # Returns true if the attribute is locked, false otherwise def attribute_locked?(name) @attribute_overrides.has_key?(name) || @attribute_overrides.has_key?("#{name}!") end # Internal: Apply substitutions to the attribute value # # If the value is an inline passthrough macro (e.g., pass:[text]), then # apply the substitutions defined on the macro to the text. Otherwise, # apply the verbatim substitutions to the value. # # value - The String attribute value on which to perform substitutions # # Returns The String value with substitutions performed. def apply_attribute_value_subs(value) if value.match(REGEXP[:pass_macro_basic]) # copy match for Ruby 1.8.7 compat m = $~ subs = [] if !m[1].empty? subs = resolve_subs(m[1]) end if !subs.empty? apply_subs(m[2], subs) else m[2] end else apply_header_subs(value) end end # Public: Update the backend attributes to reflect a change in the selected backend def update_backend_attributes() backend = @attributes['backend'] if BACKEND_ALIASES.has_key? backend backend = @attributes['backend'] = BACKEND_ALIASES[backend] end basebackend = backend.sub(/[[:digit:]]+$/, '') page_width = DEFAULT_PAGE_WIDTHS[basebackend] if page_width @attributes['pagewidth'] = page_width else @attributes.delete('pagewidth') end @attributes["backend-#{backend}"] = '' @attributes['basebackend'] = basebackend @attributes["basebackend-#{basebackend}"] = '' # REVIEW cases for the next two assignments @attributes["#{backend}-#{@attributes['doctype']}"] = '' @attributes["#{basebackend}-#{@attributes['doctype']}"] = '' ext = DEFAULT_EXTENSIONS[basebackend] || '.html' @attributes['outfilesuffix'] = ext file_type = ext[1..-1] @attributes['filetype'] = file_type @attributes["filetype-#{file_type}"] = '' end def splain Debug.debug { msg = '' if @header msg = "Header is #{@header}" else msg = "No header" end msg += "I have #{@blocks.count} blocks" @blocks.each_with_index do |block, i| msg += "v" * 60 msg += "Block ##{i} is a #{block.class}" msg += "Name is #{block.title rescue 'n/a'}" block.splain(0) if block.respond_to? :splain msg += "^" * 60 end } nil end def renderer(opts = {}) return @renderer if @renderer render_options = {} # Load up relevant Document @options if @options.has_key? :template_dir render_options[:template_dir] = @options[:template_dir] end render_options[:backend] = @attributes.fetch('backend', 'html5') render_options[:template_engine] = @options[:template_engine] render_options[:eruby] = @options.fetch(:eruby, 'erb') render_options[:compact] = @options.fetch(:compact, false) # Override Document @option settings with options passed in render_options.merge! opts @renderer = Renderer.new(render_options) end # Public: Render the Asciidoc document using the templates # loaded by Renderer. If a :template_dir is not specified, # or a template is missing, the renderer will fall back to # using the appropriate built-in template. def render(opts = {}) restore_attributes r = renderer(opts) @options.merge(opts)[:header_footer] ? r.render('document', self).strip : r.render('embedded', self) end def content # per AsciiDoc-spec, remove the title after rendering the header @attributes.delete('title') @blocks.map {|b| b.render }.join end def to_s %[#{super.to_s} - #{doctitle}] end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/renderer_test.rb
require 'test_helper' context 'Renderer' do test 'should extract view mapping from built-in template with one segment and backend' do view_name, view_backend = Asciidoctor::Renderer.extract_view_mapping('Asciidoctor::HTML5::DocumentTemplate') assert_equal 'document', view_name assert_equal 'html5', view_backend end test 'should extract view mapping from built-in template with two segments and backend' do view_name, view_backend = Asciidoctor::Renderer.extract_view_mapping('Asciidoctor::DocBook45::BlockSidebarTemplate') assert_equal 'block_sidebar', view_name assert_equal 'docbook45', view_backend end test 'should extract view mapping from built-in template without backend' do view_name, view_backend = Asciidoctor::Renderer.extract_view_mapping('Asciidoctor::DocumentTemplate') assert_equal 'document', view_name assert view_backend.nil? end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/paragraphs_test.rb
<gh_stars>0 require 'test_helper' context "Paragraphs" do context 'Normal' do test "rendered correctly" do assert_xpath "//p", render_string("Plain text for the win.\n\nYes, plainly."), 2 end test "with title" do rendered = render_string(".Titled\nParagraph.\n\nWinning") assert_xpath "//div[@class='title']", rendered assert_xpath "//p", rendered, 2 end test "no duplicate block before next section" do rendered = render_string("Title\n=====\n\nPreamble.\n\n== First Section\n\nParagraph 1\n\nParagraph 2\n\n\n== Second Section\n\nLast words") assert_xpath '//p[text()="Paragraph 2"]', rendered, 1 end test 'does not treat wrapped line as a list item' do input = <<-EOS paragraph . wrapped line EOS output = render_embedded_string input assert_css 'p', output, 1 assert_xpath %(//p[text()="paragraph\n. wrapped line"]), output, 1 end test 'does not treat wrapped line as a block title' do input = <<-EOS paragraph .wrapped line EOS output = render_embedded_string input assert_css 'p', output, 1 assert_xpath %(//p[text()="paragraph\n.wrapped line"]), output, 1 end test 'expands index term macros in DocBook backend' do input = <<-EOS Here is an index entry for ((tigers)). indexterm:[Big cats,Tigers,Siberian Tiger] Here is an index entry for indexterm2:[Linux]. (((Operating Systems,Linux,Fedora))) Note that multi-entry terms generate separate index entries. EOS output = render_embedded_string input, :attributes => {'backend' => 'docbook45'} assert_xpath '/simpara', output, 1 term1 = (xmlnodes_at_xpath '(//indexterm)[1]', output, 1).first assert_equal '<indexterm><primary>tigers</primary></indexterm>', term1.to_s assert term1.next.content.start_with?('tigers') term2 = (xmlnodes_at_xpath '(//indexterm)[2]', output, 1).first term2_elements = term2.elements assert_equal 3, term2_elements.size assert_equal '<primary>Big cats</primary>', term2_elements[0].to_s assert_equal '<secondary>Tigers</secondary>', term2_elements[1].to_s assert_equal '<tertiary>Siberian Tiger</tertiary>', term2_elements[2].to_s term3 = (xmlnodes_at_xpath '(//indexterm)[3]', output, 1).first term3_elements = term3.elements assert_equal 2, term3_elements.size assert_equal '<primary>Tigers</primary>', term3_elements[0].to_s assert_equal '<secondary>Siberian Tiger</secondary>', term3_elements[1].to_s term4 = (xmlnodes_at_xpath '(//indexterm)[4]', output, 1).first term4_elements = term4.elements assert_equal 1, term4_elements.size assert_equal '<primary>Siberian Tiger</primary>', term4_elements[0].to_s term5 = (xmlnodes_at_xpath '(//indexterm)[5]', output, 1).first assert_equal '<indexterm><primary>Linux</primary></indexterm>', term5.to_s assert term5.next.content.start_with?('Linux') assert_xpath '(//indexterm)[6]/*', output, 3 assert_xpath '(//indexterm)[7]/*', output, 2 assert_xpath '(//indexterm)[8]/*', output, 1 end end context "code" do test "single-line literal paragraphs" do assert_xpath "//pre", render_string(" LITERALS\n\n ARE LITERALLY\n\n AWESOMMMME.") end test "multi-line literal paragraph" do input = <<-EOS Install instructions: yum install ruby rubygems gem install asciidoctor You're good to go! EOS output = render_string(input) assert_xpath "//pre", output, 1 assert_match(/^gem install asciidoctor/, output, "Indentation should be trimmed from literal block") end test "literal paragraph" do assert_xpath "//*[@class='literalblock']//pre[text()='blah blah blah']", render_string("[literal]\nblah blah blah") end test "listing paragraph" do assert_xpath "//*[@class='listingblock']//pre[text()='blah blah blah']", render_string("[listing]\nblah blah blah") end test "source code paragraph" do assert_xpath "//pre[@class='highlight']/code", render_string("[source]\nblah blah blah") end test "source code paragraph with language" do assert_xpath "//pre[@class='highlight']/code[@class='perl']", render_string("[source, perl]\ndie 'zomg perl sucks';") end end context "quote" do test "quote block" do output = render_string("____\nFamous quote.\n____") assert_xpath '//*[@class = "quoteblock"]', output, 1 assert_xpath '//*[@class = "quoteblock"]//p[text() = "Famous quote."]', output, 1 end test "quote block with attribution" do output = render_string("[quote, A famous person, A famous book (1999)]\n____\nFamous quote.\n____") assert_xpath '//*[@class = "quoteblock"]', output, 1 assert_xpath '//*[@class = "quoteblock"]/*[@class = "attribution"]', output, 1 assert_xpath '//*[@class = "quoteblock"]/*[@class = "attribution"]/cite[text() = "A famous book (1999)"]', output, 1 # TODO I can't seem to match the attribution (author) w/ xpath end test "quote block with section body" do output = render_string("____\nFamous quote.\n\nNOTE: That was inspiring.\n____") assert_xpath '//*[@class = "quoteblock"]', output, 1 assert_xpath '//*[@class = "quoteblock"]//*[@class = "admonitionblock"]', output, 1 end test "single-line quote paragraph" do output = render_string("[quote]\nFamous quote.") assert_xpath '//*[@class = "quoteblock"]', output, 1 assert_xpath '//*[@class = "quoteblock"]//p', output, 0 assert_xpath '//*[@class = "quoteblock"]//*[contains(text(), "Famous quote.")]', output, 1 end test "verse paragraph" do output = render_string("[verse]\nFamous verse.") assert_xpath '//*[@class = "verseblock"]', output, 1 assert_xpath '//*[@class = "verseblock"]/pre', output, 1 assert_xpath '//*[@class = "verseblock"]//p', output, 0 assert_xpath '//*[@class = "verseblock"]/pre[normalize-space(text()) = "Famous verse."]', output, 1 end test "single-line verse block" do output = render_string("[verse]\n____\nFamous verse.\n____") assert_xpath '//*[@class = "verseblock"]', output, 1 assert_xpath '//*[@class = "verseblock"]/pre', output, 1 assert_xpath '//*[@class = "verseblock"]//p', output, 0 assert_xpath '//*[@class = "verseblock"]/pre[normalize-space(text()) = "Famous verse."]', output, 1 end test "multi-line verse block" do output = render_string("[verse]\n____\nFamous verse.\n\nStanza two.\n____") assert_xpath '//*[@class = "verseblock"]', output, 1 assert_xpath '//*[@class = "verseblock"]/pre', output, 1 assert_xpath '//*[@class = "verseblock"]//p', output, 0 assert_xpath '//*[@class = "verseblock"]/pre[contains(text(), "Famous verse.")]', output, 1 assert_xpath '//*[@class = "verseblock"]/pre[contains(text(), "Stanza two.")]', output, 1 end test "verse block does not contain block elements" do output = render_string("[verse]\n____\nFamous verse.\n\n....\nnot a literal\n....\n____") assert_xpath '//*[@class = "verseblock"]', output, 1 assert_xpath '//*[@class = "verseblock"]/pre', output, 1 assert_xpath '//*[@class = "verseblock"]//p', output, 0 assert_xpath '//*[@class = "verseblock"]//*[@class = "literalblock"]', output, 0 end end context "special" do test "note multiline syntax" do Asciidoctor::ADMONITION_STYLES.each do |style| assert_xpath "//div[@class='admonitionblock']", render_string("[#{style}]\nThis is a winner.") end end test "note block syntax" do Asciidoctor::ADMONITION_STYLES.each do |style| assert_xpath "//div[@class='admonitionblock']", render_string("[#{style}]\n====\nThis is a winner.\n====") end end test "note inline syntax" do Asciidoctor::ADMONITION_STYLES.each do |style| assert_xpath "//div[@class='admonitionblock']", render_string("#{style}: This is important, fool!") end end test "sidebar block" do input = <<-EOS == Section .Sidebar **** Content goes here **** EOS result = render_string(input) assert_xpath "//*[@class='sidebarblock']//p", result, 1 end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/asciidoctor.gemspec
## This is the rakegem gemspec template. Make sure you read and understand ## all of the comments. Some sections require modification, and others can ## be deleted if you don't need them. Once you understand the contents of ## this file, feel free to delete any comments that begin with two hash marks. ## You can find comprehensive Gem::Specification documentation, at ## http://docs.rubygems.org/read/chapter/20 Gem::Specification.new do |s| s.specification_version = 2 if s.respond_to? :specification_version= s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.rubygems_version = '1.3.5' ## Leave these as is they will be modified for you by the rake gemspec task. ## If your rubyforge_project name is different, then edit it and comment out ## the sub! line in the Rakefile s.name = 'asciidoctor' s.version = '0.1.1' s.date = '2013-02-26' s.rubyforge_project = 'asciidoctor' ## Make sure your summary is short. The description may be as long ## as you like. s.summary = "Pure Ruby Asciidoc to HTML rendering." s.description = "A pure Ruby processor to turn Asciidoc-formatted documents into HTML (and, eventually, other formats perhaps)." ## List the primary authors. If there are a bunch of authors, it's probably ## better to set the email to an email list or something. If you don't have ## a custom homepage, consider using your GitHub URL or the like. s.authors = ["<NAME>", "<NAME>", "<NAME>"] s.email = '<EMAIL>' s.homepage = 'http://github.com/asciidoctor' ## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as ## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb' s.require_paths = %w[lib] ## If your gem includes any executables, list them here. s.executables = ["asciidoctor"] ## Specify any RDoc options here. You'll want to add your README and ## LICENSE files to the extra_rdoc_files list. s.rdoc_options = ["--charset=UTF-8"] s.extra_rdoc_files = %w[LICENSE] ## List your runtime dependencies here. Runtime dependencies are those ## that are needed for an end user to actually USE your code. ## List your development dependencies here. Development dependencies are ## those that are only needed during development s.add_development_dependency('coderay') s.add_development_dependency('erubis') s.add_development_dependency('htmlentities') s.add_development_dependency('mocha') s.add_development_dependency('nokogiri') s.add_development_dependency('pending') s.add_development_dependency('rake') s.add_development_dependency('rdoc', '~> 3.12') s.add_development_dependency('tilt') ## Leave this section as-is. It will be automatically generated from the ## contents of your Git repository via the gemspec task. DO NOT REMOVE ## THE MANIFEST COMMENTS, they are used as delimiters by the task. # = MANIFEST = s.files = %w[ Gemfile LICENSE README.asciidoc Rakefile asciidoctor.gemspec bin/asciidoctor bin/asciidoctor-safe lib/asciidoctor.rb lib/asciidoctor/abstract_block.rb lib/asciidoctor/abstract_node.rb lib/asciidoctor/attribute_list.rb lib/asciidoctor/backends/base_template.rb lib/asciidoctor/backends/docbook45.rb lib/asciidoctor/backends/html5.rb lib/asciidoctor/block.rb lib/asciidoctor/callouts.rb lib/asciidoctor/cli/invoker.rb lib/asciidoctor/cli/options.rb lib/asciidoctor/debug.rb lib/asciidoctor/document.rb lib/asciidoctor/errors.rb lib/asciidoctor/helpers.rb lib/asciidoctor/inline.rb lib/asciidoctor/lexer.rb lib/asciidoctor/list_item.rb lib/asciidoctor/reader.rb lib/asciidoctor/renderer.rb lib/asciidoctor/section.rb lib/asciidoctor/substituters.rb lib/asciidoctor/table.rb lib/asciidoctor/version.rb man/asciidoctor.1 man/asciidoctor.ad test/attributes_test.rb test/blocks_test.rb test/document_test.rb test/fixtures/asciidoc.txt test/fixtures/asciidoc_index.txt test/fixtures/ascshort.txt test/fixtures/dot.gif test/fixtures/encoding.asciidoc test/fixtures/include-file.asciidoc test/fixtures/list_elements.asciidoc test/fixtures/sample.asciidoc test/fixtures/tip.gif test/invoker_test.rb test/lexer_test.rb test/links_test.rb test/lists_test.rb test/options_test.rb test/paragraphs_test.rb test/preamble_test.rb test/reader_test.rb test/renderer_test.rb test/sections_test.rb test/substitutions_test.rb test/tables_test.rb test/test_helper.rb test/text_test.rb ] # = MANIFEST = ## Test files will be grabbed from the file list. Make sure the path glob ## matches what you actually use. s.test_files = s.files.select { |path| path =~ /^test\/.*_test\.rb/ } end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/abstract_node.rb
<gh_stars>0 module Asciidoctor # Public: An abstract base class that provides state and methods for managing a # node of AsciiDoc content. The state and methods on this class are comment to # all content segments in an AsciiDoc document. class AbstractNode include Substituters # Public: Get the element which is the parent of this node attr_reader :parent # Public: Get the Asciidoctor::Document to which this node belongs attr_reader :document # Public: Get the Symbol context for this node attr_reader :context # Public: Get the id of this node attr_accessor :id # Public: Get the Hash of attributes for this node attr_reader :attributes def initialize(parent, context) @parent = (context != :document ? parent : nil) if !parent.nil? @document = parent.is_a?(Document) ? parent : parent.document else @document = nil end @context = context @attributes = {} @passthroughs = [] end # Public: Get the value of the specified attribute # # Get the value for the specified attribute. First look in the attributes on # this node and return the value of the attribute if found. Otherwise, if # this node is a child of the Document node, look in the attributes of the # Document node and return the value of the attribute if found. Otherwise, # return the default value, which defaults to nil. # # name - the name of the attribute to lookup as a String or Symbol # default - the value to return if the attribute is not found (default: nil) # # return the value of the attribute or the default value if the attribute # is not found in the attributes of this node or the document node def attr(name, default = nil) name = name.to_s if name.is_a?(Symbol) if self == @document default.nil? ? @attributes[name] : @attributes.fetch(name, default) else default.nil? ? @attributes.fetch(name, @document.attr(name)) : @attributes.fetch(name, @document.attr(name, default)) end end # Public: Check if the attribute is defined, optionally performing a # comparison of its value # # Check if the attribute is defined. First look in the attributes on this # node. If not found, and this node is a child of the Document node, look in # the attributes of the Document node. If the attribute is found and a # comparison value is specified, return whether the two values match. # Otherwise, return whether the attribute was found. # # name - the name of the attribute to lookup as a String or Symbol # expect - the expected value of the attribute (default: nil) # # return a Boolean indicating whether the attribute exists and, if a # comparison value is specified, whether the value of the attribute matches # the comparison value def attr?(name, expect = nil) name = name.to_s if name.is_a?(Symbol) if expect.nil? if @attributes.has_key? name true elsif self != @document @document.attributes.has_key? name else false end else if @attributes.has_key? name @attributes[name] == expect elsif self != @document && @document.attributes.has_key?(name) @document.attributes[name] == expect else false end end end # Public: Get the execution context of this object (via Kernel#binding). # # This method is used to set the 'self' reference as well as local variables # that map to this method's arguments during the evaluation of a backend # template. # # Each object in Ruby has a binding context that can be used to set the 'self' # reference in an evaluation context. Any arguments passed to this # method are also available in the execution environment. # # template - The BaseTemplate instance in which this binding will be active. # Bound to the local variable of the same name, template. # # returns the execution context for this object so it can be be transferred to # the backend template and binds the method arguments as local variables in # that same environment. def get_binding template binding end # Public: Update the attributes of this node with the new values in # the attributes argument. # # If an attribute already exists with the same key, it's value will # be overridden. # # attributes - A Hash of attributes to assign to this node. # # returns nothing def update_attributes(attributes) @attributes.update(attributes) nil end # Public: Get the Asciidoctor::Renderer instance being used for the # Asciidoctor::Document to which this node belongs def renderer @document.renderer end # Public: Construct a reference or data URI to an icon image for the # specified icon name. # # If the 'icon' attribute is set on this block, the name is ignored and the # value of this attribute is used as the target image path. Otherwise, # construct a target image path by concatenating the value of the 'iconsdir' # attribute, the icon name and the value of the 'icontype' attribute # (defaulting to 'png'). # # The target image path is then passed through the #image_uri() method. If # the 'data-uri' attribute is set on the document, the image will be # safely converted to a data URI. # # The return value of this method can be safely used in an image tag. # # name - The String name of the icon # # Returns A String reference or data URI for an icon image def icon_uri(name) if attr? 'icon' image_uri(attr('icon'), nil) else image_uri(name + '.' + @document.attr('icontype', 'png'), 'iconsdir') end end # Public: Construct a reference or data URI to the target image. # # If the target image is a URI reference, then leave it untouched. # # The target image is resolved relative to the directory retrieved from the # specified attribute key, if provided. # # If the 'data-uri' attribute is set on the document, and the safe mode level # is less than SafeMode::SECURE, the image will be safely converted to a data URI # by reading it from the same directory. If neither of these conditions # are satisfied, a relative path (i.e., URL) will be returned. # # The return value of this method can be safely used in an image tag. # # target_image - A String path to the target image # asset_dir_key - The String attribute key used to lookup the directory where # the image is located (default: 'imagesdir') # # Returns A String reference or data URI for the target image def image_uri(target_image, asset_dir_key = 'imagesdir') if target_image.include?(':') && target_image.match(Asciidoctor::REGEXP[:uri_sniff]) target_image elsif @document.safe < Asciidoctor::SafeMode::SECURE && @document.attr?('data-uri') generate_data_uri(target_image, asset_dir_key) elsif asset_dir_key && attr?(asset_dir_key) File.join(@document.attr(asset_dir_key), target_image) else target_image end end # Public: Generate a data URI that can be used to embed an image in the output document # # First, and foremost, the target image path is cleaned if the document safe mode level # is set to at least SafeMode::SAFE (a condition which is true by default) to prevent access # to ancestor paths in the filesystem. The image data is then read and converted to # Base64. Finally, a data URI is built which can be used in an image tag. # # target_image - A String path to the target image # asset_dir_key - The String attribute key used to lookup the directory where # the image is located (default: nil) # # Returns A String data URI containing the content of the target image def generate_data_uri(target_image, asset_dir_key = nil) Helpers.require_library 'base64' mimetype = 'image/' + File.extname(target_image)[1..-1] if asset_dir_key image_path = File.join(normalize_asset_path(@document.attr(asset_dir_key, '.'), asset_dir_key), target_image) else image_path = normalize_asset_path(target_image) end bindata = nil if IO.respond_to? :binread bindata = IO.binread(image_path) else bindata = File.open(image_path, 'rb') {|file| file.read } end 'data:' + mimetype + ';base64,' + Base64.encode64(bindata).delete("\n") end # Public: Normalize the asset file or directory to a concrete and rinsed path # # The most important functionality in this method is to prevent the asset # reference from resolving to a directory outside of the chroot directory # (which defaults to the directory of the source file, stored in the base_dir # instance variable on Document) if the document safe level is set to # SafeMode::SAFE or greater (a condition which is true by default). # # asset_ref - the String asset file or directory referenced in the document # or configuration attribute # asset_name - the String name of the file or directory being resolved (for use in # the warning message) (default: 'path') # # Examples # # # given these fixtures # document.base_dir # # => "/path/to/chroot" # document.safe >= Asciidoctor::SafeMode::SAFE # # => true # # # then # normalize_asset_path('images') # # => "/path/to/chroot/images" # normalize_asset_path('/etc/images') # # => "/path/to/chroot/images" # normalize_asset_path('../images') # # => "/path/to/chroot/images" # # # given these fixtures # document.base_dir # # => "/path/to/chroot" # document.safe >= Asciidoctor::SafeMode::SAFE # # => false # # # then # normalize_asset_path('images') # # => "/path/to/chroot/images" # normalize_asset_path('/etc/images') # # => "/etc/images" # normalize_asset_path('../images') # # => "/path/to/images" # # Returns The normalized asset file or directory as a String path #-- # TODO this method is missing a coordinate; it should be able to resolve # both the directory reference and the path to an asset in it; callers # of this method are still doing a File.join to finish the task def normalize_asset_path(asset_ref, asset_name = 'path', autocorrect = true) # TODO we may use pathname enough to make it a top-level require Helpers.require_library 'pathname' input_path = @document.base_dir asset_path = Pathname.new(asset_ref) if asset_path.relative? asset_path = File.expand_path(File.join(input_path, asset_ref)) else asset_path = asset_path.cleanpath.to_s end if @document.safe >= SafeMode::SAFE relative_asset_path = Pathname.new(asset_path).relative_path_from(Pathname.new(input_path)).to_s if relative_asset_path.start_with?('..') if autocorrect puts "asciidoctor: WARNING: #{asset_name} has illegal reference to ancestor of base directory" else raise SecurityError, "#{asset_name} has reference to path outside of base directory, disallowed in safe mode: #{asset_path}" end relative_asset_path.sub!(/^(?:\.\.\/)*/, '') # just to be absolutely sure ;) if relative_asset_path[0..0] == '.' raise 'Substitution of parent path references failed for ' + relative_asset_path end asset_path = File.expand_path(File.join(input_path, relative_asset_path)) end end asset_path end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/list_item.rb
<gh_stars>0 module Asciidoctor # Public: Methods for managing items for AsciiDoc olists, ulist, and dlists. class ListItem < AbstractBlock # Public: Get/Set the String used to mark this list item attr_accessor :marker # Public: Initialize an Asciidoctor::ListItem object. # # parent - The parent list block for this list item # text - the String text (default nil) def initialize(parent, text = nil) super(parent, :list_item) @text = text @level = parent.level end def text? !@text.to_s.empty? end def text # this will allow the text to be processed Block.new(self, nil, [@text]).content end def content blocks? ? blocks.map {|b| b.render }.join : nil end # Public: Fold the first paragraph block into the text # # Here are the rules for when a folding occurs: # # Given: this list item has at least one block # When: the first block is a paragraph that's not connected by a list continuation # Or: the first block is an indented paragraph that's adjacent (wrapped line) # Or: the first block is an indented paragraph that's not connected by a list continuation # Then: then drop the first block and fold it's content (buffer) into the list text # # Returns nothing def fold_first(continuation_connects_first_block = false, content_adjacent = false) if !blocks.empty? && blocks.first.is_a?(Block) && ((blocks.first.context == :paragraph && !continuation_connects_first_block) || ((content_adjacent || !continuation_connects_first_block) && blocks.first.context == :literal && blocks.first.attr('options', []).include?('listparagraph'))) block = blocks.shift unless @text.to_s.empty? block.buffer.unshift("#@text\n") end @text = block.buffer.join end nil end def splain(parent_level = 0) parent_level += 1 Debug.puts_indented(parent_level, "List Item anchor: #{@anchor}") unless @anchor.nil? Debug.puts_indented(parent_level, "Text: #{@text}") unless @text.nil? Debug.puts_indented(parent_level, "Blocks: #{@blocks.count}") if @blocks.any? Debug.puts_indented(parent_level, "Blocks content (#{@blocks.count}):") @blocks.each_with_index do |block, i| Debug.puts_indented(parent_level, "v" * (60 - parent_level*2)) Debug.puts_indented(parent_level, "Block ##{i} is a #{block.class}") Debug.puts_indented(parent_level, "Name is #{block.title rescue 'n/a'}") Debug.puts_indented(parent_level, "=" * 40) block.splain(parent_level) if block.respond_to? :splain Debug.puts_indented(parent_level, "^" * (60 - parent_level*2)) end end nil end def to_s "#{super.to_s} - #@context [text:#@text, blocks:#{(@blocks || []).size}]" end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/specifications/asciidoctor-0.1.0.gemspec
<filename>src/main/resources/ruby/1.9.1/specifications/asciidoctor-0.1.0.gemspec # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "asciidoctor" s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>", "<NAME>", "<NAME>"] s.date = "2013-02-04" s.description = "A pure Ruby processor to turn Asciidoc-formatted documents into HTML (and, eventually, other formats perhaps)." s.email = "<EMAIL>" s.executables = ["asciidoctor"] s.extra_rdoc_files = ["LICENSE"] s.files = ["bin/asciidoctor", "LICENSE"] s.homepage = "http://github.com/asciidoctor" s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubyforge_project = "asciidoctor" s.rubygems_version = "1.8.25" s.summary = "Pure Ruby Asciidoc to HTML rendering." if s.respond_to? :specification_version then s.specification_version = 2 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<coderay>, [">= 0"]) s.add_development_dependency(%q<erubis>, [">= 0"]) s.add_development_dependency(%q<htmlentities>, [">= 0"]) s.add_development_dependency(%q<mocha>, [">= 0"]) s.add_development_dependency(%q<nokogiri>, [">= 0"]) s.add_development_dependency(%q<pending>, [">= 0"]) s.add_development_dependency(%q<rake>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<tilt>, [">= 0"]) else s.add_dependency(%q<coderay>, [">= 0"]) s.add_dependency(%q<erubis>, [">= 0"]) s.add_dependency(%q<htmlentities>, [">= 0"]) s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<nokogiri>, [">= 0"]) s.add_dependency(%q<pending>, [">= 0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<tilt>, [">= 0"]) end else s.add_dependency(%q<coderay>, [">= 0"]) s.add_dependency(%q<erubis>, [">= 0"]) s.add_dependency(%q<htmlentities>, [">= 0"]) s.add_dependency(%q<mocha>, [">= 0"]) s.add_dependency(%q<nokogiri>, [">= 0"]) s.add_dependency(%q<pending>, [">= 0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<tilt>, [">= 0"]) end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/reader_test.rb
<gh_stars>0 require 'test_helper' class ReaderTest < Test::Unit::TestCase # setup for test def setup @src_data = File.readlines(sample_doc_path(:asciidoc_index)) @reader = Asciidoctor::Reader.new @src_data end context "has_more_lines?" do test "returns false for empty document" do assert !Asciidoctor::Reader.new.has_more_lines? end test "returns true with lines remaining" do assert @reader.has_more_lines?, "Yo, didn't work" end end context "with source data loaded" do test "get_line returns next line" do assert_equal @src_data[0], @reader.get_line end test "get_line consumes the line it returns" do reader = Asciidoctor::Reader.new(["foo", "bar"]) _ = reader.get_line second = reader.get_line assert_equal "bar", second end test "peek_line does not consume the line it returns" do reader = Asciidoctor::Reader.new(["foo", "bar"]) _ = reader.peek_line second = reader.peek_line assert_equal "foo", second end test "unshift puts line onto Reader instance for the next get_line" do reader = Asciidoctor::Reader.new(["foo"]) reader.unshift("bar") assert_equal "bar", reader.get_line assert_equal "foo", reader.get_line end end context "Grab lines" do test "Grab until end" do input = <<-EOS This is one paragraph. This is another paragraph. EOS lines = input.lines.entries reader = Asciidoctor::Reader.new(lines) result = reader.grab_lines_until assert_equal 3, result.size assert_equal lines, result assert !reader.has_more_lines? assert reader.empty? end test "Grab until blank line" do input = <<-EOS This is one paragraph. This is another paragraph. EOS lines = input.lines.entries reader = Asciidoctor::Reader.new(lines) result = reader.grab_lines_until :break_on_blank_lines => true assert_equal 1, result.size assert_equal lines.first, result.first assert_equal lines.last, reader.peek_line end test "Grab until blank line preserving last line" do input = <<-EOS This is one paragraph. This is another paragraph. EOS lines = input.lines.entries reader = Asciidoctor::Reader.new(lines) result = reader.grab_lines_until :break_on_blank_lines => true, :preserve_last_line => true assert_equal 1, result.size assert_equal lines.first, result.first assert_equal "\n", reader.peek_line end test "Grab until condition" do input = <<-EOS -- This is one paragraph inside the block. This is another paragraph inside the block. -- This is a paragraph outside the block. EOS lines = input.lines.entries reader = Asciidoctor::Reader.new(lines) reader.get_line result = reader.grab_lines_until {|line| line.chomp == '--' } assert_equal 3, result.size assert_equal lines[1, 3], result assert_equal "\n", reader.peek_line end test "Grab until condition with last line" do input = <<-EOS -- This is one paragraph inside the block. This is another paragraph inside the block. -- This is a paragraph outside the block. EOS lines = input.lines.entries reader = Asciidoctor::Reader.new(lines) reader.get_line result = reader.grab_lines_until(:grab_last_line => true) {|line| line.chomp == '--' } assert_equal 4, result.size assert_equal lines[1, 4], result assert_equal "\n", reader.peek_line end test "Grab until condition with last line and preserving last line" do input = <<-EOS -- This is one paragraph inside the block. This is another paragraph inside the block. -- This is a paragraph outside the block. EOS lines = input.lines.entries reader = Asciidoctor::Reader.new(lines) reader.get_line result = reader.grab_lines_until(:grab_last_line => true, :preserve_last_line => true) {|line| line.chomp == '--' } assert_equal 4, result.size assert_equal lines[1, 4], result assert_equal "--\n", reader.peek_line end end context 'Include Macro' do test 'include macro is disabled by default' do input = <<-EOS include::include-file.asciidoc[] EOS para = block_from_string input, :attributes => { 'include-depth' => 0 } assert_equal 1, para.buffer.size assert_equal 'include::include-file.asciidoc[]', para.buffer.join end test 'include macro is enabled when safe mode is less than SECURE' do input = <<-EOS include::fixtures/include-file.asciidoc[] EOS doc = document_from_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'docdir' => File.dirname(__FILE__)} output = doc.render assert_match(/included content/, output) end test "block is called to handle an include macro" do input = <<-EOS first line include::include-file.asciidoc[] last line EOS doc = Asciidoctor::Document.new [], :safe => Asciidoctor::SafeMode::SAFE reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) {|inc| ":includefile: #{inc}\n\nmiddle line".lines.entries } lines = [] while reader.has_more_lines? lines << reader.get_line end assert_match(/^:includefile: include-file.asciidoc$/, lines.join) end test 'escaped include macro is left unprocessed' do input = <<-EOS \\include::include-file.asciidoc[] EOS para = block_from_string input assert_equal 1, para.buffer.size assert_equal 'include::include-file.asciidoc[]', para.buffer.join end test 'include macro not at start of line is ignored' do input = <<-EOS include::include-file.asciidoc[] EOS para = block_from_string input assert_equal 1, para.buffer.size # NOTE the space gets stripped because the line is treated as an inline literal assert_equal :literal, para.context assert_equal 'include::include-file.asciidoc[]', para.buffer.join end test 'include macro is disabled when include-depth attribute is 0' do input = <<-EOS include::include-file.asciidoc[] EOS para = block_from_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => { 'include-depth' => 0 } assert_equal 1, para.buffer.size assert_equal 'include::include-file.asciidoc[]', para.buffer.join end test 'include-depth cannot be set by document' do input = <<-EOS :include-depth: 1 include::include-file.asciidoc[] EOS para = block_from_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => { 'include-depth' => 0 } assert_equal 1, para.buffer.size assert_equal 'include::include-file.asciidoc[]', para.buffer.join end end context 'build secure asset path' do test 'allows us to specify a path relative to the current dir' do doc = Asciidoctor::Document.new Asciidoctor::Reader.new([], doc, true) legit_path = Dir.pwd + "/foo" assert_equal legit_path, doc.normalize_asset_path(legit_path) end test "keeps naughty absolute paths from getting outside" do naughty_path = "#{disk_root}etc/passwd" doc = Asciidoctor::Document.new Asciidoctor::Reader.new([], doc, true) secure_path = doc.normalize_asset_path(naughty_path) assert naughty_path != secure_path assert_match(/^#{doc.base_dir}/, secure_path) end test "keeps naughty relative paths from getting outside" do naughty_path = "safe/ok/../../../../../etc/passwd" doc = Asciidoctor::Document.new Asciidoctor::Reader.new([], doc, true) secure_path = doc.normalize_asset_path(naughty_path) assert naughty_path != secure_path assert_match(/^#{doc.base_dir}/, secure_path) end end context 'Conditional Inclusions' do test 'preprocess_next_line returns true if cursor advanced' do input = <<-EOS ifdef::asciidoctor[] Asciidoctor! endif::asciidoctor[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) assert reader.preprocess_next_line == true end test 'preprocess_next_line returns false if cursor not advanced' do input = <<-EOS content ifdef::asciidoctor[] Asciidoctor! endif::asciidoctor[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) assert reader.preprocess_next_line == false end test 'preprocess_next_line returns nil if cursor advanced past end of source' do input = <<-EOS ifdef::foobar[] swallowed content endif::foobar[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) assert reader.preprocess_next_line.nil? end test 'ifdef with defined attribute includes block' do input = <<-EOS ifdef::holygrail[] There is a holy grail! endif::holygrail[] EOS doc = Asciidoctor::Document.new [], :attributes => {'holygrail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'There is a holy grail!', lines.join.strip end test 'ifdef with defined attribute includes text in brackets' do input = <<-EOS On our quest we go... ifdef::holygrail[There is a holy grail!] There was much rejoicing. EOS doc = Asciidoctor::Document.new [], :attributes => {'holygrail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "On our quest we go...\nThere is a holy grail!\nThere was much rejoicing.", lines.join.strip end test 'include with non-matching nested exclude' do input = <<-EOS ifdef::grail[] holy ifdef::swallow[] swallow endif::swallow[] grail endif::grail[] EOS doc = Asciidoctor::Document.new [], :attributes => {'grail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "holy\ngrail", lines.join.strip end test 'nested excludes with same condition' do input = <<-EOS ifndef::grail[] ifndef::grail[] not here endif::grail[] endif::grail[] EOS doc = Asciidoctor::Document.new [], :attributes => {'grail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal '', lines.join.strip end test 'include with nested exclude of inverted condition' do input = <<-EOS ifdef::grail[] holy ifndef::grail[] not here endif::grail[] grail endif::grail[] EOS doc = Asciidoctor::Document.new [], :attributes => {'grail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "holy\ngrail", lines.join.strip end test 'exclude with matching nested exclude' do input = <<-EOS poof ifdef::swallow[] no ifdef::swallow[] swallow endif::swallow[] here endif::swallow[] gone EOS doc = Asciidoctor::Document.new [], :attributes => {'grail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "poof\ngone", lines.join.strip end test 'exclude with nested include using shorthand end' do input = <<-EOS poof ifndef::grail[] no grail ifndef::swallow[] or swallow endif::[] in here endif::[] gone EOS doc = Asciidoctor::Document.new [], :attributes => {'grail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "poof\ngone", lines.join.strip end test 'ifdef with one alternative attribute set includes content' do input = <<-EOS ifdef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS doc = Asciidoctor::Document.new [], :attributes => {'swallow' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Our quest is complete!', lines.join.strip end test 'ifdef with no alternative attributes set does not include content' do input = <<-EOS ifdef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal '', lines.join.strip end test 'ifdef with all required attributes set includes content' do input = <<-EOS ifdef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS doc = Asciidoctor::Document.new [], :attributes => {'holygrail' => '', 'swallow' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Our quest is complete!', lines.join.strip end test 'ifdef with missing required attributes does not include content' do input = <<-EOS ifdef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS doc = Asciidoctor::Document.new [], :attributes => {'holygrail' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal '', lines.join.strip end test 'ifndef with undefined attribute includes block' do input = <<-EOS ifndef::holygrail[] Our quest continues to find the holy grail! endif::holygrail[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Our quest continues to find the holy grail!', lines.join.strip end test 'ifndef with one alternative attribute set includes content' do input = <<-EOS ifndef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS doc = Asciidoctor::Document.new [], :attributes => {'swallow' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Our quest is complete!', lines.join.strip end test 'ifndef with no alternative attributes set includes content' do input = <<-EOS ifndef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Our quest is complete!', lines.join.strip end test 'ifndef with any required attributes set does not include content' do input = <<-EOS ifndef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS doc = Asciidoctor::Document.new [], :attributes => {'swallow' => ''} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal '', lines.join.strip end test 'ifndef with no required attributes set includes content' do input = <<-EOS ifndef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Our quest is complete!', lines.join.strip end test 'escaped ifdef is unescaped and ignored' do input = <<-EOS \\ifdef::holygrail[] content \\endif::holygrail[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "ifdef::holygrail[]\ncontent\nendif::holygrail[]", lines.join.strip end test 'ifeval comparing double-quoted attribute to matching string is included' do input = <<-EOS ifeval::["{gem}" == "asciidoctor"] Asciidoctor it is! endif::[] EOS doc = Asciidoctor::Document.new [], :attributes => {'gem' => 'asciidoctor'} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Asciidoctor it is!', lines.join.strip end test 'ifeval comparing single-quoted attribute to matching string is included' do input = <<-EOS ifeval::['{gem}' == 'asciidoctor'] Asciidoctor it is! endif::[] EOS doc = Asciidoctor::Document.new [], :attributes => {'gem' => 'asciidoctor'} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Asciidoctor it is!', lines.join.strip end test 'ifeval comparing quoted attribute to non-matching string is ignored' do input = <<-EOS ifeval::['{gem}' == 'asciidoctor'] Asciidoctor it is! endif::[] EOS doc = Asciidoctor::Document.new [], :attributes => {'gem' => 'tilt'} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal '', lines.join.strip end test 'ifeval comparing attribute to lower version number is included' do input = <<-EOS ifeval::['{asciidoctor-version}' >= '0.1.0'] That version will do! endif::[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'That version will do!', lines.join.strip end test 'ifeval comparing attribute to self is included' do input = <<-EOS ifeval::['{asciidoctor-version}' == '{asciidoctor-version}'] Of course it's the same! endif::[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'Of course it\'s the same!', lines.join.strip end test 'ifeval arguments can be mirrored' do input = <<-EOS ifeval::["0.1.0" <= "{asciidoctor-version}"] That version will do! endif::[] EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'That version will do!', lines.join.strip end test 'ifeval matching numeric comparison is included' do input = <<-EOS ifeval::[{rings} == 1] One ring to rule them all! endif::[] EOS doc = Asciidoctor::Document.new [], :attributes => {'rings' => 1} reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal 'One ring to rule them all!', lines.join.strip end test 'ifdef with no target is ignored' do input = <<-EOS ifdef::[] content EOS doc = Asciidoctor::Document.new reader = Asciidoctor::Reader.new(input.lines.entries, doc, true) lines = [] while reader.has_more_lines? lines << reader.get_line end assert_equal "ifdef::[]\ncontent", lines.join.strip end end context 'Text processing' do test 'should clean CRLF from end of lines' do input = <<-EOS source\r with\r CRLF\r endlines\r EOS reader = Asciidoctor::Reader.new(input.lines.entries, Asciidoctor::Document.new, true) reader.lines.each do |line| assert !line.end_with?("\r\n") end end test 'sanitize attribute name' do assert_equal 'foobar', @reader.sanitize_attribute_name("Foo Bar") assert_equal 'foo', @reader.sanitize_attribute_name("foo") assert_equal 'foo3-bar', @reader.sanitize_attribute_name("Foo 3^ # - Bar[") end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/substitutions_test.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin<gh_stars>0 require 'test_helper' # TODO # - test negatives # - test role on every quote type context 'Substitutions' do context 'Dispatcher' do test 'apply normal substitutions' do para = block_from_string("[blue]'http://asciidoc.org[AsciiDoc]' & [red]*Ruby*\n&#167; Making +++<u>documentation</u>+++ together +\nsince (C) {inception_year}.") para.document.attributes['inception_year'] = '2012' result = para.apply_normal_subs(para.buffer) assert_equal %{<em><span class="blue"><a href="http://asciidoc.org">AsciiDoc</a></span></em> &amp; <strong><span class="red">Ruby</span></strong>\n&#167; Making <u>documentation</u> together<br>\nsince &#169; 2012.}, result end end context 'Quotes' do test 'single-line double-quoted string' do para = block_from_string(%q{``a few quoted words''}) assert_equal '&#8220;a few quoted words&#8221;', para.sub_quotes(para.buffer.join) end test 'escaped single-line double-quoted string' do para = block_from_string(%q{\``a few quoted words''}) assert_equal %q(&#8216;`a few quoted words&#8217;'), para.sub_quotes(para.buffer.join) end test 'multi-line double-quoted string' do para = block_from_string(%Q{``a few\nquoted words''}) assert_equal "&#8220;a few\nquoted words&#8221;", para.sub_quotes(para.buffer.join) end test 'double-quoted string with inline single quote' do para = block_from_string(%q{``Here's Johnny!''}) assert_equal %q{&#8220;Here's Johnny!&#8221;}, para.sub_quotes(para.buffer.join) end test 'double-quoted string with inline backquote' do para = block_from_string(%q{``Here`s Johnny!''}) assert_equal %q{&#8220;Here`s Johnny!&#8221;}, para.sub_quotes(para.buffer.join) end test 'single-line single-quoted string' do para = block_from_string(%q{`a few quoted words'}) assert_equal '&#8216;a few quoted words&#8217;', para.sub_quotes(para.buffer.join) end test 'escaped single-line single-quoted string' do para = block_from_string(%q{\`a few quoted words'}) assert_equal %(`a few quoted words'), para.sub_quotes(para.buffer.join) end test 'multi-line single-quoted string' do para = block_from_string(%Q{`a few\nquoted words'}) assert_equal "&#8216;a few\nquoted words&#8217;", para.sub_quotes(para.buffer.join) end test 'single-quoted string with inline single quote' do para = block_from_string(%q{`That isn't what I did.'}) assert_equal %q{&#8216;That isn't what I did.&#8217;}, para.sub_quotes(para.buffer.join) end test 'single-quoted string with inline backquote' do para = block_from_string(%q{`Here`s Johnny!'}) assert_equal %q{&#8216;Here`s Johnny!&#8217;}, para.sub_quotes(para.buffer.join) end test 'single-line constrained unquoted string' do para = block_from_string(%q{#a few words#}) assert_equal 'a few words', para.sub_quotes(para.buffer.join) end test 'escaped single-line constrained unquoted string' do para = block_from_string(%q{\#a few words#}) assert_equal '#a few words#', para.sub_quotes(para.buffer.join) end test 'multi-line constrained unquoted string' do para = block_from_string(%Q{#a few\nwords#}) assert_equal "a few\nwords", para.sub_quotes(para.buffer.join) end test 'single-line unconstrained unquoted string' do para = block_from_string(%q{##--anything goes ##}) assert_equal '--anything goes ', para.sub_quotes(para.buffer.join) end test 'escaped single-line unconstrained unquoted string' do para = block_from_string(%q{\##--anything goes ##}) assert_equal '#--anything goes #', para.sub_quotes(para.buffer.join) end test 'multi-line unconstrained unquoted string' do para = block_from_string(%Q{##--anything\ngoes ##}) assert_equal "--anything\ngoes ", para.sub_quotes(para.buffer.join) end test 'single-line constrained strong string' do para = block_from_string(%q{*a few strong words*}) assert_equal '<strong>a few strong words</strong>', para.sub_quotes(para.buffer.join) end test 'escaped single-line constrained strong string' do para = block_from_string(%q{\*a few strong words*}) assert_equal '*a few strong words*', para.sub_quotes(para.buffer.join) end test 'multi-line constrained strong string' do para = block_from_string(%Q{*a few\nstrong words*}) assert_equal "<strong>a few\nstrong words</strong>", para.sub_quotes(para.buffer.join) end test 'constrained strong string containing an asterisk' do para = block_from_string(%q{*bl*ck*-eye}) assert_equal '<strong>bl*ck</strong>-eye', para.sub_quotes(para.buffer.join) end test 'single-line constrained quote variation emphasized string' do para = block_from_string(%q{'a few emphasized words'}) assert_equal '<em>a few emphasized words</em>', para.sub_quotes(para.buffer.join) end test 'escaped single-line constrained quote variation emphasized string' do para = block_from_string(%q{\'a few emphasized words'}) assert_equal %q('a few emphasized words'), para.sub_quotes(para.buffer.join) end test 'multi-line constrained emphasized quote variation string' do para = block_from_string(%Q{'a few\nemphasized words'}) assert_equal "<em>a few\nemphasized words</em>", para.sub_quotes(para.buffer.join) end test 'single-quoted string containing an emphasized phrase' do para = block_from_string(%q{`I told him, 'Just go for it!''}) assert_equal '&#8216;I told him, <em>Just go for it!</em>&#8217;', para.sub_quotes(para.buffer.join) end test 'escaped single-quotes inside emphasized words are restored' do para = block_from_string(%q{'Here\'s Johnny!'}) # NOTE the \' is replaced with ' by the :replacements substitution, later in the substitution pipeline assert_equal %q{<em>Here\'s Johnny!</em>}, para.sub_quotes(para.buffer.join) end test 'single-line constrained emphasized underline variation string' do para = block_from_string(%q{_a few emphasized words_}) assert_equal '<em>a few emphasized words</em>', para.sub_quotes(para.buffer.join) end test 'escaped single-line constrained emphasized underline variation string' do para = block_from_string(%q{\_a few emphasized words_}) assert_equal '_a few emphasized words_', para.sub_quotes(para.buffer.join) end test 'multi-line constrained emphasized underline variation string' do para = block_from_string(%Q{_a few\nemphasized words_}) assert_equal "<em>a few\nemphasized words</em>", para.sub_quotes(para.buffer.join) end test 'single-line constrained monospaced string' do para = block_from_string(%q{`a few <\{monospaced\}> words`}) # NOTE must use apply_normal_subs because constrained monospaced is handled as a passthrough assert_equal '<tt>a few &lt;{monospaced}&gt; words</tt>', para.apply_normal_subs(para.buffer) end test 'escaped single-line constrained monospaced string' do para = block_from_string(%q{\`a few <monospaced> words`}) # NOTE must use apply_normal_subs because constrained monospaced is handled as a passthrough assert_equal '`a few &lt;monospaced&gt; words`', para.apply_normal_subs(para.buffer) end test 'multi-line constrained monospaced string' do para = block_from_string(%Q{`a few\n<\{monospaced\}> words`}) # NOTE must use apply_normal_subs because constrained monospaced is handled as a passthrough assert_equal "<tt>a few\n&lt;{monospaced}&gt; words</tt>", para.apply_normal_subs(para.buffer) end test 'single-line unconstrained strong chars' do para = block_from_string(%q{**Git**Hub}) assert_equal '<strong>Git</strong>Hub', para.sub_quotes(para.buffer.join) end test 'escaped single-line unconstrained strong chars' do para = block_from_string(%q{\**Git**Hub}) assert_equal '<strong>*Git</strong>*Hub', para.sub_quotes(para.buffer.join) end test 'multi-line unconstrained strong chars' do para = block_from_string(%Q{**G\ni\nt\n**Hub}) assert_equal "<strong>G\ni\nt\n</strong>Hub", para.sub_quotes(para.buffer.join) end test 'unconstrained strong chars with inline asterisk' do para = block_from_string(%q{**bl*ck**-eye}) assert_equal '<strong>bl*ck</strong>-eye', para.sub_quotes(para.buffer.join) end test 'unconstrained strong chars with role' do para = block_from_string(%q{Git[blue]**Hub**}) assert_equal %q{Git<strong><span class="blue">Hub</span></strong>}, para.sub_quotes(para.buffer.join) end # TODO this is not the same result as AsciiDoc, though I don't understand why AsciiDoc gets what it gets test 'escaped unconstrained strong chars with role' do para = block_from_string(%q{Git\[blue]**Hub**}) assert_equal %q{Git[blue]<strong>*Hub</strong>*}, para.sub_quotes(para.buffer.join) end test 'single-line unconstrained emphasized chars' do para = block_from_string(%q{__Git__Hub}) assert_equal '<em>Git</em>Hub', para.sub_quotes(para.buffer.join) end test 'escaped single-line unconstrained emphasized chars' do para = block_from_string(%q{\__Git__Hub}) assert_equal '__Git__Hub', para.sub_quotes(para.buffer.join) end test 'multi-line unconstrained emphasized chars' do para = block_from_string(%Q{__G\ni\nt\n__Hub}) assert_equal "<em>G\ni\nt\n</em>Hub", para.sub_quotes(para.buffer.join) end test 'unconstrained emphasis chars with role' do para = block_from_string(%q{[gray]__Git__Hub}) assert_equal %q{<em><span class="gray">Git</span></em>Hub}, para.sub_quotes(para.buffer.join) end test 'escaped unconstrained emphasis chars with role' do para = block_from_string(%q{\[gray]__Git__Hub}) assert_equal %q{[gray]__Git__Hub}, para.sub_quotes(para.buffer.join) end test 'single-line unconstrained monospaced chars' do para = block_from_string(%q{Git++Hub++}) assert_equal 'Git<tt>Hub</tt>', para.sub_quotes(para.buffer.join) end test 'escaped single-line unconstrained monospaced chars' do para = block_from_string(%q{Git\++Hub++}) assert_equal 'Git+<tt>Hub</tt>+', para.sub_quotes(para.buffer.join) end test 'multi-line unconstrained monospaced chars' do para = block_from_string(%Q{Git++\nH\nu\nb++}) assert_equal "Git<tt>\nH\nu\nb</tt>", para.sub_quotes(para.buffer.join) end test 'single-line superscript chars' do para = block_from_string(%q{x^2^ = x * x, e = mc^2^, there's a 1^st^ time for everything}) assert_equal 'x<sup>2</sup> = x * x, e = mc<sup>2</sup>, there\'s a 1<sup>st</sup> time for everything', para.sub_quotes(para.buffer.join) end test 'escaped single-line superscript chars' do para = block_from_string(%q{x\^2^ = x * x}) assert_equal 'x^2^ = x * x', para.sub_quotes(para.buffer.join) end test 'multi-line superscript chars' do para = block_from_string(%Q{x^(n\n+\n1)^}) assert_equal "x<sup>(n\n+\n1)</sup>", para.sub_quotes(para.buffer.join) end test 'single-line subscript chars' do para = block_from_string(%q{H~2~O}) assert_equal 'H<sub>2</sub>O', para.sub_quotes(para.buffer.join) end test 'escaped single-line subscript chars' do para = block_from_string(%q{H\~2~O}) assert_equal 'H~2~O', para.sub_quotes(para.buffer.join) end test 'multi-line subscript chars' do para = block_from_string(%Q{project~ view\non\nGitHub~}) assert_equal "project<sub> view\non\nGitHub</sub>", para.sub_quotes(para.buffer.join) end end context 'Macros' do test 'a single-line link macro should be interpreted as a link' do para = block_from_string('link:/home.html[]') assert_equal %q{<a href="/home.html">/home.html</a>}, para.sub_macros(para.buffer.join) end test 'a single-line link macro with text should be interpreted as a link' do para = block_from_string('link:/home.html[Home]') assert_equal %q{<a href="/home.html">Home</a>}, para.sub_macros(para.buffer.join) end test 'a single-line raw url should be interpreted as a link' do para = block_from_string('http://google.com') assert_equal %q{<a href="http://google.com">http://google.com</a>}, para.sub_macros(para.buffer.join) end test 'a single-line raw url with text should be interpreted as a link' do para = block_from_string('http://google.com[Google]') assert_equal %q{<a href="http://google.com">Google</a>}, para.sub_macros(para.buffer.join) end test 'a multi-line raw url with text should be interpreted as a link' do para = block_from_string("http://google.com[Google\nHomepage]") assert_equal %{<a href="http://google.com">Google\nHomepage</a>}, para.sub_macros(para.buffer.join) end test 'a multi-line raw url with attribute as text should be interpreted as a link with resolved attribute' do para = block_from_string("http://google.com[{google_homepage}]") para.document.attributes['google_homepage'] = 'Google Homepage' assert_equal %q{<a href="http://google.com">Google Homepage</a>}, para.sub_macros(para.buffer.join) end test 'a single-line escaped raw url should not be interpreted as a link' do para = block_from_string('\http://google.com') assert_equal %q{http://google.com}, para.sub_macros(para.buffer.join) end test 'a single-line image macro should be interpreted as an image' do para = block_from_string('image:tiger.png[]') assert_equal %{<span class="image"><img src="tiger.png" alt="tiger"></span>}, para.sub_macros(para.buffer.join).gsub(/>\s+</, '><') end test 'a single-line image macro with text should be interpreted as an image with alt text' do para = block_from_string('image:tiger.png[Tiger]') assert_equal %{<span class="image"><img src="tiger.png" alt="Tiger"></span>}, para.sub_macros(para.buffer.join).gsub(/>\s+</, '><') end test 'a single-line image macro with text and dimensions should be interpreted as an image with alt text and dimensions' do para = block_from_string('image:tiger.png[Tiger, 200, 100]') assert_equal %{<span class="image"><img src="tiger.png" alt="Tiger" width="200" height="100"></span>}, para.sub_macros(para.buffer.join).gsub(/>\s+</, '><') end test 'a single-line image macro with text and link should be interpreted as a linked image with alt text' do para = block_from_string('image:tiger.png[Tiger, link="http://en.wikipedia.org/wiki/Tiger"]') assert_equal %{<span class="image"><a class="image" href="http://en.wikipedia.org/wiki/Tiger"><img src="tiger.png" alt="Tiger"></a></span>}, para.sub_macros(para.buffer.join).gsub(/>\s+</, '><') end test 'a single-line footnote macro should be registered and rendered as a footnote' do para = block_from_string('Sentence text footnote:[An example footnote.].') assert_equal %(Sentence text <span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>.), para.sub_macros(para.buffer.join) assert_equal 1, para.document.references[:footnotes].size footnote = para.document.references[:footnotes].first assert_equal 1, footnote.index assert footnote.id.nil? assert_equal 'An example footnote.', footnote.text end test 'a multi-line footnote macro should be registered and rendered as a footnote' do para = block_from_string("Sentence text footnote:[An example footnote\nwith wrapped text.].") assert_equal %(Sentence text <span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>.), para.sub_macros(para.buffer.join) assert_equal 1, para.document.references[:footnotes].size footnote = para.document.references[:footnotes].first assert_equal 1, footnote.index assert footnote.id.nil? assert_equal "An example footnote\nwith wrapped text.", footnote.text end test 'a footnote macro can be directly adjacent to preceding word' do para = block_from_string('Sentence textfootnote:[An example footnote.].') assert_equal %(Sentence text<span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>.), para.sub_macros(para.buffer.join) end test 'a footnote macro may contain a macro' do para = block_from_string('Share your code. footnote:[http://github.com[GitHub]]') assert_equal %(Share your code. <span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>), para.sub_macros(para.buffer.join) assert_equal 1, para.document.references[:footnotes].size footnote1 = para.document.references[:footnotes][0] assert_equal '<a href="http://github.com">GitHub</a>', footnote1.text end test 'should increment index of subsequent footnote macros' do para = block_from_string("Sentence text footnote:[An example footnote.]. Sentence text footnote:[Another footnote.].") assert_equal %(Sentence text <span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>. Sentence text <span class="footnote">[<a id="_footnoteref_2" class="footnote" href="#_footnote_2" title="View footnote.">2</a>]</span>.), para.sub_macros(para.buffer.join) assert_equal 2, para.document.references[:footnotes].size footnote1 = para.document.references[:footnotes][0] assert_equal 1, footnote1.index assert footnote1.id.nil? assert_equal "An example footnote.", footnote1.text footnote2 = para.document.references[:footnotes][1] assert_equal 2, footnote2.index assert footnote2.id.nil? assert_equal "Another footnote.", footnote2.text end test 'a footnoteref macro with id and single-line text should be registered and rendered as a footnote' do para = block_from_string('Sentence text footnoteref:[ex1, An example footnote.].') assert_equal %(Sentence text <span class="footnote" id="_footnote_ex1">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>.), para.sub_macros(para.buffer.join) assert_equal 1, para.document.references[:footnotes].size footnote = para.document.references[:footnotes].first assert_equal 1, footnote.index assert_equal 'ex1', footnote.id assert_equal 'An example footnote.', footnote.text end test 'a footnoteref macro with id and multi-line text should be registered and rendered as a footnote' do para = block_from_string("Sentence text footnoteref:[ex1, An example footnote\nwith wrapped text.].") assert_equal %(Sentence text <span class="footnote" id="_footnote_ex1">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>.), para.sub_macros(para.buffer.join) assert_equal 1, para.document.references[:footnotes].size footnote = para.document.references[:footnotes].first assert_equal 1, footnote.index assert_equal 'ex1', footnote.id assert_equal "An example footnote\nwith wrapped text.", footnote.text end test 'a footnoteref macro with id should refer to footnoteref with same id' do para = block_from_string('Sentence text footnoteref:[ex1, An example footnote.]. Sentence text footnoteref:[ex1].') assert_equal %(Sentence text <span class="footnote" id="_footnote_ex1">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>. Sentence text <span class="footnoteref">[<a class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>.), para.sub_macros(para.buffer.join) assert_equal 1, para.document.references[:footnotes].size footnote = para.document.references[:footnotes].first assert_equal 1, footnote.index assert_equal 'ex1', footnote.id assert_equal 'An example footnote.', footnote.text end test 'a single-line index term macro with a primary term should be registered as an index reference' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macros = ['indexterm:[Tigers]', '(((Tigers)))'] macros.each do |macro| para = block_from_string("#{sentence}#{macro}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['Tigers'], para.document.references[:indexterms].first end end test 'a single-line index term macro with primary and secondary terms should be registered as an index reference' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macros = ['indexterm:[Big cats, Tigers]', '(((Big cats, Tigers)))'] macros.each do |macro| para = block_from_string("#{sentence}#{macro}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['Big cats', 'Tigers'], para.document.references[:indexterms].first end end test 'a single-line index term macro with primary, secondary and tertiary terms should be registered as an index reference' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macros = ['indexterm:[Big cats,Tigers , Panthera tigris]', '(((Big cats,Tigers , Panthera tigris)))'] macros.each do |macro| para = block_from_string("#{sentence}#{macro}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['Big cats', 'Tigers', 'Panthera tigris'], para.document.references[:indexterms].first end end test 'a multi-line index term macro should be compacted and registered as an index reference' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macros = ["indexterm:[Panthera\ntigris]", "(((Panthera\ntigris)))"] macros.each do |macro| para = block_from_string("#{sentence}#{macro}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['Panthera tigris'], para.document.references[:indexterms].first end end test 'normal substitutions are performed on an index term macro' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macros = ['indexterm:[*Tigers*]', '(((*Tigers*)))'] macros.each do |macro| para = block_from_string("#{sentence}#{macro}") output = para.apply_normal_subs(para.buffer) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['<strong>Tigers</strong>'], para.document.references[:indexterms].first end end test 'registers multiple index term macros' do sentence = "The tiger (Panthera tigris) is the largest cat species." macros = "(((Tigers)))\n(((Animals,Cats)))" para = block_from_string("#{sentence}\n#{macros}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output.rstrip assert_equal 2, para.document.references[:indexterms].size assert_equal ['Tigers'], para.document.references[:indexterms][0] assert_equal ['Animals', 'Cats'], para.document.references[:indexterms][1] end test 'an index term macro with round bracket syntax may contain round brackets in term' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macro = '(((Tiger (Panthera tigris))))' para = block_from_string("#{sentence}#{macro}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['Tiger (Panthera tigris)'], para.document.references[:indexterms].first end test 'an index term macro with square bracket syntax may contain square brackets in term' do sentence = "The tiger (Panthera tigris) is the largest cat species.\n" macro = 'indexterm:[Tiger [Panthera tigris\\]]' para = block_from_string("#{sentence}#{macro}") output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['Tiger [Panthera tigris]'], para.document.references[:indexterms].first end test 'a single-line index term 2 macro should be registered as an index reference and retain term inline' do sentence = 'The tiger (Panthera tigris) is the largest cat species.' macros = ['The indexterm2:[tiger] (Panthera tigris) is the largest cat species.', 'The ((tiger)) (Panthera tigris) is the largest cat species.'] macros.each do |macro| para = block_from_string(macro) output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['tiger'], para.document.references[:indexterms].first end end test 'a multi-line index term 2 macro should be compacted and registered as an index reference and retain term inline' do sentence = 'The panthera tigris is the largest cat species.' macros = ["The indexterm2:[ panthera\ntigris ] is the largest cat species.", "The (( panthera\ntigris )) is the largest cat species."] macros.each do |macro| para = block_from_string(macro) output = para.sub_macros(para.buffer.join) assert_equal sentence, output assert_equal 1, para.document.references[:indexterms].size assert_equal ['panthera tigris'], para.document.references[:indexterms].first end end test 'registers multiple index term 2 macros' do sentence = "The ((tiger)) (Panthera tigris) is the largest ((cat)) species." para = block_from_string(sentence) output = para.sub_macros(para.buffer.join) assert_equal 'The tiger (Panthera tigris) is the largest cat species.', output assert_equal 2, para.document.references[:indexterms].size assert_equal ['tiger'], para.document.references[:indexterms][0] assert_equal ['cat'], para.document.references[:indexterms][1] end test 'normal substitutions are performed on an index term 2 macro' do sentence = 'The ((*tiger*)) (Panthera tigris) is the largest cat species.' para = block_from_string sentence output = para.apply_normal_subs(para.buffer) assert_equal 'The <strong>tiger</strong> (Panthera tigris) is the largest cat species.', output assert_equal 1, para.document.references[:indexterms].size assert_equal ['<strong>tiger</strong>'], para.document.references[:indexterms].first end test 'index term 2 macro with round bracket syntex should not interfer with index term macro with round bracket syntax' do sentence = "The ((panthera tigris)) is the largest cat species.\n(((Big cats,Tigers)))" para = block_from_string sentence output = para.sub_macros(para.buffer.join) assert_equal "The panthera tigris is the largest cat species.\n", output terms = para.document.references[:indexterms] assert_equal 2, terms.size assert_equal ['Big cats', 'Tigers'], terms[0] assert_equal ['panthera tigris'], terms[1] end end context 'Passthroughs' do test 'collect inline triple plus passthroughs' do para = block_from_string('+++<code>inline code</code>+++') result = para.extract_passthroughs(para.buffer.join) assert_equal "\x0" + '0' + "\x0", result assert_equal 1, para.passthroughs.size assert_equal '<code>inline code</code>', para.passthroughs.first[:text] assert para.passthroughs.first[:subs].empty? end test 'collect multi-line inline triple plus passthroughs' do para = block_from_string("+++<code>inline\ncode</code>+++") result = para.extract_passthroughs(para.buffer.join) assert_equal "\x0" + '0' + "\x0", result assert_equal 1, para.passthroughs.size assert_equal "<code>inline\ncode</code>", para.passthroughs.first[:text] assert para.passthroughs.first[:subs].empty? end test 'collect inline double dollar passthroughs' do para = block_from_string('$$<code>{code}</code>$$') result = para.extract_passthroughs(para.buffer.join) assert_equal "\x0" + '0' + "\x0", result assert_equal 1, para.passthroughs.size assert_equal '<code>{code}</code>', para.passthroughs.first[:text] assert_equal [:specialcharacters], para.passthroughs.first[:subs] end test 'collect multi-line inline double dollar passthroughs' do para = block_from_string("$$<code>\n{code}\n</code>$$") result = para.extract_passthroughs(para.buffer.join) assert_equal "\x0" + '0' + "\x0", result assert_equal 1, para.passthroughs.size assert_equal "<code>\n{code}\n</code>", para.passthroughs.first[:text] assert_equal [:specialcharacters], para.passthroughs.first[:subs] end test 'collect passthroughs from inline pass macro' do para = block_from_string(%Q{pass:specialcharacters,quotes[<code>['code'\\]</code>]}) result = para.extract_passthroughs(para.buffer.join) assert_equal "\x0" + '0' + "\x0", result assert_equal 1, para.passthroughs.size assert_equal %q{<code>['code']</code>}, para.passthroughs.first[:text] assert_equal [:specialcharacters, :quotes], para.passthroughs.first[:subs] end test 'collect multi-line passthroughs from inline pass macro' do para = block_from_string(%Q{pass:specialcharacters,quotes[<code>['more\ncode'\\]</code>]}) result = para.extract_passthroughs(para.buffer.join) assert_equal "\x0" + '0' + "\x0", result assert_equal 1, para.passthroughs.size assert_equal %Q{<code>['more\ncode']</code>}, para.passthroughs.first[:text] assert_equal [:specialcharacters, :quotes], para.passthroughs.first[:subs] end # NOTE placeholder is surrounded by text to prevent reader from stripping trailing boundary char (unique to test scenario) test 'restore inline passthroughs without subs' do para = block_from_string("some \x0" + '0' + "\x0 to study") para.passthroughs << {:text => '<code>inline code</code>', :subs => []} result = para.restore_passthroughs(para.buffer.join) assert_equal "some <code>inline code</code> to study", result end # NOTE placeholder is surrounded by text to prevent reader from stripping trailing boundary char (unique to test scenario) # TODO add two entries to ensure index lookup is working correctly (0 indx could be ambiguous) test 'restore inline passthroughs with subs' do para = block_from_string("some \x0" + '0' + "\x0 to study") para.passthroughs << {:text => '<code>{code}</code>', :subs => [:specialcharacters]} result = para.restore_passthroughs(para.buffer.join) assert_equal 'some &lt;code&gt;{code}&lt;/code&gt; to study', result end end context 'Post replacements' do test 'line break inserted after line with line break character' do para = block_from_string("First line +\nSecond line") result = para.apply_subs(para.buffer, :post_replacements) assert_equal "First line<br>\n", result.first end test 'line break inserted after line wrap with hardbreaks enabled' do para = block_from_string("First line\nSecond line", :attributes => {'hardbreaks' => ''}) result = para.apply_subs(para.buffer, :post_replacements) assert_equal "First line<br>\n", result.first end test 'line break character stripped from end of line with hardbreaks enabled' do para = block_from_string("First line +\nSecond line", :attributes => {'hardbreaks' => ''}) result = para.apply_subs(para.buffer, :post_replacements) assert_equal "First line<br>\n", result.first end test 'line break not inserted for single line with hardbreaks enabled' do para = block_from_string("First line", :attributes => {'hardbreaks' => ''}) result = para.apply_subs(para.buffer, :post_replacements) assert_equal "First line", result.first end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/inline.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin<filename>src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/inline.rb module Asciidoctor # Public: Methods for managing inline elements in AsciiDoc block class Inline < AbstractNode # Public: Get the text of this inline element attr_reader :text # Public: Get the type (qualifier) of this inline element attr_reader :type # Public: Get/Set the target (e.g., uri) of this inline element attr_accessor :target def initialize(parent, context, text = nil, opts = {}) super(parent, context) @text = text #@id = opts[:id] if opts.has_key?(:id) #@type = opts[:type] if opts.has_key?(:type) #@target = opts[:target] if opts.has_key?(:target) @id = opts[:id] @type = opts[:type] @target = opts[:target] if opts.has_key?(:attributes) && (attributes = opts[:attributes]).is_a?(Hash) update_attributes(opts[:attributes]) unless attributes.empty? end end def render renderer.render("inline_#{@context}", self).chomp end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin<gh_stars>0 require 'rubygems' require 'strscan' $:.unshift(File.dirname(__FILE__)) #$:.unshift(File.join(File.dirname(__FILE__), '..', 'vendor')) # Public: Methods for parsing Asciidoc input files and rendering documents # using eRuby templates. # # Asciidoc documents comprise a header followed by zero or more sections. # Sections are composed of blocks of content. For example: # # Doc Title # ========= # # SECTION 1 # --------- # # This is a paragraph block in the first section. # # SECTION 2 # # This section has a paragraph block and an olist block. # # 1. Item 1 # 2. Item 2 # # Examples: # # Use built-in templates: # # lines = File.readlines("your_file.asc") # doc = Asciidoctor::Document.new(lines) # html = doc.render # File.open("your_file.html", "w+") do |file| # file.puts html # end # # Use custom (Tilt-supported) templates: # # lines = File.readlines("your_file.asc") # doc = Asciidoctor::Document.new(lines, :template_dir => 'templates') # html = doc.render # File.open("your_file.html", "w+") do |file| # file.puts html # end module Asciidoctor module SafeMode # A safe mode level that disables any of the security features enforced # by Asciidoctor (Ruby is still subject to its own restrictions). UNSAFE = 0; # A safe mode level that closely parallels safe mode in AsciiDoc. This value # prevents access to files which reside outside of the parent directory of # the source file and disables any macro other than the include::[] macro. SAFE = 1; # A safe mode level that disallows the document from setting attributes # that would affect the rendering of the document, in addition to all the # security features of SafeMode::SAFE. For instance, this level disallows # changing the backend or the source-highlighter using an attribute defined # in the source document. This is the most fundamental level of security # for server-side deployments (hence the name). SERVER = 10; # A safe mode level that disallows the document from attempting to read # files from the file system and including the contents of them into the # document, in additional to all the security features of SafeMode::SERVER. # For instance, this level disallows use of the include::[] macro and the # embedding of binary content (data uri), stylesheets and JavaScripts # referenced by the document.(Asciidoctor and trusted extensions may still # be allowed to embed trusted content into the document). # # Since Asciidoctor is aiming for wide adoption, this level is the default # and is recommended for server-side deployments. SECURE = 20; # A planned safe mode level that disallows the use of passthrough macros and # prevents the document from setting any known attributes, in addition to all # the security features of SafeMode::SECURE. # # Please note that this level is not currently implemented (and therefore not # enforced)! #PARANOID = 100; end # The default document type # Can influence markup generated by render templates DEFAULT_DOCTYPE = 'article' # The backend determines the format of the rendered output, default to html5 DEFAULT_BACKEND = 'html5' # Pointers to the preferred version for a given backend. BACKEND_ALIASES = { 'html' => 'html5', 'docbook' => 'docbook45' } # Default page widths for calculating absolute widths DEFAULT_PAGE_WIDTHS = { 'docbook' => 425 } # Default extensions for the respective base backends DEFAULT_EXTENSIONS = { 'html' => '.html', 'docbook' => '.xml', 'asciidoc' => '.ad', 'markdown' => '.md' } DELIMITED_BLOCKS = { '--' => :open, '----' => :listing, '....' => :literal, '====' => :example, '****' => :sidebar, '____' => :quote, '++++' => :pass, '|===' => :table, '!===' => :table, '////' => :comment, '```' => :fenced_code, '~~~' => :fenced_code } BREAK_LINES = { %q{'''} => :ruler, '<<<' => :page_break } LIST_CONTEXTS = [:ulist, :olist, :dlist, :colist] NESTABLE_LIST_CONTEXTS = [:ulist, :olist, :dlist] ORDERED_LIST_STYLES = [:arabic, :loweralpha, :lowerroman, :upperalpha, :upperroman] ORDERED_LIST_MARKER_PATTERNS = { :arabic => /\d+[.>]/, :loweralpha => /[a-z]\./, :upperalpha => /[A-Z]\./, :lowerroman => /[ivx]+\)/, :upperroman => /[IVX]+\)/ } LIST_CONTINUATION = '+' LINE_BREAK = ' +' # NOTE allows for empty space in line as it could be left by the template engine BLANK_LINES_PATTERN = /^\s*\n/ LINE_FEED_ENTITY = '&#10;' # or &#x0A; # The following pattern, which appears frequently, captures the contents between square brackets, # ignoring escaped closing brackets (closing brackets prefixed with a backslash '\' character) # # Pattern: # (?:\[((?:\\\]|[^\]])*?)\]) # Matches: # [enclosed text here] or [enclosed [text\] here] REGEXP = { # [[Foo]] :anchor => /^\[\[([^\[\]]+)\]\]$/, # Foowhatevs [[Bar]] :anchor_embedded => /^(.*?)\s*\[\[([^\[\]]+)\]\]$/, # [[ref]] (anywhere inline) :anchor_macro => /\\?\[\[([\w":].*?)\]\]/, # matches any block delimiter: # open, listing, example, literal, comment, quote, sidebar, passthrough, table # NOTE position the most common blocks towards the front of the pattern :any_blk => %r{^(?:--|(?:-|\.|=|\*|_|\+|/){4,}|[\|!]={3,}|(?:`|~){3,}.*)$}, # :foo: bar # :Author: Dan # :numbered!: :attr_entry => /^:(\w.*?):(?:[[:blank:]]+(.*))?$/, # {name?value} :attr_conditional => /^\s*\{([^\?]+)\?\s*([^\}]+)\s*\}/, # + Attribute values treat lines ending with ' +' as a continuation, # not a line-break as elsewhere in the document, where this is # a forced line break. This should be the same regexp as :line_break, # below, but it gets its own entry because readability ftw, even # though repeating regexps ftl. :attr_continue => /^[[:blank:]]*(.*)[[:blank:]]\+[[:blank:]]*$/, # :foo!: :attr_delete => /^:([^:]+)!:$/, # An attribute list above a block element # # Can be strictly positional: # [quote, <NAME>, Wealth of Nations] # Or can have name/value pairs # [NOTE, caption="Good to know"] # Can be defined by an attribute # [{lead}] :blk_attr_list => /^\[([\w\{].*)\]$/, # block attribute list or block id (bulk query) :attr_line => /^\[([\w\{].*|\[[^\[\]]+\])\]$/, # attribute reference # {foo} # {counter:pcount:1} :attr_ref => /(\\?)\{(\w+(?:[\-:]\w+)*)(\\?)\}/, # The author info line the appears immediately following the document title # <NAME> <<EMAIL>> :author_info => /^\s*(\w[\w\-'.]*)(?: +(\w[\w\-'.]*))?(?: +(\w[\w\-'.]*))?(?: +<([^>]+)>)?$/, # [[[Foo]]] (anywhere inline) :biblio_macro => /\\?\[\[\[([\w:][\w:.-]*?)\]\]\]/, # callout reference inside literal text # <1> # special characters will already be replaced, hence their use in the regex :callout_render => /\\?&lt;(\d+)&gt;/, # ...but not while scanning :callout_scan => /\\?<(\d+)>/, # <1> Foo :colist => /^<?(\d+)> (.*)/, # //// # comment block # //// :comment_blk => %r{^/{4,}$}, # // (and then whatever) :comment => %r{^//(?:[^/]|$)}, # one,two # one, two # one , two :csv_delimiter => /[[:space:]]*,[[:space:]]*/, # 29 :digits => /^\d+$/, # foo:: || foo::: || foo:::: || foo;; # Should be followed by a definition, on the same line... # foo:: That which precedes 'bar' (see also, <<bar>>) # ...or on a separate line # foo:: # That which precedes 'bar' (see also, <<bar>>) # The term may be an attribute reference # {term_foo}:: {def_foo} :dlist => /^\s*(.*?)(:{2,4}|;;)(?:[[:blank:]]+(.*))?$/, :dlist_siblings => { # (?:.*?[^:])? - a non-capturing group which grabs longest sequence of characters that doesn't end w/ colon '::' => /^\s*((?:.*[^:])?)(::)(?:[[:blank:]]+(.*))?$/, ':::' => /^\s*((?:.*[^:])?)(:::)(?:[[:blank:]]+(.*))?$/, '::::' => /^\s*((?:.*[^:])?)(::::)(?:[[:blank:]]+(.*))?$/, ';;' => /^\s*(.*)(;;)(?:[[:blank:]]+(.*))?$/ }, # ==== #:example => /^={4,}$/, # footnote:[text] # footnoteref:[id,text] # footnoteref:[id] :footnote_macro => /\\?(footnote|footnoteref):\[((?:\\\]|[^\]])*?)\]/m, # image::filename.png[Caption] :image_blk => /^image::(\S+?)\[(.*?)\]$/, # image:filename.png[Alt Text] :image_macro => /\\?image:([^\[]+)(?:\[([^\]]*)\])/, # indexterm:[Tigers,Big cats] # (((Tigers,Big cats))) :indexterm_macro => /\\?(?:indexterm:(?:\[((?:\\\]|[^\]])*?)\])|\(\(\((.*?)\)\)\)(?!\)))/m, # indexterm2:[Tigers] # ((Tigers)) :indexterm2_macro => /\\?(?:indexterm2:(?:\[((?:\\\]|[^\]])*?)\])|\(\((.*?)\)\)(?!\)))/m, # whitespace at the beginning of the line :leading_blanks => /^([[:blank:]]*)/, # + From the Asciidoc User Guide: "A plus character preceded by at # least one space character at the end of a non-blank line forces # a line break. It generates a line break (br) tag for HTML outputs. # # + (would not match because there's no space before +) # + (would match and capture '') # Foo + (would and capture 'Foo') :line_break => /^(.*)[[:blank:]]\+$/, # inline link and some inline link macro # FIXME revisit! :link_inline => %r{(^|link:|\s|>|&lt;|[\(\)\[\]])(\\?(?:https?|ftp)://[^\s\[<]*[^\s.\)\[<])(?:\[((?:\\\]|[^\]])*?)\])?}, # inline link macro # link:path[label] :link_macro => /\\?link:([^\s\[]+)(?:\[((?:\\\]|[^\]])*?)\])/, # ---- #:listing => /^\-{4,}$/, # .... #:literal => /^\.{4,}$/, # <TAB>Foo or one-or-more-spaces-or-tabs then whatever :lit_par => /^([[:blank:]]+.*)$/, # -- #:open_blk => /^\-\-$/, # . Foo (up to 5 consecutive dots) # 1. Foo (arabic, default) # a. Foo (loweralpha) # A. Foo (upperalpha) # i. Foo (lowerroman) # I. Foo (upperroman) :olist => /^\s*(\d+\.|[a-z]\.|[ivx]+\)|\.{1,5}) +(.*)$/i, # ''' (ruler) # <<< (pagebreak) :break_line => /^('|<){3,}$/, # ++++ #:pass => /^\+{4,}$/, # inline passthrough macros # +++text+++ # $$text$$ # pass:quotes[text] :pass_macro => /\\?(?:(\+{3}|\${2})(.*?)\1|pass:([a-z,]*)\[((?:\\\]|[^\]])*?)\])/m, # passthrough macro allowed in value of attribute assignment # pass:[text] :pass_macro_basic => /^pass:([a-z,]*)\[(.*)\]$/, # inline literal passthrough macro # `text` :pass_lit => /(^|[^`\w])(\\?`([^`\s]|[^`\s].*?\S)`)(?![`\w])/m, # placeholder for extracted passthrough text :pass_placeholder => /\x0(\d+)\x0/, # ____ #:quote => /^_{4,}$/, # The document revision info line the appears immediately following the # document title author info line, if present # v1.0, 2013-01-01: Ring in the new year release :revision_info => /^(?:\D*(.*?),)?(?:\s*(?!:)(.*?))(?:\s*(?!^):\s*(.*))?$/, # ''' #:ruler => /^'{3,}$/, # **** #:sidebar_blk => /^\*{4,}$/, # \' within a word :single_quote_esc => /(\w)\\'(\w)/, # an alternative if our backend generated single-quoted html/xml attributes #:single_quote_esc => /(\w|=)\\'(\w)/, # used for sanitizing attribute names :illegal_attr_name_chars => /[^\w\-]/, # |=== # |table # |=== #:table => /^\|={3,}$/, # !=== # !table # !=== #:table_nested => /^!={3,}$/, # 1*h,2*,^3e :table_colspec => /^(?:(\d+)\*)?([<^>](?:\.[<^>]?)?|(?:[<^>]?\.)?[<^>])?(\d+)?([a-z])?$/, # 2.3+<.>m # TODO might want to use step-wise scan rather than this mega-regexp :table_cellspec => { :start => /^[[:blank:]]*(?:(\d+(?:\.\d*)?|(?:\d*\.)?\d+)([*+]))?([<^>](?:\.[<^>]?)?|(?:[<^>]?\.)?[<^>])?([a-z])?\|/, :end => /[[:blank:]]+(?:(\d+(?:\.\d*)?|(?:\d*\.)?\d+)([*+]))?([<^>](?:\.[<^>]?)?|(?:[<^>]?\.)?[<^>])?([a-z])?$/ }, # .Foo but not . Foo or ..Foo :blk_title => /^\.([^\s.].*)$/, :dbl_quoted => /^("|)(.*)\1$/, :m_dbl_quoted => /^("|)(.*)\1$/m, # == Foo # ^ yields a level 2 title # # == Foo == # ^ also yields a level 2 title # # both equivalent to this two-line version: # Foo # ~~~ # # match[1] is the delimiter, whose length determines the level # match[2] is the title itself # match[3] is an inline anchor, which becomes the section id :section_title => /^(={1,5})\s+(\S.*?)(?:\s*\[\[([^\[]+)\]\])?(?:\s+\1)?$/, # does not begin with a dot and has at least one alphanumeric character :section_name => /^((?=.*\w+.*)[^.].*?)$/, # ====== || ------ || ~~~~~~ || ^^^^^^ || ++++++ :section_underline => /^([=\-~^\+])+$/, # * Foo (up to 5 consecutive asterisks) # - Foo :ulist => /^ \s* (- | \*{1,5}) \s+ (.*) $/x, # inline xref macro # <<id,reftext>> (special characters have already been escaped, hence the entity references) # xref:id[reftext] :xref_macro => /\\?(?:&lt;&lt;([\w":].*?)&gt;&gt;|xref:([\w":].*?)\[(.*?)\])/m, # ifdef::basebackend-html[] # ifndef::theme[] # ifeval::["{asciidoctor-version}" >= "0.1.0"] # ifdef::asciidoctor[Asciidoctor!] # endif::theme[] # endif::basebackend-html[] # endif::[] :ifdef_macro => /^[\\]?(ifdef|ifndef|ifeval|endif)::(\S*?(?:([,\+])\S+?)?)\[(.+)?\]$/, # "{asciidoctor-version}" >= "0.1.0" :eval_expr => /^(\S.*?)[[:blank:]]*(==|!=|<=|>=|<|>)[[:blank:]]*(\S.*)$/, # ...or if we want to be more strict up front about what's on each side #:eval_expr => /^(true|false|("|'|)\{\w+(?:\-\w+)*\}\2|("|')[^\3]*\3|\-?\d+(?:\.\d+)*)[[:blank:]]*(==|!=|<=|>=|<|>)[[:blank:]]*(true|false|("|'|)\{\w+(?:\-\w+)*\}\6|("|')[^\7]*\7|\-?\d+(?:\.\d+)*)$/, # include::chapter1.ad[] :include_macro => /^\\?include::([^\[]+)\[\]$/, # http://domain # https://domain # data:info :uri_sniff => /^[[:alpha:]][[:alnum:].+-]*:/i } ADMONITION_STYLES = ['NOTE', 'TIP', 'IMPORTANT', 'WARNING', 'CAUTION'] INTRINSICS = Hash.new{|h,k| STDERR.puts "Missing intrinsic: #{k.inspect}"; "{#{k}}"}.merge( { 'startsb' => '[', 'endsb' => ']', 'brvbar' => '|', 'caret' => '^', 'asterisk' => '*', 'tilde' => '~', 'plus' => '&#43;', 'apostrophe' => '\'', 'backslash' => '\\', 'backtick' => '`', 'empty' => '', 'sp' => ' ', 'space' => ' ', 'two-colons' => '::', 'two-semicolons' => ';;', 'nbsp' => '&#160;', 'deg' => '&#176;', 'zwsp' => '&#8203;', 'quot' => '&#34;', 'apos' => '&#39;', 'lsquo' => '&#8216;', 'rsquo' => '&#8217;', 'ldquo' => '&#8220;', 'rdquo' => '&#8221;', 'wj' => '&#8288;', 'amp' => '&', 'lt' => '<', 'gt' => '>' } ) SPECIAL_CHARS = { '<' => '&lt;', '>' => '&gt;', '&' => '&amp;' } SPECIAL_CHARS_PATTERN = /[#{SPECIAL_CHARS.keys.join}]/ # unconstrained quotes:: can appear anywhere # constrained quotes:: must be bordered by non-word characters # NOTE these substituions are processed in the order they appear here and # the order in which they are replaced is important QUOTE_SUBS = [ # **strong** [:strong, :unconstrained, /\\?(?:\[([^\]]+?)\])?\*\*(.+?)\*\*/m], # *strong* [:strong, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?\*(\S|\S.*?\S)\*(?=\W|$)/m], # ``double-quoted'' [:double, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?``(\S|\S.*?\S)''(?=\W|$)/m], # 'emphasis' [:emphasis, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?'(\S|\S.*?\S)'(?=\W|$)/m], # `single-quoted' [:single, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?`(\S|\S.*?\S)'(?=\W|$)/m], # ++monospaced++ [:monospaced, :unconstrained, /\\?(?:\[([^\]]+?)\])?\+\+(.+?)\+\+/m], # +monospaced+ [:monospaced, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?\+(\S|\S.*?\S)\+(?=\W|$)/m], # __emphasis__ [:emphasis, :unconstrained, /\\?(?:\[([^\]]+?)\])?\_\_(.+?)\_\_/m], # _emphasis_ [:emphasis, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?_(\S|\S.*?\S)_(?=\W|$)/m], # ##unquoted## [:none, :unconstrained, /\\?(?:\[([^\]]+?)\])?##(.+?)##/m], # #unquoted# [:none, :constrained, /(^|[^\w;:}])(?:\[([^\]]+?)\])?#(\S|\S.*?\S)#(?=\W|$)/m], # ^superscript^ [:superscript, :unconstrained, /\\?(?:\[([^\]]+?)\])?\^(.+?)\^/m], # ~subscript~ [:subscript, :unconstrained, /\\?(?:\[([^\]]+?)\])?\~(.+?)\~/m] ] # NOTE in Ruby 1.8.7, [^\\] does not match start of line, # so we need to match it explicitly # order is significant REPLACEMENTS = [ # (C) [/(^|[^\\])\(C\)/, '\1&#169;'], # (R) [/(^|[^\\])\(R\)/, '\1&#174;'], # (TM) [/(^|[^\\])\(TM\)/, '\1&#8482;'], # foo -- bar [/(^|\n| )--( |\n|$)/, '&#8201;&#8212;&#8201;'], # foo--bar [/(\w)--(?=\w)/, '\1&#8212;'], # ellipsis [/(^|[^\\])\.\.\./, '\1&#8230;'], # single quotes [/(\w)'(\w)/, '\1&#8217;\2'], # escaped single quotes [/(\w)\\'(\w)/, '\1\'\2'], # right arrow -> [/(^|[^\\])-&gt;/, '\1&#8594;'], # right double arrow => [/(^|[^\\])=&gt;/, '\1&#8658;'], # left arrow <- [/(^|[^\\])&lt;-/, '\1&#8592;'], # right left arrow <= [/(^|[^\\])&lt;=/, '\1&#8656;'], # and so on... # restore entities; TODO needs cleanup [/(^|[^\\])&amp;(#[a-z0-9]+;)/i, '\1&\2'] ] # Public: Parse the AsciiDoc source input into an Asciidoctor::Document # # Accepts input as an IO (or StringIO), String or String Array object. If the # input is a File, information about the file is stored in attributes on the # Document object. # # input - the AsciiDoc source as a IO, String or Array. # options - a Hash of options to control processing (default: {}) # see Asciidoctor::Document#initialize for details # block - a callback block for handling include::[] directives # # returns the Asciidoctor::Document def self.load(input, options = {}, &block) lines = nil if input.is_a?(File) options[:attributes] ||= {} attrs = options[:attributes] lines = input.readlines input_mtime = input.mtime input_path = File.expand_path(input.path) # hold off on setting infile and indir until we get a better sense of their purpose attrs['docfile'] = input_path attrs['docdir'] = File.dirname(input_path) attrs['docname'] = File.basename(input_path, File.extname(input_path)) attrs['docdate'] = input_mtime.strftime('%Y-%m-%d') attrs['doctime'] = input_mtime.strftime('%H:%M:%S %Z') attrs['docdatetime'] = [attrs['docdate'], attrs['doctime']] * ' ' elsif input.respond_to?(:readlines) input.rewind rescue nil lines = input.readlines elsif input.is_a?(String) lines = input.lines.entries elsif input.is_a?(Array) lines = input.dup else raise "Unsupported input type: #{input.class}" end Document.new(lines, options, &block) end # Public: Parse the contents of the AsciiDoc source file into an Asciidoctor::Document # # Accepts input as an IO, String or String Array object. If the # input is a File, information about the file is stored in # attributes on the Document. # # input - the String AsciiDoc source filename # options - a Hash of options to control processing (default: {}) # see Asciidoctor::Document#initialize for details # block - a callback block for handling include::[] directives # # returns the Asciidoctor::Document def self.load_file(filename, options = {}, &block) Asciidoctor.load(File.new(filename), options, &block) end # Public: Parse the AsciiDoc source input into an Asciidoctor::Document and render it # to the specified backend format # # Accepts input as an IO, String or String Array object. If the # input is a File, information about the file is stored in # attributes on the Document. # # If the :in_place option is true, and the input is a File, the output is # written to a file adjacent to the input file, having an extension that # corresponds to the backend format. Otherwise, if the :to_file option is # specified, the file is written to that file. If :to_file is not an absolute # path, it is resolved relative to :to_dir, if given, otherwise the # Document#base_dir. If the target directory does not exist, it will not be # created unless the :mkdirs option is set to true. If the file cannot be # written because the target directory does not exist, or because it falls # outside of the Document#base_dir in safe mode, an IOError is raised. # # If the output is going to be written to a file, the header and footer are # rendered unless specified otherwise (writing to a file implies creating a # standalone document). Otherwise, the header and footer are not rendered by # default and the rendered output is returned. # # input - the String AsciiDoc source filename # options - a Hash of options to control processing (default: {}) # see Asciidoctor::Document#initialize for details # block - a callback block for handling include::[] directives # # returns nothing if the rendered output String is written to a file, # otherwise the rendered output String is returned def self.render(input, options = {}, &block) in_place = options.delete(:in_place) || false to_file = options.delete(:to_file) to_dir = options.delete(:to_dir) mkdirs = options.delete(:mkdirs) || false write_in_place = in_place && input.is_a?(File) write_to_target = to_file || to_dir raise ArgumentError, ':in_place with input file must not accompany :to_dir or :to_file' if write_in_place && write_to_target if !options.has_key?(:header_footer) && (write_in_place || write_to_target) options[:header_footer] = true end doc = Asciidoctor.load(input, options, &block) if write_in_place to_file = File.join(File.dirname(input.path), "#{doc.attributes['docname']}#{doc.attributes['outfilesuffix']}") elsif write_to_target if to_dir to_dir = doc.normalize_asset_path(to_dir, 'to_dir', false) if to_file # normalize again, to_file could have dirty bits to_file = doc.normalize_asset_path(File.expand_path(to_file, to_dir), 'to_file', false) # reestablish to_dir as the final target directory (in the case to_file had directory segments) to_dir = File.dirname(to_file) else to_file = File.join(to_dir, "#{doc.attributes['docname']}#{doc.attributes['outfilesuffix']}") end elsif to_file to_file = doc.normalize_asset_path(to_file, 'to_file', false) to_dir = File.dirname(to_file) end if !File.directory? to_dir if mkdirs Helpers.require_library 'fileutils' FileUtils.mkdir_p to_dir else raise IOError, "target directory does not exist: #{to_dir}" end end end if to_file File.open(to_file, 'w') {|file| file.write doc.render } nil else doc.render end end # Public: Parse the contents of the AsciiDoc source file into an Asciidoctor::Document # and render it to the specified backend format # # input - the String AsciiDoc source filename # options - a Hash of options to control processing (default: {}) # see Asciidoctor::Document#initialize for details # block - a callback block for handling include::[] directives # # returns nothing if the rendered output String is written to a file, # otherwise the rendered output String is returned def self.render_file(filename, options = {}, &block) Asciidoctor.render(File.new(filename), options, &block) end # NOTE still contemplating this method #def self.parse_document_header(input, options = {}) # document = Document.new [], options # reader = Reader.new input, document, true # Lexer.parse_document_header reader, document # document #end # modules require 'asciidoctor/debug' require 'asciidoctor/substituters' require 'asciidoctor/helpers' # abstract classes require 'asciidoctor/abstract_node' require 'asciidoctor/abstract_block' # concrete classes require 'asciidoctor/attribute_list' require 'asciidoctor/backends/base_template' require 'asciidoctor/block' require 'asciidoctor/callouts' require 'asciidoctor/document' #require 'asciidoctor/errors' require 'asciidoctor/inline' require 'asciidoctor/lexer' require 'asciidoctor/list_item' require 'asciidoctor/reader' require 'asciidoctor/renderer' require 'asciidoctor/section' require 'asciidoctor/table' # info require 'asciidoctor/version' end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/attributes_test.rb
require 'test_helper' context 'Attributes' do context 'Assignment' do test 'creates an attribute' do doc = document_from_string(':frog: Tanglefoot') assert_equal 'Tanglefoot', doc.attributes['frog'] end test 'requires a space after colon following attribute name' do doc = document_from_string 'foo:bar' assert_equal nil, doc.attributes['foo'] end test 'creates an attribute by fusing a multi-line value' do str = <<-EOS :description: This is the first + Ruby implementation of + AsciiDoc. EOS doc = document_from_string(str) assert_equal 'This is the first Ruby implementation of AsciiDoc.', doc.attributes['description'] end test 'deletes an attribute' do doc = document_from_string(":frog: Tanglefoot\n:frog!:") assert_equal nil, doc.attributes['frog'] end test "doesn't choke when deleting a non-existing attribute" do doc = document_from_string(':frog!:') assert_equal nil, doc.attributes['frog'] end test "replaces special characters in attribute value" do doc = document_from_string(":xml-busters: <>&") assert_equal '&lt;&gt;&amp;', doc.attributes['xml-busters'] end test "performs attribute substitution on attribute value" do doc = document_from_string(":version: 1.0\n:release: Asciidoctor {version}") assert_equal 'Asciidoctor 1.0', doc.attributes['release'] end test "assigns attribute to empty string if substitution fails to resolve attribute" do doc = document_from_string(":release: Asciidoctor {version}") assert_equal '', doc.attributes['release'] end test "assigns multi-line attribute to empty string if substitution fails to resolve attribute" do doc = document_from_string(":release: Asciidoctor +\n {version}") assert_equal '', doc.attributes['release'] end test "apply custom substitutions to text in passthrough macro and assign to attribute" do doc = document_from_string(":xml-busters: pass:[<>&]") assert_equal '<>&', doc.attributes['xml-busters'] doc = document_from_string(":xml-busters: pass:none[<>&]") assert_equal '<>&', doc.attributes['xml-busters'] doc = document_from_string(":xml-busters: pass:specialcharacters[<>&]") assert_equal '&lt;&gt;&amp;', doc.attributes['xml-busters'] end test "attribute is treated as defined until it's not" do input = <<-EOS :holygrail: ifdef::holygrail[] The holy grail has been found! endif::holygrail[] :holygrail!: ifndef::holygrail[] Buggers! What happened to the grail? endif::holygrail[] EOS output = render_string input assert_xpath '//p', output, 2 assert_xpath '(//p)[1][text() = "The holy grail has been found!"]', output, 1 assert_xpath '(//p)[2][text() = "Buggers! What happened to the grail?"]', output, 1 end # Validates requirement: "Header attributes are overridden by command-line attributes." test 'attribute defined in document options overrides attribute in document' do doc = document_from_string(':cash: money', :attributes => {'cash' => 'heroes'}) assert_equal 'heroes', doc.attributes['cash'] end test 'attribute defined in document options cannot be unassigned in document' do doc = document_from_string(':cash!:', :attributes => {'cash' => 'heroes'}) assert_equal 'heroes', doc.attributes['cash'] end test 'attribute undefined in document options cannot be assigned in document' do doc = document_from_string(':cash: money', :attributes => {'cash!' => '' }) assert_equal nil, doc.attributes['cash'] doc = document_from_string(':cash: money', :attributes => {'cash' => nil }) assert_equal nil, doc.attributes['cash'] end test 'backend attributes are updated if backend attribute is defined in document and safe mode is less than SERVER' do doc = document_from_string(':backend: docbook45', :safe => Asciidoctor::SafeMode::SAFE) assert_equal 'docbook45', doc.attributes['backend'] assert doc.attributes.has_key? 'backend-docbook45' assert_equal 'docbook', doc.attributes['basebackend'] assert doc.attributes.has_key? 'basebackend-docbook' end test 'backend attributes defined in document options overrides backend attribute in document' do doc = document_from_string(':backend: docbook45', :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'backend' => 'html5'}) assert_equal 'html5', doc.attributes['backend'] assert doc.attributes.has_key? 'backend-html5' assert_equal 'html', doc.attributes['basebackend'] assert doc.attributes.has_key? 'basebackend-html' end end context 'Interpolation' do test "render properly with simple names" do html = render_string(":frog: Tanglefoot\n:my_super-hero: Spiderman\n\nYo, {frog}!\nBeat {my_super-hero}!") result = Nokogiri::HTML(html) assert_equal "Yo, Tanglefoot!\nBeat Spiderman!", result.css("p").first.content.strip end test 'attribute lookup is not case sensitive' do result = render_embedded_string(":He-Man: The most powerful man in the universe\n\n{He-Man}") assert_xpath '//p[text()="The most powerful man in the universe"]', result, 1 end test "render properly with single character name" do html = render_string(":r: Ruby\n\nR is for {r}!") result = Nokogiri::HTML(html) assert_equal 'R is for Ruby!', result.css("p").first.content.strip end test "convert multi-word names and render" do input = <<-EOS Main Header =========== :My frog: Tanglefoot Yo, {myfrog}! EOS output = render_string input assert_xpath '(//p)[1][text()="Yo, Tanglefoot!"]', output, 1 end test "ignores lines with bad attributes" do html = render_string("This is\nblah blah {foobarbaz}\nall there is.") result = Nokogiri::HTML(html) assert_no_match(/blah blah/m, result.css("p").first.content.strip) end test "attribute value gets interpretted when rendering" do doc = document_from_string(":google: http://google.com[Google]\n\n{google}") assert_equal 'http://google.com[Google]', doc.attributes['google'] output = doc.render assert_xpath '//a[@href="http://google.com"][text() = "Google"]', output, 1 end # See above - AsciiDoc says we're supposed to delete lines with bad # attribute refs in them. AsciiDoc is strange. # # test "Unknowns" do # html = render_string("Look, a {gobbledygook}") # result = Nokogiri::HTML(html) # assert_equal("Look, a {gobbledygook}", result.css("p").first.content.strip) # end test "substitutes inside unordered list items" do html = render_string(":foo: bar\n* snort at the {foo}\n* yawn") result = Nokogiri::HTML(html) assert_match(/snort at the bar/, result.css("li").first.content.strip) end test 'substitutes inside section title' do output = render_string(":prefix: Cool\n\n== {prefix} Title\n\ncontent") result = Nokogiri::HTML(output) assert_match(/Cool Title/, result.css('h2').first.content) assert_match(/_cool_title/, result.css('h2').first.attr('id')) end test 'substitutes inside block title' do input = <<-EOS :gem_name: asciidoctor .Require the +{gem_name}+ gem To use {gem_name}, the first thing to do is to import it in your Ruby source file. EOS output = render_embedded_string input assert_xpath '//*[@class="title"]/tt[text()="asciidoctor"]', output, 1 end test 'renders attribute until it is deleted' do input = <<-EOS :foo: bar Crossing the {foo}. :foo!: Belly up to the {foo}. EOS output = render_embedded_string input assert_xpath '//p[text()="Crossing the bar."]', output, 1 assert_xpath '//p[text()="Belly up to the bar."]', output, 0 end test 'does not disturb attribute-looking things escaped with backslash' do html = render_string(":foo: bar\nThis is a \\{foo} day.") result = Nokogiri::HTML(html) assert_equal 'This is a {foo} day.', result.css('p').first.content.strip end test 'does not disturb attribute-looking things escaped with literals' do html = render_string(":foo: bar\nThis is a +++{foo}+++ day.") result = Nokogiri::HTML(html) assert_equal 'This is a {foo} day.', result.css('p').first.content.strip end test 'does not substitute attributes inside listing blocks' do input = <<-EOS :forecast: snow ---- puts 'The forecast for today is {forecast}' ---- EOS output = render_string(input) assert_match(/\{forecast\}/, output) end test 'does not substitute attributes inside literal blocks' do input = <<-EOS :foo: bar .... You insert the text {foo} to expand the value of the attribute named foo in your document. .... EOS output = render_string(input) assert_match(/\{foo\}/, output) end test 'does not show docdir and shows relative docfile if safe mode is SERVER or greater' do input = <<-EOS * docdir: {docdir} * docfile: {docfile} EOS docdir = Dir.pwd docfile = File.join(docdir, 'sample.asciidoc') output = render_embedded_string input, :safe => Asciidoctor::SafeMode::SERVER, :attributes => {'docdir' => docdir, 'docfile' => docfile} assert_xpath '//li[1]/p[text()="docdir: "]', output, 1 assert_xpath '//li[2]/p[text()="docfile: sample.asciidoc"]', output, 1 end test 'shows absolute docdir and docfile paths if safe mode is less than SERVER' do input = <<-EOS * docdir: {docdir} * docfile: {docfile} EOS docdir = Dir.pwd docfile = File.join(docdir, 'sample.asciidoc') output = render_embedded_string input, :safe => Asciidoctor::SafeMode::SAFE, :attributes => {'docdir' => docdir, 'docfile' => docfile} assert_xpath %(//li[1]/p[text()="docdir: #{docdir}"]), output, 1 assert_xpath %(//li[2]/p[text()="docfile: #{docfile}"]), output, 1 end end context "Intrinsic attributes" do test "substitute intrinsics" do Asciidoctor::INTRINSICS.each_pair do |key, value| html = render_string("Look, a {#{key}} is here") # can't use Nokogiri because it interprets the HTML entities and we can't match them assert_match(/Look, a #{Regexp.escape(value)} is here/, html) end end test "don't escape intrinsic substitutions" do html = render_string('happy{nbsp}together') assert_match(/happy&#160;together/, html) end test "escape special characters" do html = render_string('<node>&</node>') assert_match(/&lt;node&gt;&amp;&lt;\/node&gt;/, html) end test 'creates counter' do input = <<-EOS {counter:mycounter} EOS doc = document_from_string input output = doc.render assert_equal 1, doc.attributes['mycounter'] assert_xpath '//p[text()="1"]', output, 1 end test 'creates counter silently' do input = <<-EOS {counter2:mycounter} EOS doc = document_from_string input output = doc.render assert_equal 1, doc.attributes['mycounter'] assert_xpath '//p[text()="1"]', output, 0 end test 'creates counter with numeric seed value' do input = <<-EOS {counter2:mycounter:10} EOS doc = document_from_string input doc.render assert_equal 10, doc.attributes['mycounter'] end test 'creates counter with character seed value' do input = <<-EOS {counter2:mycounter:A} EOS doc = document_from_string input doc.render assert_equal 'A', doc.attributes['mycounter'] end test 'increments counter with numeric value' do input = <<-EOS :mycounter: 1 {counter:mycounter} {mycounter} EOS doc = document_from_string input output = doc.render assert_equal 2, doc.attributes['mycounter'] assert_xpath '//p[text()="2"]', output, 2 end test 'increments counter with character value' do input = <<-EOS :mycounter: @ {counter:mycounter} {mycounter} EOS doc = document_from_string input output = doc.render assert_equal 'A', doc.attributes['mycounter'] assert_xpath '//p[text()="A"]', output, 2 end end context "Block attributes" do test "Position attributes assigned to block" do input = <<-EOS [quote, Name, Source] ____ A famous quote. ____ EOS doc = document_from_string(input) qb = doc.blocks.first assert_equal 'quote', qb.attributes['style'] assert_equal 'quote', qb.attr(:style) assert_equal 'Name', qb.attributes['attribution'] assert_equal 'Source', qb.attributes['citetitle'] end test "Normal substitutions are performed on single-quoted attributes" do input = <<-EOS [quote, Name, 'http://wikipedia.org[Source]'] ____ A famous quote. ____ EOS doc = document_from_string(input) qb = doc.blocks.first assert_equal 'quote', qb.attributes['style'] assert_equal 'quote', qb.attr(:style) assert_equal 'Name', qb.attributes['attribution'] assert_equal '<a href="http://wikipedia.org">Source</a>', qb.attributes['citetitle'] end test "Attribute substitutions are performed on attribute list before parsing attributes" do input = <<-EOS :lead: role="lead" [{lead}] A paragraph EOS doc = document_from_string(input) para = doc.blocks.first assert_equal 'lead', para.attributes['role'] end test "Block attributes are additive" do input = <<-EOS [id='foo'] [role='lead'] A paragraph. EOS doc = document_from_string(input) para = doc.blocks.first assert_equal 'foo', para.id assert_equal 'lead', para.attributes['role'] end test "Last wins for id attribute" do input = <<-EOS [[bar]] [[foo]] == Section paragraph [[baz]] [id='coolio'] === Section EOS doc = document_from_string(input) sec = doc.first_section assert_equal 'foo', sec.id subsec = sec.blocks.last assert_equal 'coolio', subsec.id end test 'block id above document title sets id on document' do input = <<-EOS [[reference]] Reference Manual ================ :css-signature: refguide preamble EOS doc = document_from_string input assert_equal 'reference', doc.id assert_equal 'refguide', doc.attr('css-signature') output = doc.render assert_xpath '//body[@id="reference"]', output, 1 end test "trailing block attributes tranfer to the following section" do input = <<-EOS [[one]] == Section One paragraph [[sub]] // try to mess this up! === Sub-section paragraph [role='classy'] //// block comment //// == Section Two content EOS doc = document_from_string(input) section_one = doc.blocks.first assert_equal 'one', section_one.id subsection = section_one.blocks.last assert_equal 'sub', subsection.id section_two = doc.blocks.last assert_equal 'classy', section_two.attr(:role) end end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/test/preamble_test.rb
require 'test_helper' context 'Preamble' do test 'title and single paragraph preamble before section' do input = <<-EOS Title ===== Preamble paragraph 1. == First Section Section paragraph 1. EOS result = render_string(input) assert_xpath '//p', result, 2 assert_xpath '//*[@id="preamble"]', result, 1 assert_xpath '//*[@id="preamble"]//p', result, 1 assert_xpath '//*[@id="preamble"]/following-sibling::*//h2[@id="_first_section"]', result, 1 assert_xpath '//*[@id="preamble"]/following-sibling::*//p', result, 1 end test 'title and multi-paragraph preamble before section' do input = <<-EOS Title ===== Preamble paragraph 1. Preamble paragraph 2. == First Section Section paragraph 1. EOS result = render_string(input) assert_xpath '//p', result, 3 assert_xpath '//*[@id="preamble"]', result, 1 assert_xpath '//*[@id="preamble"]//p', result, 2 assert_xpath '//*[@id="preamble"]/following-sibling::*//h2[@id="_first_section"]', result, 1 assert_xpath '//*[@id="preamble"]/following-sibling::*//p', result, 1 end test 'title and preamble only' do input = <<-EOS Title ===== Preamble paragraph 1. EOS result = render_string(input) assert_xpath '//p', result, 1 assert_xpath '//*[@id="preamble"]', result, 1 assert_xpath '//*[@id="preamble"]//p', result, 1 assert_xpath '//*[@id="preamble"]/following-sibling::*', result, 0 end test 'title and section without preamble' do input = <<-EOS Title ===== == First Section Section paragraph 1. EOS result = render_string(input) assert_xpath '//p', result, 1 assert_xpath '//*[@id="preamble"]', result, 0 assert_xpath '//h2[@id="_first_section"]', result, 1 end test 'no title with preamble and section' do input = <<-EOS Preamble paragraph 1. == First Section Section paragraph 1. EOS result = render_string(input) assert_xpath '//p', result, 2 assert_xpath '//*[@id="preamble"]', result, 0 assert_xpath '//h2[@id="_first_section"]/preceding::p', result, 1 end test 'preamble in book doctype' do input = <<-EOS Book ==== :doctype: book Back then... = Chapter One It was a dark and stormy night... = Chapter Two They couldn't believe their eyes when... EOS d = document_from_string(input) assert_equal 'book', d.doctype output = d.render assert_xpath '//h1', output, 3 assert_xpath %{//*[@id="preamble"]//p[text() = "Back then#{[8230].pack('U*')}"]}, output, 1 end end
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/bundler/setup.rb
<reponame>wilkinsona/asciidoctor-gradle-plugin path = File.expand_path('..', __FILE__) $:.unshift File.expand_path("#{path}/../ruby/1.9.1/gems/asciidoctor-0.1.1/lib") $:.unshift File.expand_path("#{path}/../ruby/1.9.1/gems/coderay-1.0.8/lib") $:.unshift File.expand_path("#{path}/../ruby/1.9.1/bundler/gems/tilt-be4017422c98/lib")
wilkinsona/asciidoctor-gradle-plugin
src/main/resources/ruby/1.9.1/gems/asciidoctor-0.1.1/lib/asciidoctor/abstract_block.rb
module Asciidoctor class AbstractBlock < AbstractNode # Public: Get the Array of Asciidoctor::AbstractBlock sub-blocks for this block attr_reader :blocks # Public: Set the Integer level of this Section or the Section level in which this Block resides attr_accessor :level # Public: Set the String block title. attr_writer :title def initialize(parent, context) super(parent, context) @blocks = [] @id = nil @title = nil if context == :document @level = 0 elsif !parent.nil? && !self.is_a?(Section) @level = parent.level else @level = nil end @next_section_index = 0 end # Public: A convenience method that indicates whether the title instance # variable is blank (nil or empty) def title? !@title.to_s.empty? end # Public: Get the String title of this Block with title substitions applied # # The following substitutions are applied to block and section titles: # # :specialcharacters, :quotes, :replacements, :macros, :attributes and :post_replacements # # Examples # # block.title = "Foo 3^ # {two-colons} Bar(1)" # block.title # => "Foo 3^ # :: Bar(1)" # # Returns the String title of this Block def title # prevent substitutions from being applied multiple times if defined?(@subbed_title) @subbed_title elsif @title @subbed_title = apply_title_subs(@title) else @title end end # Public: Determine whether this Block contains block content # # returns Whether this Block has block content # #-- # TODO we still need another method that answers # whether this Block *can* have block content # that should be the option 'sectionbody' def blocks? !blocks.empty? end # Public: Get the element at i in the array of blocks. # # i - The Integer array index number. # # section = Section.new # # section << 'foo' # section << 'bar' # section[1] # => "bar" def [](i) @blocks[i] end # Public: Append a content block to this block's list of blocks. # # block - The new child block. # # Examples # # block = Block.new(parent, :preamble) # # block << Block.new(block, :paragraph, 'p1') # block << Block.new(block, :paragraph, 'p2') # block.blocks # # => ["p1", "p2"] # # Returns nothing. def <<(block) if block.is_a?(Section) assign_index(block) end @blocks << block end # Public: Insert a content block at the specified index in this block's # list of blocks. # # i - The Integer array index number. # val = The content block to insert. # # section = Section.new # # section << 'foo' # section << 'baz' # section.insert(1, 'bar') # section.blocks # ["foo", "bar", "baz"] def insert(i, block) @blocks.insert(i, block) end # Public: Delete the element at i in the array of section blocks, # returning that element or nil if i is out of range. # # i - The Integer array index number. # # section = Section.new # # section << 'foo' # section << 'bar' # section.delete_at(1) # => "bar" # # section.blocks # => ["foo"] def delete_at(i) @blocks.delete_at(i) end # Public: Clear this Block's list of blocks. # # section = Section.new # # section << 'foo' # section << 'bar' # section.blocks # => ["foo", "bar"] # section.clear_blocks # section.blocks # => [] def clear_blocks @blocks = [] end # Public: Get the Integer number of blocks in this block # # Examples # # section = Section.new # # section.size # => 0 # # section << 'foo' # section << 'bar' # section.size # => 2 def size @blocks.size end # Public: Get the Array of child Section objects # # Only applies to Document and Section instances # # Examples # # section = Section.new(parent) # section << Block.new(section, :paragraph, 'paragraph 1') # section << Section.new(parent) # section << Block.new(section, :paragraph, 'paragraph 2') # section.sections.size # # => 1 # # returns an Array of Section objects def sections @blocks.inject([]) {|collector, block| collector << block if block.is_a?(Section) collector } end # Internal: Assign the next index (0-based) to this section # # Assign the next index of this section within the parent # Block (in document order) # # returns nothing def assign_index(section) section.index = @next_section_index @next_section_index += 1 end # Internal: Reassign the section indexes # # Walk the descendents of the current Document or Section # and reassign the section 0-based index value to each Section # as it appears in document order. # # returns nothing def reindex_sections @next_section_index = 0 @blocks.each {|block| if block.is_a?(Section) assign_index(block) block.reindex_sections end } end end end
gleuch/display-mode
app.rb
require "rubygems" require "bundler" Bundler.setup require "sinatra" require "instagram" require "json" configure do APP_ENV = Sinatra::Application.environment.to_s APP_ROOT = File.expand_path(File.dirname(__FILE__)) end use Rack::Session::Cookie Instagram.configure do |config| oauth = YAML::load(File.open("#{APP_ROOT}/oauth.yml"))[APP_ENV] config.client_id = oauth['instagram']['key'] config.client_secret = oauth['instagram']['secret'] CALLBACK_URL = oauth['instagram']['callback'] end def has_access_token; !session[:access_token].nil? && session[:access_token] != ''; end def get_or_post(path, opts={}, &block) get(path, opts, &block) post(path, opts, &block) end def fetch_photos_for_tag(tag) client = Instagram.client(:access_token => session[:access_token]) user = client.user photos = {} list_photos = Instagram.tag_recent_media(tag) unless list_photos.empty? || list_photos['data'].empty? list_photos['data'].each do |v| photos[v.id] = {:image => v.images.standard_resolution.url, :user => v.user, :caption => (v.caption.nil? || v.caption.text.nil? ? nil : v.caption.text)} end else photos end photos end # INDEX PAGE get '/' do if has_access_token redirect '/tag' else erb :index end end get_or_post '/auth/instagram' do redirect Instagram.authorize_url(:redirect_uri => CALLBACK_URL) end # DO OAUTH get_or_post '/auth/:name/callback' do response = Instagram.get_access_token(params[:code], :redirect_uri => CALLBACK_URL) session[:access_token] = response.access_token redirect '/tag' end # FETCH TAG html_show_tags = lambda { # IF ACCESS if has_access_token # IF TAGNAME unless params.nil? || params[:tag].nil? || params[:tag] == '' begin @photos = fetch_photos_for_tag(params[:tag]) erb :view_tag rescue => err session[:access_token] = nil erb :error_tag end # PROMPT TO INPUT TAG else erb :choose_tag end # REQUIRE LOGIN else redirect '/' end } get_or_post '/tag/:tag', &html_show_tags get_or_post '/tag', &html_show_tags json_show_tags = lambda { # IF ACCESS if has_access_token # IF TAGNAME unless params.nil? || params[:tag].nil? || params[:tag] == '' begin @photos = fetch_photos_for_tag(params[:tag]) {:success => true, :photos => @photos}.to_json rescue session[:access_token] = nil {:error => true, :message => 'Server error.'}.to_json end # PROMPT TO INPUT TAG else {:error => true, :select_tag => true, :message => 'No tag specified.'}.to_json end # REQUIRE LOGIN else {:error => true, :logout => true, :message => 'Login required'}.to_json end } get_or_post '/tag/:tag.json', &json_show_tags get_or_post '/tag.json', &json_show_tags
alexekim/mendel_inheritance
app.rb
<gh_stars>0 require 'bundler' #using ruby to require a gem Bundler.require # load all the gems in the gemfile class Peaplant #when def initialize(flower_color, *meta) # *meta is a splat @flower_color = flower_color @@seeds = true #all pea plants will have this @meta = meta end def to_s "A simple pea plant with #{@flower_color} flowers." end end white_flower_pea_plant = Peaplant.new('white') p white_flower_pea_plant p white_flower_pea_plant.to_s magenta_flower_pea_plant = Peaplant.new('magenta') p magenta_flower_pea_plant p magenta_flower_pea_plant.to_s purple_flower_pea_plant = Peaplant.new('Purple') p purple_flower_pea_plant p purple_flower_pea_plant.to_s
HalcyonLA/HalcyonInnovationKit
HalcyonInnovationKit.podspec
Pod::Spec.new do |s| s.platform = :ios s.ios.deployment_target = '8.0' s.name = "HalcyonInnovationKit" s.module_name = "HalcyonInnovationKit" s.summary = "Halcyon Innovation development kit." s.requires_arc = true s.version = "1.3.35" s.author = { "<NAME>" => "<EMAIL>" } s.license = { :type => "MIT", :file => "LICENSE" } s.homepage = "https://github.com/HalcyonLA/HalcyonInnovationKit" s.source = { :git => "https://github.com/HalcyonLA/HalcyonInnovationKit.git", :tag => "#{s.version}"} s.framework = "UIKit" s.default_subspec = 'Core' s.subspec 'Core' do |cs| cs.dependency 'HalcyonInnovationKit/UI' cs.dependency 'HalcyonInnovationKit/Network' cs.dependency 'HalcyonInnovationKit/Database' end s.subspec 'UI' do |ui| ui.framework = 'MapKit' ui.framework = "Accelerate" ui.framework = "QuartzCore" ui.source_files = "Source/{UI,Extensions}/*.{swift}" ui.dependency 'SDWebImage', '~> 5.0.0' ui.dependency 'MBProgressHUD', '~> 1.1.0' end s.subspec 'Network' do |network| network.source_files = "Source/Network/*.{swift}" network.dependency 'AFNetworking', '~> 4.0.0' network.dependency 'AFNetworking+RetryPolicy', '~> 1.0.4' network.dependency 'XCGLogger', '~> 7.0.0' network.dependency 'MBProgressHUD', '~> 1.1.0' network.dependency 'HalcyonInnovationKit/UI' end s.subspec 'Database' do |database| database.framework = "CoreData" database.source_files = "Source/Database/*.{swift}" database.dependency 'FastEasyMapping', '~> 1.2.2' database.dependency 'XCGLogger', '~> 7.0.0' database.dependency 'HalcyonInnovationKit/UI' end s.subspec 'Crypto' do |crypto| crypto.source_files = "Source/Crypto/*.{swift}" crypto.dependency 'HalcyonInnovationKit/Network' crypto.dependency 'CryptoSwift', '~> 1.0.0' end end
pkucherenk0/peatio
spec/api/v2/admin/engines_spec.rb
# frozen_string_literal: true describe API::V2::Admin::Engines, type: :request do let(:admin) { create(:member, :admin, :level_3, email: '<EMAIL>', uid: 'ID73BF61C8H0') } let(:token) { jwt_for(admin) } let(:level_3_member) { create(:member, :level_3) } let(:level_3_member_token) { jwt_for(level_3_member) } describe 'GET /api/v2/admin/engines/:id' do let(:engine) { Engine.first } it 'returns information about specified engine' do api_get "/api/v2/admin/engines/#{engine.id}", token: token expect(response).to be_successful result = JSON.parse(response.body) expect(result.fetch('id')).to eq engine.id expect(result.fetch('name')).to eq engine.name expect(result.fetch('driver')).to eq engine.driver expect(result.fetch('state')).to eq engine.state end it 'returns error in case of invalid id' do api_get '/api/v2/admin/engines/120', token: token expect(response.code).to eq '404' expect(response).to include_api_error('record.not_found') end it 'return error in case of not permitted ability' do api_get "/api/v2/admin/engines/#{engine.id}", token: level_3_member_token expect(response.code).to eq '403' expect(response).to include_api_error('admin.ability.not_permitted') end end describe 'GET /api/v2/admin/engines' do it 'lists of engines' do api_get '/api/v2/admin/engines', token: token expect(response).to be_successful result = JSON.parse(response.body) expect(result.size).to eq 2 end it 'returns engines by ascending order' do api_get '/api/v2/admin/engines', params: { ordering: 'asc' }, token: token result = JSON.parse(response.body) expect(response).to be_successful expect(result.first['id']).to eq Engine.first.id end it 'returns paginated engines' do api_get '/api/v2/admin/engines', params: { limit: 1, page: 1 }, token: token result = JSON.parse(response.body) expect(response).to be_successful expect(response.headers.fetch('Total')).to eq '2' expect(result.size).to eq 1 api_get '/api/v2/admin/engines', params: { limit: 1, page: 2 }, token: token result = JSON.parse(response.body) expect(response).to be_successful expect(response.headers.fetch('Total')).to eq '2' expect(result.size).to eq 1 end it 'return error in case of not permitted ability' do api_get '/api/v2/admin/engines', token: level_3_member_token expect(response.code).to eq '403' expect(response).to include_api_error('admin.ability.not_permitted') end end describe 'POST /api/v2/admin/engines/new' do let(:engine) { create(:engine) } let(:valid_params) do { name: 'new-engine', driver: 'new_driver', uid: 'UID123456', key: 'your_key', secret: 'your_secret', data: { some_data: 'some data' } } end it 'creates new engine' do api_post '/api/v2/admin/engines/new', token: token, params: valid_params result = JSON.parse(response.body) expect(response).to be_successful expect(result['name']).to eq 'new-engine' expect(result['data'].blank?).to eq true api_post '/api/v2/admin/engines/new', token: token, params: valid_params expect(response).to have_http_status 422 expect(response).to include_api_error('admin.engine.duplicate_name') end it 'checked required params' do api_post '/api/v2/admin/engines/new', params: {}, token: token expect(response).to have_http_status 422 expect(response).to include_api_error('admin.engine.missing_name') expect(response).to include_api_error('admin.engine.missing_driver') end it 'return error in case of not permitted ability' do api_post '/api/v2/admin/engines/new', params: valid_params, token: level_3_member_token expect(response.code).to eq '403' expect(response).to include_api_error('admin.ability.not_permitted') end end describe 'POST /api/v2/admin/engines/update' do it 'updates attributes' do api_post '/api/v2/admin/engines/update', params: { id: Engine.first.id, name: 'Second Engine', driver: 'second_driver' }, token: token result = JSON.parse(response.body) expect(response).to be_successful expect(result['name']).to eq 'Second Engine' expect(result['driver']).to eq 'second_driver' end it 'updates secret' do api_post '/api/v2/admin/engines/update', params: { id: Engine.first.id, secret: 'my_secret' }, token: token expect(response).to be_successful expect(Engine.first.secret).to eq('my_secret') end it 'checkes required params' do api_post '/api/v2/admin/engines/update', params: {}, token: token expect(response).to have_http_status 422 expect(response).to include_api_error('admin.engine.missing_id') end it 'return error in case of not permitted ability' do api_post '/api/v2/admin/engines/update', params: { id: Engine.first.id, name: :new }, token: level_3_member_token expect(response.code).to eq '403' expect(response).to include_api_error('admin.ability.not_permitted') end end end
pkucherenk0/peatio
spec/api/v2/account/transactions_spec.rb
<reponame>pkucherenk0/peatio # encoding: UTF-8 # frozen_string_literal: true describe API::V2::Account::Transactions, type: :request do describe 'GET /api/v2/account/transactions' do let(:member) { create(:member, :level_3) } let(:token) { jwt_for(member) } let(:btc_account) { member.get_account('btc') } let(:usd_account) { member.get_account('usd') } let(:balance) { 100000 } context 'successful' do before do btc_account.plus_funds(balance) usd_account.plus_funds(balance) create_list(:deposit_usd, 4, member: member, updated_at: 5.hour.ago) create_list(:usd_withdraw, 4, member: member, updated_at: 5.hour.ago) create_list(:deposit_btc, 3, member: member, updated_at: 10.hour.ago) create_list(:btc_withdraw, 3, member: member, updated_at: 10.hour.ago) create_list(:deposit_usd, 5, member: member, updated_at: 5.days.ago) create_list(:usd_withdraw, 5, member: member, updated_at: 5.days.ago) end it 'returns all deposits and withdraws num' do api_get '/api/v2/account/transactions', token: token result = JSON.parse(response.body) expect(result.size).to eq 24 expect(response.headers.fetch('Total')).to eq '24' end it 'returns limited deposits and withdraws' do api_get '/api/v2/account/transactions', params: { limit: 2, page: 1 }, token: token result = JSON.parse(response.body) expect(result.size).to eq 2 expect(response.headers.fetch('Total')).to eq '24' api_get '/api/v2/account/transactions', params: { limit: 1, page: 2 }, token: token result = JSON.parse(response.body) expect(result.size).to eq 1 expect(response.headers.fetch('Total')).to eq '24' end it 'returns deposits and withdraws for the last two days' do api_get '/api/v2/account/transactions', params: { time_from: 2.days.ago.to_i }, token: token result = JSON.parse(response.body) expect(result.size).to eq 14 expect(response.headers.fetch('Total')).to eq '14' end it 'returns deposits and withdraws before 2 days ago' do api_get '/api/v2/account/transactions', params: { time_to: 2.days.ago.to_i }, token: token result = JSON.parse(response.body) expect(result.size).to eq 10 expect(response.headers.fetch('Total')).to eq '10' end it 'returns newest mixed up withdraws and deposits depending on updated_at' do api_get '/api/v2/account/transactions', params: { limit: 8, page: 1 }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Withdraw' }.count).to eq 4 expect(result.select { |t| t['type'] == 'Deposit' }.count).to eq 4 end it 'returns the oldest mixed up withdraws and deposits depending on updated_at' do api_get '/api/v2/account/transactions', params: { limit: 8, page: 2, time_from: 2.days.ago.to_i }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Withdraw' }.count).to eq 3 expect(result.select { |t| t['type'] == 'Deposit' }.count).to eq 3 end it 'returns sorted transactions in descending order' do api_get '/api/v2/account/transactions', token: token result = JSON.parse(response.body) update_time = result.pluck('updated_at') expect(update_time).to eq(update_time.sort { |a, b| b <=> a }) end it 'returns sorted transactions in ascending order' do api_get '/api/v2/account/transactions', params: { order_by: 'asc' }, token: token result = JSON.parse(response.body) update_time = result.pluck('updated_at') expect(update_time).to eq(update_time.sort) end it 'returns only transactions with BTC currency' do api_get '/api/v2/account/transactions', params: { currency: 'btc' }, token: token result = JSON.parse(response.body) expect(result.count).to eq 6 end it 'returns only transactions with USD currency' do api_get '/api/v2/account/transactions', params: { currency: 'USD' }, token: token result = JSON.parse(response.body) expect(result.count).to eq 18 end it 'returns nil in confirmations field for fiat' do api_get '/api/v2/account/transactions', params: { currency: 'USD' }, token: token result = JSON.parse(response.body) expect(result.pluck('confimations').none?).to be_truthy end it 'returns valid number in confirmations field for coin' do api_get '/api/v2/account/transactions', params: { currency: 'btc' }, token: token result = JSON.parse(response.body) expect(result.pluck('confimations').any? { |c| c.nil? ? true : c > 1 }).to be_truthy end it 'returns transaction with txid filter' do api_get '/api/v2/account/transactions', params: { txid: Deposits::Coin.first.txid }, token: token result = JSON.parse(response.body) expect(result.size).to eq 1 expect(result.all? { |d| d['txid'] == Deposits::Coin.first.txid }).to be_truthy end context 'state filters' do before do create_list(:deposit_usd, 4, member: member, updated_at: 5.hour.ago, aasm_state: 'accepted') create_list(:deposit_usd, 4, member: member, updated_at: 5.hour.ago, aasm_state: 'rejected') create_list(:usd_withdraw, 4, member: member, updated_at: 5.days.ago, aasm_state: 'accepted') create_list(:usd_withdraw, 4, member: member, updated_at: 5.days.ago, aasm_state: 'rejected') end it 'returns transactions with more than one deposit state' do expect(Deposit.count).to eq 20 api_get '/api/v2/account/transactions', params: { deposit_state: ['accepted', 'submitted'] }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Deposit' }.count).to eq 16 expect(result.select { |t| t['type'] == 'Deposit' }.pluck('state').uniq).to match_array(['submitted', 'accepted']) end it 'returns transactions with one deposit state' do expect(Deposit.count).to eq 20 api_get '/api/v2/account/transactions', params: { deposit_state: 'submitted' }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Deposit' }.count).to eq 12 expect(result.select { |t| t['type'] == 'Deposit' }.pluck('state').uniq).to eq (['submitted']) end it 'returns transactions with more than one withdraw state' do expect(Withdraw.count).to eq 20 api_get '/api/v2/account/transactions', params: { withdraw_state: ['accepted', 'prepared'] }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Withdraw' }.count).to eq 16 expect(result.select { |t| t['type'] == 'Withdraw' }.pluck('state').uniq).to match_array(['prepared', 'accepted']) end it 'returns transactions with one withdraw state' do expect(Withdraw.count).to eq 20 api_get '/api/v2/account/transactions', params: { withdraw_state: 'prepared' }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Withdraw' }.count).to eq 12 expect(result.select { |t| t['type'] == 'Withdraw' }.pluck('state').uniq).to eq (['prepared']) end it 'returns transactions with one withdraw state and one deposit state' do expect(Withdraw.count).to eq 20 expect(Deposit.count).to eq 20 api_get '/api/v2/account/transactions', params: { withdraw_state: 'rejected', deposit_state: 'rejected' }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Deposit' }.count).to eq 4 expect(result.select { |t| t['type'] == 'Withdraw' }.count).to eq 4 expect(result.select { |t| t['type'] == 'Deposit' }.pluck('state').uniq).to eq (['rejected']) expect(result.select { |t| t['type'] == 'Withdraw' }.pluck('state').uniq).to eq (['rejected']) end it 'returns transactions with more than one withdraw state and more that one deposit state' do expect(Withdraw.count).to eq 20 expect(Deposit.count).to eq 20 api_get '/api/v2/account/transactions', params: { withdraw_state: ['rejected', 'accepted'], deposit_state: ['rejected', 'accepted'] }, token: token result = JSON.parse(response.body) expect(result.select { |t| t['type'] == 'Deposit' }.count).to eq 8 expect(result.select { |t| t['type'] == 'Withdraw' }.count).to eq 8 expect(result.select { |t| t['type'] == 'Deposit' }.pluck('state').uniq).to match_array(['accepted','rejected']) expect(result.select { |t| t['type'] == 'Withdraw' }.pluck('state').uniq).to match_array(['accepted','rejected']) end end end context 'fail' do before do btc_account.plus_funds(balance) usd_account.plus_funds(balance) end it 'requires authentication' do api_get '/api/v2/account/transactions' expect(response.code).to eq '401' end it 'validates currency param' do api_get '/api/v2/account/transactions', params: { currency: 'bar' }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.currency_doesnt_exist') end it 'validates order_by param' do api_get '/api/v2/account/transactions', params: { order_by: 'foo' }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.order_by_invalid') end it 'validates time_from param' do api_get '/api/v2/account/transactions', params: { time_from: 'btc' }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.non_integer_time_from') end it 'validates time_to param' do api_get '/api/v2/account/transactions', params: { time_to: [] }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.non_integer_time_to') end it 'validates deposit state param' do api_get '/api/v2/account/transactions', params: { deposit_state: [] }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.invalid_deposit_state') end it 'validates withdraw state param' do api_get '/api/v2/account/transactions', params: { withdraw_state: [] }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.invalid_withdraw_state') end it 'validates page param' do api_get '/api/v2/account/transactions', params: { page: -1 }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.non_positive_page') api_get '/api/v2/account/transactions', params: { page: 'btc' }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.non_integer_page') end it 'validates limit param' do api_get '/api/v2/account/transactions', params: { limit: 1001 }, token: token expect(response.code).to eq '422' expect(response).to include_api_error('account.transactions.invalid_limit') end context 'unauthorized' do before do Ability.stubs(:user_permissions).returns([]) end it 'renders unauthorized error' do api_get '/api/v2/account/transactions', params: { limit: 1000 }, token: token expect(response).to have_http_status 403 expect(response).to include_api_error('user.ability.not_permitted') end end end end end
JRomeoSalazar/marcen
rakefile.rb
require 'coyote/rake' coyote :build do |config| config.input = "src/Sylius/Bundle/WebBundle/Resources/public/less/frontend.less" config.output = "src/Sylius/Bundle/WebBundle/Resources/public/css/frontend.css" end
JRomeoSalazar/marcen
template/rakefile.rb
<gh_stars>0 require 'coyote/rake' coyote :build do |config| config.input = "public/less/frontend.less" config.output = "public/css/frontend.css" end
GinBlades/stm_strategy
lib/generators/stm_strategy/install/templates/omniauth.rb
# Set the following values in secrets.yml: # auth_provider_url: # auth_provider_application_id: # auth_provider_secret: PROVIDER = Rails.application.secrets.auth_provider_url SETUP_PROC = lambda do |env| env['omniauth.strategy'].options[:client_id] = Rails.application.secrets.auth_provider_application_id env['omniauth.strategy'].options[:client_secret] = Rails.application.secrets.auth_provider_secret env['omniauth.strategy'].options[:client_options].site = PROVIDER env['omniauth.strategy'].options[:client_options].authorize_url = "#{PROVIDER}/oauth/authorize" env['omniauth.strategy'].options[:client_options].access_token_url = "#{PROVIDER}/oauth/token" end Rails.application.config.middleware.use OmniAuth::Builder do provider :stm, setup: SETUP_PROC end
GinBlades/stm_strategy
lib/omniauth/strategies/stm.rb
<reponame>GinBlades/stm_strategy<gh_stars>0 require 'omniauth-oauth2' module OmniAuth module Strategies class Stm < OmniAuth::Strategies::OAuth2 option :name, :stm uid { raw_info['id'] } info do { email: raw_info['email'], admin: raw_info['admin'] } end extra do { #current_sign_in_at: raw_info['extra']['current_sign_in_at'], #name: raw_info['extra']['name'] #first_name: raw_info['extra']['first_name'], #:last_name => raw_info['extra']['last_name'] } end def raw_info @raw_info ||= access_token.get("/oauth/me.json").parsed end def callback_url options[:redirect_uri] || (full_host + script_name + callback_path) end end end end
GinBlades/stm_strategy
lib/stm_strategy.rb
require "stm_strategy/engine" require 'omniauth-oauth2' require 'omniauth/strategies/stm' module StmStrategy end
GinBlades/stm_strategy
app/controllers/stm_strategy/application_controller.rb
<filename>app/controllers/stm_strategy/application_controller.rb module StmStrategy class ApplicationController < ActionController::Base protect_from_forgery before_action :check_cookie def check_cookie if !cookie_valid? session[:user_id] = nil end end def cookie_valid? cookies[:stm_strategy].present? && session[:user_id].present? && cookies[:stm_strategy].to_s == session[:user_id].to_s end def login_required if !current_user not_authorized end end def not_authorized respond_to do |format| format.html{ auth_redirect } format.json{ head :unauthorized } end end def auth_redirect observable_redirect_to "/auth/stm?origin=#{request.protocol}#{request.host_with_port}#{request.fullpath}" end def current_user return nil unless session[:user_id] @current_user ||= User.find_by_id(session[:user_id]) end def signed_in? current_user.present? end helper_method :signed_in? helper_method :current_user private # These two methods help with testing def integration_test? Rails.env.test? && defined?(Cucumber::Rails) end def observable_redirect_to(url) if integration_test? render :text => "If this wasn't an integration test, you'd be redirected to: #{url}" else redirect_to url end end end end
GinBlades/stm_strategy
config/routes.rb
<filename>config/routes.rb Rails.application.routes.draw do # omniauth get '/auth/:provider/callback', :to => 'stm_strategy/user_sessions#create' get '/auth/failure', :to => 'stm_strategy/user_sessions#failure' # Custom logout post '/logout', :to => 'stm_strategy/user_sessions#destroy' end
EnisAdemov/WKJavaScriptController
WKJavaScriptController.podspec
<gh_stars>0 Pod::Spec.new do |s| s.name = 'WKJavaScriptController' s.version = '1.1.9' s.summary = 'Calling native code from Javascript in the iOS application likes JavascriptInterface in the Android.' s.homepage = 'https://github.com/EnisAdemov/WKJavaScriptController' s.authors = { 'Ridibooks Viewer Team' => '<EMAIL>' } s.license = 'MIT' s.ios.deployment_target = '8.0' s.source = { :git => 'https://github.com/EnisAdemov/WKJavaScriptController.git', :tag => s.version } s.source_files = 'WKJavaScriptController/WKJavaScriptController.swift' s.frameworks = 'Foundation', 'WebKit' end
ajroetker/puppet
lib/puppet/file_serving/metadata.rb
<filename>lib/puppet/file_serving/metadata.rb require 'puppet' require 'puppet/indirector' require 'puppet/file_serving' require 'puppet/file_serving/base' require 'puppet/util/checksums' # A class that handles retrieving file metadata. class Puppet::FileServing::Metadata < Puppet::FileServing::Base include Puppet::Util::Checksums extend Puppet::Indirector indirects :file_metadata, :terminus_class => :selector attr_reader :path, :owner, :group, :mode, :checksum_type, :checksum, :ftype, :destination PARAM_ORDER = [:mode, :ftype, :owner, :group] def checksum_type=(type) raise(ArgumentError, "Unsupported checksum type #{type}") unless respond_to?("#{type}_file") @checksum_type = type end class MetaStat extend Forwardable def initialize(stat, source_permissions = nil) @stat = stat @source_permissions_ignore = source_permissions == :ignore end def owner @source_permissions_ignore ? Process.euid : @stat.uid end def group @source_permissions_ignore ? Process.egid : @stat.gid end def mode @source_permissions_ignore ? 0644 : @stat.mode end def_delegators :@stat, :ftype end class WindowsStat < MetaStat if Puppet.features.microsoft_windows? require 'puppet/util/windows/security' end def initialize(stat, path, source_permissions = nil) super(stat, source_permissions) @path = path end { :owner => 'S-1-5-32-544', :group => 'S-1-0-0', :mode => 0644 }.each do |method, default_value| define_method method do return default_value if @source_permissions_ignore # this code remains for when source_permissions is not set to :ignore begin Puppet::Util::Windows::Security.send("get_#{method}", @path) || default_value rescue Puppet::Util::Windows::Error => detail # Very carefully catch only this specific error that result from # trying to read permissions on a symlinked file that is on a volume # that does not support ACLs. # # Unfortunately readlink method will not return the target path when # the given path is not the symlink. # # For instance, consider: # symlink c:\link points to c:\target # FileSystem.readlink('c:/link') returns 'c:/target' # FileSystem.readlink('c:/link/file') will NOT return 'c:/target/file' # # Since detecting this up front is costly, since the path in question # needs to be recursively split and tested at each depth in the path, # we catch the standard error that will result from trying to read a # file that doesn't have a DACL - 1336 is ERROR_INVALID_DACL # # Note that this affects any manually created symlinks as well as # paths like puppet:///modules return default_value if detail.code == 1336 # Also handle a VirtualBox bug where ERROR_INVALID_FUNCTION is # returned when following a symlink to a volume that is not NTFS. # It appears that the VirtualBox file system is not propagating # the standard Win32 error code above like it should. # # Apologies to all who enter this code path at a later date if detail.code == 1 && Facter.value(:virtual) == 'virtualbox' return default_value end raise end end end end def collect_stat(path, source_permissions) stat = stat() if Puppet.features.microsoft_windows? WindowsStat.new(stat, path, source_permissions) else MetaStat.new(stat, source_permissions) end end # Retrieve the attributes for this file, relative to a base directory. # Note that Puppet::FileSystem.stat(path) raises Errno::ENOENT # if the file is absent and this method does not catch that exception. def collect(source_permissions = nil) real_path = full_path stat = collect_stat(real_path, source_permissions) @owner = stat.owner @group = stat.group @ftype = stat.ftype # We have to mask the mode, yay. @mode = stat.mode & 007777 case stat.ftype when "file" @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", real_path).to_s when "directory" # Always just timestamp the directory. @checksum_type = "ctime" @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", path).to_s when "link" @destination = Puppet::FileSystem.readlink(real_path) @checksum = ("{#{@checksum_type}}") + send("#{@checksum_type}_file", real_path).to_s rescue nil else raise ArgumentError, "Cannot manage files of type #{stat.ftype}" end end def initialize(path,data={}) @owner = data.delete('owner') @group = data.delete('group') @mode = data.delete('mode') if checksum = data.delete('checksum') @checksum_type = checksum['type'] @checksum = checksum['value'] end @checksum_type ||= Puppet[:digest_algorithm] @ftype = data.delete('type') @destination = data.delete('destination') super(path,data) end def to_data_hash super.update( { 'owner' => owner, 'group' => group, 'mode' => mode, 'checksum' => { 'type' => checksum_type, 'value' => checksum }, 'type' => ftype, 'destination' => destination, } ) end def self.from_data_hash(data) new(data.delete('path'), data) end def self.from_pson(data) Puppet.deprecation_warning("from_pson is being removed in favour of from_data_hash.") self.from_data_hash(data) end end
ajroetker/puppet
acceptance/tests/environment/enc_nonexistent_directory_environment.rb
<gh_stars>0 test_name "Master should produce error if enc specifies a nonexistent environment" testdir = create_tmpdir_for_user master, 'nonexistent_env' apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => '0770', } file { "#{testdir}":; "#{testdir}/environments":; "#{testdir}/environments/production":; "#{testdir}/environments/production/manifests":; "#{testdir}/environments/production/manifests/site.pp": ensure => file, mode => '0644', content => 'notify { "In the production environment": }'; "#{testdir}/enc.rb": ensure => file, mode => '0775', content => '#!#{master['puppetbindir']}/ruby puts "environment: doesnotexist" '; } MANIFEST master_opts = { 'main' => { 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb", 'environmentpath' => "#{testdir}/environments", } } with_puppet_running_on master, master_opts, testdir do agents.each do |agent| on(agent, puppet("agent --no-daemonize --onetime --server #{master} --verbose")) do assert_match(/Could not find a directory environment named 'doesnotexist'/, stderr, "Errors when nonexistant environment is specified") assert_not_match(/In the production environment/, stdout, "Executed manifest from production environment") end end end
jreidinger/pull_requests_reminder
pr_reminder.rb
#! /usr/bin/env ruby require 'open-uri' require 'json' require 'ostruct' class GitHubAPI @@api_token_file = File.expand_path(File.dirname(__FILE__)) + "/api_token" @@api_token = nil def self.token if !@@api_token if ENV['GH_API_TOKEN'] @@api_token = ENV['GH_API_TOKEN'] elsif File.exists?(@@api_token_file) @@api_token = File.open(@@api_token_file).read.gsub("\n", "") end end @@api_token end def self.load_repos_in_page(organization, page) url = "https://api.github.com/orgs/#{organization}/repos?page=#{page}&per_page=100" if self.token url += "&access_token=#{self.token}" end open(url) do |json_file| JSON.load(json_file.gets).map { |repo_data| Repository.new(repo_data) } end end def self.pending_pull_requests(repository) pull_requests = [] url = "https://api.github.com/repos/#{repository}/pulls" if self.token url += "?access_token=#{self.token}" end open(url) do |json_file| pull_requests = JSON.load(json_file.gets).map { |pr_data| PullRequest.new(pr_data) } end pull_requests.select do |pull_request| next false if pull_request.draft days = (Time.now.monday? || Time.now.tuesday?) ? 5 : 3 # do not count weekend in pending time pull_request.pending_days > days end end end # Represents an Organization in GitHub class Organization attr_reader :name def initialize(name) @name = name end # Retrieves all the repositories of the organization (with PRs by default) def repositories_with_pull_requests(reponames = []) repositories = [] page = 1 loop do repositories_in_page = load_repos_in_page(page) break if repositories_in_page.empty? repositories.concat(repositories_in_page) page += 1 end repositories.select! { |repo| reponames.include?(repo.name) } unless reponames.empty? repositories.select!(&:any_pull_requests?) repositories end private # Load repositories in the page from GitHub def load_repos_in_page(page) GitHubAPI.load_repos_in_page(name, page) end end # Represents a Repository in GitHub class Repository < OpenStruct def pending_pull_requests GitHubAPI.pending_pull_requests(full_name) end def any_pull_requests? # approximate with issues as there is no quick check for pull request # used only for quick decision if we need to inspect it open_issues_count > 0 end end # Represents a PullRequest in GitHub class PullRequest < OpenStruct def updated @updated ||= Time.parse(updated_at) end def pending_days ((Time.now - updated) / 24 / 3600).floor end end def usage <<-END #{$PROGRAM_NAME} <github organization> [repo-name-1] [repo-name-2] ... [repo-name-n] Tool to print report about pending pull request of given organization repositories. If a whitelist of repository names is passed then the tool will filter the results by them. END end if ARGV.empty? puts usage exit 1 end organization, *reponames = ARGV message = "" begin Organization.new(organization).repositories_with_pull_requests(reponames).each do |repository| pending_pull_requests = repository.pending_pull_requests next if pending_pull_requests.empty? message << "\nPending requests in repository #{repository.name}:\n" pending_pull_requests.each do |pull_request| message << " - " pull_request.labels.each { |label| message << "[#{label["name"]}] " } message << "#{pull_request.title} (#{pull_request.pending_days} days)\n" message << " #{pull_request.html_url}\n\n" end end rescue OpenURI::HTTPError message << "\n\n ERROR: API query limit exceeded" end puts message
vigo/textmate2-gfm-preview
Support/urlify.rb
require 'rubygems' require 'bundler/setup' Bundler.require LINK_REGEX_PATTERN = /^\[(.+)\]\(([a-z\-\.]+)\)$/ if ENV['TM_SELECTED_TEXT'] input = ENV['TM_SELECTED_TEXT'] input_has_patched = input.scan(LINK_REGEX_PATTERN) if input_has_patched.size > 0 text = input_has_patched.first.first link = input_has_patched.first.last out = text if input == "[#{text}](#{link})" else out = "[#{input}](#{input.to_url}.md)" end print out end
vigo/textmate2-gfm-preview
Support/gfm.rb
require 'rubygems' require 'bundler/setup' Bundler.require require 'rouge/plugins/redcarpet' DELIMITER = /^---\s*$/ TIME_STAMP = Time.now.strftime('%s') CSS_FILES = ['github-markdown', 'syntax-hightlight'].map do |f| "<link rel=\"stylesheet\" href=\"file://#{ENV['TM_BUNDLE_SUPPORT']}/css/#{f}.css?#{TIME_STAMP}\">" end jl = ['jquery.1.12.4.min', 'app'] jl.map! do |f| "<script type=\"text/javascript\" src=\"file://#{ENV['TM_BUNDLE_SUPPORT']}/js/#{f}.js?#{TIME_STAMP}\"></script>" end if ENV['TM_MARKDOWN_MATHJAX'].to_i > 0 jl << "<script type=\"text/x-mathjax-config\"> MathJax.Hub.Config({ extensions: [\"tex2jax.js\"], jax: [\"input/TeX\", \"output/HTML-CSS\"], tex2jax: { inlineMath: [ [\"$\",\"$\"], [\"\\\\(\",\"\\\\)\"] ], displayMath: [ [\"$$\",\"$$\"], [\"\\\\[\",\"\\\\]\"] ], processEscapes: false }, \"HTML-CSS\": { availableFonts: [\"TeX\"] } }); </script>" jl << "<script type=\"text/javascript\" async src=\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>" end JS_FILES = jl class HTMLwithRouge < Redcarpet::Render::HTML include Rouge::Plugins::Redcarpet end def markdown(text) renderer = HTMLwithRouge.new options = { :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :tables => true, :strikethrough => true, # this is ~~good~~ bad :superscript => true, # this is the 2^(nd) time :underline => true, # This is _underlined_ but this is still *italic* :highlight => true, # This is ==highlighted== :quote => true, # This is a "quote" :footnotes => true, # This is a sentence.[^1] # [^1]: This is a footnote. :smart => true, :safelink => true, :no_intraemphasis => true, :filter_html => false, } Redcarpet::Markdown.new(renderer, options).render(text) end extra_css_information = "<style type=\"text/css\"> .github-gfm { %{gfm_zoom_factor} %{gfm_font_factor} } .github-gfm a { %{gfm_link_font_weight} %{gfm_link_text_decoration} } </style>" extra_css_information = extra_css_information % { gfm_zoom_factor: ENV['TM_GFM_ZOOM_FACTOR'] ? "zoom: #{ENV['TM_GFM_ZOOM_FACTOR']};" : "", gfm_font_factor: ENV['TM_GFM_FONT'] ? "font-family: #{ENV['TM_GFM_FONT']};" : "", gfm_link_font_weight: ENV['TM_GFM_LINK_FONT_WEIGHT'] ? "font-weight: #{ENV['TM_GFM_LINK_FONT_WEIGHT']};" : "", gfm_link_text_decoration: ENV['TM_GFM_LINK_TEXT_DECORATION'] ? "text-decoration: #{ENV['TM_GFM_LINK_TEXT_DECORATION']};": "", } preview_title = "Markdown Preview" preview_title= "#{preview_title}: #{File.basename(ENV['TM_FILEPATH'])}" if ENV['TM_FILEPATH'] input_file = STDIN.read def html_header(**kwargs) <<-EOT <html> <head> <title>#{kwargs[:title]}</title> #{kwargs[:css]} #{kwargs[:extra_css]} #{kwargs[:inline_js]} </head> <body> <div class="github-gfm"> EOT end def html_footer(**kwargs) <<-EOT </div> #{kwargs[:js]} </body> </html> EOT end def clear_front_matter(**kwargs) lines = kwargs[:input].split("\n") if lines[0] =~ DELIMITER && (end_of_frontmatter = lines[1..-1].find_index{ |l| l =~ DELIMITER }) != nil lines.slice!(0, end_of_frontmatter + 2) end lines end def render(input, debug=false) return "<textarea rows=\"80\" cols=\"100\">#{input}</textarea>" if debug input end def any_inline_js if ENV['TM_FILEPATH'] "<script type=\"text/javascript\">\nlet localFilePath = \"file://#{File.dirname(ENV['TM_FILEPATH'])}/\";\n</script>" end end html_out = html_header(title: preview_title, css: CSS_FILES.join("\n"), extra_css: extra_css_information, inline_js: any_inline_js) lines = clear_front_matter(input: input_file) current_line = nil if ENV['TM_CURRENT_LINE'] current_line = ENV['TM_CURRENT_LINE'] else selection_line = ENV['TM_SELECTION'].split(':').first.to_i selection_line_index = selection_line - 1 current_line = lines[selection_line_index] end tm_line_number = ENV['TM_LINE_NUMBER'].to_i ANCHOR_IDENTIFIER = 'REPLACEMEMEFORANCHOROPZ' if tm_line_number > lines.length (lines.length+1..tm_line_number-1).each do |n| lines << '' end lines << ANCHOR_IDENTIFIER else if current_line.chomp == lines[tm_line_number-1].chomp lines[tm_line_number-1] = "#{lines[tm_line_number-1]} #{ANCHOR_IDENTIFIER}" else need_index = lines.index(current_line.chomp) lines[need_index] = "#{lines[need_index]} #{ANCHOR_IDENTIFIER}" end end markdown_lines = markdown(lines.join("\n")) html_out = html_out + markdown_lines html_out = html_out + html_footer(js: JS_FILES.join("\n")) if ENV['TM_GFM_DEBUG'] puts render html_out, true else puts render html_out end
fjlanasa/api
gem.deps.rb
source 'https://rubygems.org' gem 'pronto', '~> 0.7.1'
ioquatix/time-zone
lib/time/zone/locking.rb
# Copyright, 2018, by <NAME>. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'thread' class Time module Zone LOCK = Mutex.new def self.zone=(zone) LOCK.synchronize do ENV['TZ'] = zone end end def self.zone LOCK.synchronize do ENV['TZ'] end end UTC = "UTC".freeze def self.utc? zone == UTC end def self.with(zone) LOCK.synchronize do original_zone = ENV['TZ'] begin ENV['TZ'] = zone yield ensure if original_zone ENV['TZ'] = original_zone else ENV.delete('TZ') end end end end end end
ioquatix/time-zone
gems.rb
source "https://rubygems.org" # Specify your gem's dependencies in time-zone.gemspec gemspec
ioquatix/time-zone
time-zone.gemspec
<gh_stars>1-10 require_relative "lib/time/zone/version" Gem::Specification.new do |spec| spec.name = "time-zone" spec.version = Time::Zone::VERSION spec.authors = ["<NAME>"] spec.email = ["<EMAIL>"] spec.summary = "Computes timezones using the system TZ environment variable." spec.homepage = "https://github.com/ioquatix/time-zone" spec.files = Dir['{lib}/**/*', base: __dir__] spec.require_paths = ["lib"] spec.add_development_dependency "bundler" spec.add_development_dependency "rspec" spec.add_development_dependency "bake-bundler" end
ioquatix/time-zone
lib/time/zone/timestamp.rb
# Copyright, 2018, by <NAME>. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative '../zone' require 'date' class Time module Zone class Timestamp include Comparable def self.load(string) self.parse(string) end def self.dump(time) time.strftime end def self.now(zone) self.from(Zone.now(zone), zone) end def self.from(time, zone) self.new(time.year, time.month, time.day, time.hour, time.minute, time.second, zone) end def self.parse(*args) self.from(*Zone.parse(*args)) end def initialize(year, month, day, hour, minute, second, zone = "UTC") @year = year @month = month @day = day @hour = hour @minute = minute @second = second @zone = zone @time = nil end attr :year attr :month attr :day attr :hour attr :minute attr :second attr :zone def convert(zone) self.class.from(Time::Zone.convert(to_time, zone), zone) end # Generate a new time with the specified changes. # @param months [Numeric] add this many months # @param seconds [Numeric] add this many seconds # @param zone [String] forcefully change the timezone without doing any conversion. def with_offset(months = 0, seconds = 0, zone = @zone) current = self if months != 0 current = current.to_datetime >> months end if seconds != 0 # https://bugs.ruby-lang.org/issues/14879 current = Time::Zone.convert(current.to_time + seconds, @zone) end self.class.from(current, zone) end # Add duration in various units. def offset_by(years: 0, months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0) with_offset( years * 12 + months, (((weeks * 7 + days) * 24 + hours) * 60 + minutes) * 60 + seconds ) end # Add duration in seconds. def + duration with_offset(0, duration) end # Return difference in seconds. def - other if other.is_a? Numeric # We are subtracting a duration: with_offset(0, -other) else to_time - other.to_time end end def to_time @time ||= Time::Zone.new(@year, @month, @day, @hour, @minute, @second, @zone).freeze end def to_date to_time.to_date end def to_datetime to_time.to_datetime end def iso8601 to_time.iso8601 end def <=> other to_time <=> other.to_time end DEFAULT_FORMAT = '%Y-%m-%d %H:%M:%S %Z'.freeze def to_s(format = relative_format) to_time.strftime(format.gsub('%Z', @zone)) end def strftime(format = DEFAULT_FORMAT) to_s(format) end def relative_format(now = Timestamp.now(@zone)) if self.year != now.year "%-l:%M%P, %B %-d, %Y, %Z" elsif self.month != now.month or self.day != now.day "%-l:%M%P, %B %-d, %Z" else "%-l:%M%P, %Z" end end alias to_str strftime end end end
ioquatix/time-zone
spec/time/zone_spec.rb
# Copyright, 2018, by <NAME>. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. RSpec.describe Time::Zone do let(:timezone) {"Pacific/Auckland"} let(:utc_offset) {43200} let(:now) {Time::Zone.now(timezone)} context '.new' do it "can compute specific time" do expect(Time::Zone.new(now.year, now.month, now.day, now.hour, now.min, now.sec, timezone)).to be_within(1).of(now) end end context '#utc_offset' do it "should have correct utc offset" do expect(now.utc_offset).to be >= utc_offset end end context '#utc' do it "can get current time" do expect(now.utc).to be_within(1).of(Time.now.utc) end end context '.convert' do let(:utc_time) {Time.now.utc} it "can convert times" do expect(utc_time.utc_offset).to be_zero local_time = Time::Zone.convert(utc_time, timezone) expect(local_time.utc_offset).to be >= utc_offset end it "won't convert localtime twice" do local_time = utc_local_time = nil Time::Zone.with("UTC") do utc_local_time = utc_time.localtime end Time::Zone.with(timezone) do local_time = utc_time.localtime end # This is an issue with Ruby. expect(local_time.utc_offset).to be == 0 end it "can convert times which were already localtime" do # When times are converted, Ruby refuses to do further conversions. utc_local_time = Time::Zone.convert(utc_time, "UTC") local_time = Time::Zone.convert(utc_local_time, timezone) expect(local_time.utc_offset).to be >= utc_offset end end context '.parse' do # String doesn't include timezone information. it "can parse string including timezone" do time, zone = Time::Zone.parse( now.strftime("%c #{timezone}") ) expect(time).to be_within(1).of(now) expect(zone).to be == timezone end it "doesn't modify input string" do Time::Zone.parse( "5pm Pacific/Auckland".freeze ) end end context 'Time#+', if: Time::Zone.utc? do # https://bugs.ruby-lang.org/issues/14879 it "needs to work around bug #14879" do time, _ = Time::Zone.parse("5pm", timezone) expect(time.utc_offset).to_not be == 0 expect((time + 1).utc_offset).to be == 0 end end end
ioquatix/time-zone
spec/time/zone/timestamp_spec.rb
# Copyright, 2018, by <NAME>. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'time/zone/timestamp' RSpec.describe Time::Zone::Timestamp do let(:timezone) {"Pacific/Auckland"} let(:now) {Time::Zone::Timestamp.now(timezone)} let(:birthday) {Time::Zone::Timestamp.parse("12:20:30pm, 2nd April, 1985 Pacific/Auckland")} context '.parse' do it "can parse a string" do timestamp = described_class.parse("2018-04-02 15:14:15 Z") expect(timestamp.year).to be == 2018 expect(timestamp.month).to be == 4 expect(timestamp.day).to be == 2 expect(timestamp.hour).to be == 15 expect(timestamp.minute).to be == 14 expect(timestamp.second).to be == 15 expect(timestamp.zone).to be == "Z" end it "can parse a incomplete string" do timestamp = described_class.parse("May 25, 6pm") expect(timestamp.month).to be == 5 expect(timestamp.day).to be == 25 expect(timestamp.hour).to be == 12+6 end end context '#-' do it "can subtract a duration" do time = birthday - 90 expect(time.minute).to be == (birthday.minute - 1) expect(time.second).to be == (birthday.second - 30) end it "can subtract two timestamps" do duration = now - birthday # I was older than 30 when I wrote this test :) expect(duration).to be > (30*365*24*60*60) end it "subtracts correctly" do time = described_class.parse("2018-06-28 17:00:00 Pacific/Auckland") - 1 expect(time.year).to be == 2018 expect(time.month).to be == 6 expect(time.day).to be == 28 expect(time.hour).to be == 16 expect(time.minute).to be == 59 expect(time.second).to be == 59 end end context '#iso8601' do it "generates valid string" do expect(now.iso8601).to be =~ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}/ end end context '#stftime' do it "generates valid string according to default format" do expect(birthday.strftime).to be == "1985-04-02 12:20:30 Pacific/Auckland" end end end
ioquatix/time-zone
spec/spec_helper.rb
<filename>spec/spec_helper.rb if ENV['COVERAGE'] || ENV['TRAVIS'] begin require 'simplecov' SimpleCov.start do add_filter "/spec/" end if ENV['TRAVIS'] require 'coveralls' Coveralls.wear! end rescue LoadError warn "Could not load simplecov: #{$!}" end end require "bundler/setup" require "time/zone" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
ioquatix/time-zone
bug14879.rb
#!/usr/bin/env ruby # https://bugs.ruby-lang.org/issues/14879 require 'time' ENV['TZ'] = "Pacific/Auckland" time = Time.parse("5pm") ENV['TZ'] = "UTC" puts time puts time.utc_offset puts (time + 1).utc_offset puts time + 1
ioquatix/time-zone
lib/time/zone.rb
# Copyright, 2018, by <NAME>. <http://www.codeotaku.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'zone/version' require_relative 'zone/locking' require 'time' class Time alias minute min alias second sec module Zone def self.new(year, month, day, hour, minute, second, zone) with(zone) do return Time.new(year, month, day, hour, minute, second).localtime end end def self.now(zone) with(zone) do # Time instances are lazy initialized, so we need to force it to pick up the current TZ by invoking #localtime return Time.new.localtime end end def self.convert(time, zone) with(zone) do return Time.new(time.year, time.month, time.day, time.hour, time.minute, time.second, time.utc_offset).localtime end end def self.parse(string, zone = "UTC", *args) string = string.dup if string.sub!(/\s([a-zA-Z][\w]*(\/[\w]+)?)$/, "") zone = $1 end with(zone) do return Time.parse(string, *args).localtime, zone end end end end
Calvin-Huang/omniauth-gitbook
spec/omniauth/strategies/gitbook_spec.rb
require 'spec_helper' describe OmniAuth::Strategies::GitBook do subject do OmniAuth::Strategies::GitBook.new({}) end context 'client options' do it 'should have correct site' do subject.options.client_options.site.should eq('https://api.gitbook.com') end it 'should have correct authorize url' do subject.options.client_options.authorize_url.should eq('https://api.gitbook.com/oauth/authorize') end it 'should have correct request access token target' do subject.options.client_options.token_url.should eq('https://api.gitbook.com/oauth/access_token') end end # context 'request access params' do # it 'should have response_type whether user set in config' do # subject.options.authorize_params['request_type'].should eq('code') # end # end end
Calvin-Huang/omniauth-gitbook
lib/omniauth/strategies/gitbook.rb
<reponame>Calvin-Huang/omniauth-gitbook<filename>lib/omniauth/strategies/gitbook.rb require 'omniauth-oauth2' module OmniAuth module Strategies class GitBook < OmniAuth::Strategies::OAuth2 base_url = 'https://api.gitbook.com' option :client_options, { site: base_url, authorize_url: "#{base_url}/oauth/authorize", token_url: "#{base_url}/oauth/access_token", } uid { raw_info['id'].to_s } info do { 'username' => raw_info['username'], 'name' => raw_info['name'], 'website' => raw_info['website'], 'urls' => raw_info['urls'], 'auth' => raw_info['auth'], 'token' => raw_info['token'], } end extra do { raw_info: raw_info, books: books } end def raw_info @raw_info ||= access_token.get('account').parsed end def books @books ||= access_token.get('books').parsed end def authorize_params super.tap do |params| %w[response_type].each do |v| params[v.to_sym] = 'code' end end end def request_phase super end end end end OmniAuth.config.add_camelization 'gitbook', 'GitBook'
Calvin-Huang/omniauth-gitbook
lib/omniauth-gitbook.rb
<filename>lib/omniauth-gitbook.rb<gh_stars>0 require 'gitbook/version' require 'omniauth/strategies/gitbook'
Calvin-Huang/omniauth-gitbook
spec/spec_helper.rb
<reponame>Calvin-Huang/omniauth-gitbook<filename>spec/spec_helper.rb require 'rspec' require 'rack/test' require 'webmock/rspec' require 'omniauth' require 'omniauth-gitbook' RSpec.configure do |config| config.include WebMock::API config.include Rack::Test::Methods config.extend OmniAuth::Test::StrategyMacros, type: :strategy end
alelee93/yelp_api
lib/cli.rb
<filename>lib/cli.rb<gh_stars>0 class CLI def initialize @page = 1 @limit = 20 @@favorites = [] end def start introduction business_loop end def get_business_data(loc, query) puts "\n\n MAKING A NETWORK REQUEST ... \n\n" business_array = APIManager.search_businesses(loc, query, @page, @limit) if business_array == nil || business_array.length < 1 @status = 'N/A' if @page > 1 puts "There are no more pages!" decrease_page end else @status = 'good' Business.mass_create_from_api(business_array) end end def exit_in_queue? return @query_answer != "exit" && @loc_answer != 'exit' end def business_loop task_answer = '' while task_answer != 'exit' && exit_in_queue? menu task_answer = gets.chomp.downcase if task_answer.to_i == 1 puts "What are you looking for? (i.e. piano lessons, dance studios ...)" @query_answer = gets.chomp.downcase break if @query_answer.downcase == 'exit' puts "In what city are you looking (i.e. Houston, Las Vegas ...)?" @loc_answer = gets.chomp.downcase puts "\n\n" break if @loc_answer.downcase == 'exit' get_business_data(@loc_answer, @query_answer) if @status == 'N/A' puts "Sorry we couldn't find any results. Please try another search." start break ##do I need this? elsif @status == 'good' more_options_message display_businesses end next_answer = '' while next_answer != 'exit' next_answer = gets.chomp.downcase if next_answer == 'main menu' Business.clear Reviews.clear start break #just added this, do I need this? elsif next_answer == 'prev' if @page <= 1 puts "\n\n You are already on the first page." more_options_message else decrease_page display_businesses end elsif next_answer == 'next' increase_page _, stop = get_page_range if Business.all.length < stop get_business_data(@loc_answer, @query_answer) display_businesses else display_businesses end elsif next_answer.include?('favorites') fav_item = next_answer.gsub('favorites','').to_i if valid?(fav_item) @@favorites << Business.all[fav_item - 1] puts "\n\n\n\n\n\n\n\n\n #{Business.all[fav_item - 1].name} has been added to your favorites." puts "There are #{@@favorites.length} item(s) in your favorites list." sleep(1) more_options_message else puts "Please enter a valid number to add favorite or type 'exit' to leave the program." end elsif valid?(next_answer) more_details(Business.all[next_answer.to_i - 1]) else puts "Please enter a valid response." end end break elsif task_answer.to_i == 2 puts "******************* #{@@favorites.length} item(s) in your FAVORITES LIST ************************" puts "\n\n\n" if @@favorites.length > 0 more_options_favorites_message favorites response = gets.chomp.downcase if response == 'exit' break elsif response == 'main menu' start elsif response.include?('remove') remove_item = response.gsub('remove', '').to_i if remove_item.between?(1,@@favorites.length) puts "#{@@favorites[remove_item - 1].name} has been removed from your favorites." @@favorites.delete_at(remove_item - 1) start else puts "Please enter a valid number to remove a favorite or 'exit' to leave the program." end elsif response.to_i.between?(1,@@favorites.length) more_details(@@favorites[response.to_i - 1]) else puts "Please enter a valid response." end end elsif task_answer != 'exit' && task_answer.to_i.abs > 2 puts "Please select a valid number or type 'exit' to leave the program." puts "\n\n" end end puts "You have left the program. Goodbye!" end def display_businesses start, stop = get_page_range puts "\n\nPAGE #{@page}" Business.all[start...stop].each.with_index(start) do |business, index| puts "\n" puts "#{index+1} .......................... " display_single_business(business) end end def display_single_business(business) puts "Business Name: #{business.name}" puts "Rating: #{business.rating}" puts "Address: " + business.location["display_address"].join(", ") end def get_page_range [(@page - 1) * @limit , @page * @limit ] end def valid?(i) i.to_i.between?(1, Business.all.length) end def mass_get_reviews(business_array) start, stop = get_page_range business_array[start...stop].each do |business| APIManager.search_reviews(business.id) end end def get_reviews(business) #puts "\n\n MAKING A NETWORK REQUEST ... \n\n" APIManager.search_reviews(business.id) end def display_reviews(business) business.reviews.each_with_index do |review, index| puts "#{index+1} .......................... " puts "Review by: #{review.user["name"]}" puts "Rating: #{review.rating}" puts "Review: #{review.text}" puts "\n" end end def more_details(business) get_reviews(business) if Reviews.get_reviews_from_business(business) == nil categories = [] business.categories.each { |category_hash| categories << category_hash["title"] } puts "\n\n\n" puts "********** #{business.name.upcase} **********" puts "\n" puts "Rating: #{business.rating} | #{business.review_count} reviews" puts "Categories: " + categories.join(' | ') if categories != nil puts "Price: #{business.price}" if business.price !=nil puts "Phone: #{business.display_phone}" if business.display_phone != nil puts "Address: " + business.location["display_address"].join(", ") if business.location["display_address"] != nil puts "URL: #{business.url}" if business.url != nil puts "\n" puts "********** REVIEWS ***********" puts "\n" display_reviews(business) end def favorites @@favorites.each.with_index do |business, index| puts "\n" puts "Item # #{index+1}" display_single_business(business) end end def add_to_favorites @@favorites << self end def increase_page @page += 1 end def decrease_page @page -= 1 end def more_options_favorites_message Messages.more_options_favorites_message end def introduction Messages.intro end def menu Messages.menu end def more_options_message #puts Messages.more_options puts <<-MORE For more information on a business type the number of the business Type a business by number followed by 'favorites' (example: 4 favorites) to add a business to your favorte's list Type 'next' to browse more businesses #{"or 'prev' to see the previous page" if @page > 1} Type 'main menu' to go back to your homepage Type 'exit' to exit the program MORE end end
alelee93/yelp_api
lib/api_manager.rb
<reponame>alelee93/yelp_api<filename>lib/api_manager.rb class APIManager BASE_URL = "https://api.yelp.com/v3" def self.search_businesses(loc, query, pagenum=1, limit=20) business_search_url = BASE_URL + "/businesses/search" + "?limit=#{limit}&offset=#{(pagenum-1)*limit}" headers = {"Authorization": "Bearer #{ENV['API_KEY']}"} query = {"location": loc, "term": query} res = HTTParty.get(business_search_url, query: query, headers: headers) res["businesses"] end def self.search_reviews(business_id) reviews_search_url = BASE_URL + "/businesses/#{business_id}/reviews" headers = {"Authorization": "Bearer #{ENV['API_KEY']}"} res = HTTParty.get(reviews_search_url, {headers: headers}) b = Business.all.detect do |b| b.id == business_id end res["reviews"].each do |review_hash| Reviews.new(b, review_hash) end end end
alelee93/yelp_api
lib/response_strategy.rb
class ResponseStrategy def self.get_and_respond_to(prompt: , accepted_commands:, if_fail: ->(){ puts "That is an unknown command try again"},should_downcase: true, should_intergierize: false) loop do puts prompt user_input = gets.strip user_input = user_input.downcase if should_downcase if accepted_commands.is_a? Array if accepted_commands.include? user_input yield user_input break else if_fail[] end else if accepted_commands[user_input] yield user_input break else if_fail[] end end end end end prompt = "Please select a valid input from 1-10" accepted_commands = Proc.new do |input| commands = ['exit', 'more'] if !commands.include? input return (input.to_i - 1).between?(0,9) else return true end end ResponseStrategy.get_and_respond_to(prompt: prompt, accepted_commands: accepted_commands) do |user_input| display_business(Business.all[user_input]) end ResponseStrategy.get_and_respond_to(prompt: "type iexit or more", accepted_commands: ["exit", "more"]) do |user_input| case user_input when "exit" when "more" end end # 2.6.1 :001 > hi_ale = ->(phrase){ puts "Hey Ale! #{phrase}"} # => #<Proc:0x00007f972aa3e760@(irb):1 (lambda)> # 2.6.1 :002 > say_hi = _ # => #<Proc:0x00007f972aa3e760@(irb):1 (lambda)> # 2.6.1 :003 > say_hi["you are upser cool"] # Hey Ale! you are upser cool # => nil # 2.6.1 :004 > saystuff = Proc.new do |phrase| # 2.6.1 :005 > puts phrase # 2.6.1 :006?> puts "aleeeee!!!" # 2.6.1 :007?> end # => #<Proc:0x00007f972a877170@(irb):4> # 2.6.1 :008 > saystuff["whats uppppp"] # whats uppppp
alelee93/yelp_api
lib/yelp_api.rb
require 'pry' require 'httparty' require_relative "./yelp_api/version" require_relative "./cli" require_relative "./api_manager" require_relative "./business" require_relative "./reviews" require_relative "./messages" ENV["runtime"] ||= "development" if ENV["runtime"] == "development" require_relative "../secrets" end module YelpApi class Error < StandardError; end # Your code goes here... end
alelee93/yelp_api
lib/business.rb
class Business attr_accessor :categories, :coordinates, :display_phone, :distance, :id, :alias, :image_url, :is_closed, :location, :name, :phone, :price, :rating, :review_count, :url, :transactions @@all = [] def initialize(business_hash) @reviews = [] business_hash.each do |key, value| self.send("#{key}=", value) end save end def self.mass_create_from_api(businesses_array) businesses_array.each do |business_hash| created_business = self.new(business_hash) end end def save @@all << self end def self.all @@all end def self.clear all.clear end def add_review(review_instance) if review_instance.business == nil review_instance.business = self end if @reviews.include?(review_instance) == false @reviews << review_instance end end def reviews @reviews end end
alelee93/yelp_api
lib/messages.rb
class Messages def self.menu puts "What would you like to do today? Select a number from the menu below." sleep(1) puts <<-MENU ..........MENU.......... 1. New Yelp search 2. Browse Favorites list Type 'exit' to leave the program MENU end def self.intro puts "\n\n" puts "Welcome Yelp Class Finder!" sleep(2) puts "\n\n" end def self.more_options_favorites_message puts <<-MORE For more information on a business type the number of the business Type a business by number followed by 'remove' (example: 1 remove) to remove a business from your favorte's list Type 'main menu' to go back to your homepage Type 'exit' to exit the program MORE end end
alelee93/yelp_api
lib/yelp_api/version.rb
module YelpApi VERSION = "0.1.0" end
alelee93/yelp_api
lib/reviews.rb
<filename>lib/reviews.rb class Reviews attr_accessor :id, :text, :url, :rating, :time_created, :user @@all = [] def initialize(a_business = nil, review_hash) self.business=(a_business) if a_business != nil review_hash.each do |key, value| self.send("#{key}=", value) end save end def business @business end def business=(business) @business = business business.add_review(self) end def save @@all << self end def self.all @@all end def self.clear all.clear end def self.get_reviews_from_business(business) self.all.detect do |i| i.business == business end end end
sunner/homebrew-cask
Casks/diskcatalogmaker.rb
cask "diskcatalogmaker" do version "8.3.1" sha256 :no_check url "https://download.diskcatalogmaker.com/zip/DiskCatalogMaker.zip" name "DiskCatalogMaker" desc "Toast-bundled version of DiskCatalogMaker" homepage "https://diskcatalogmaker.com/" livecheck do url "https://download.diskcatalogmaker.com/zip/DiskCatalogMaker.zip" strategy :header_match do |headers| headers["location"][/DiskCatalogMaker(\d+).zip/i, 1].split("", 3).join(".") end end app "DiskCatalogMaker.app" end
sunner/homebrew-cask
Casks/heimatdefender-rebellion.rb
cask "heimatdefender-rebellion" do version :latest sha256 :no_check url "https://www.heimat-defender.de/download/11002/" name "Heimat Defender: Rebellion" desc "2D platformer game" homepage "https://www.heimat-defender.de/en/" app "HeimatDefender.app" zap trash: [ "~/Library/Application Support/com.moremountains.corgiengine", "~/Library/Logs/Ein Prozent e.V_/HeimatDefender", "~/Library/Preferences/com.moremountains.corgiengine.plist", "~/Library/Saved Application State/com.moremountains.corgiengine.savedState", ] end
willrstern/mean-boilerplate
config/deploy/staging.rb
server 'staging.server.com', user: 'deploy', roles: %w{web} set :branch, ENV['branch'] || proc { `git rev-parse --abbrev-ref HEAD`.chomp } || 'master'
willrstern/mean-boilerplate
config/deploy.rb
lock '3.1.0' set :application, "my-application" set :repo_url, "<EMAIL>:youruser/#{fetch(:application)}.git" set :deploy_to, "~/#{fetch(:application)}" set :pty, true set :ssh_options, { keys: %w(provisioning/files/ssh/id_rsa), forward_agent: true, auth_methods: %w(publickey, password) } namespace :deploy do desc 'Restart application' task :restart do on roles(:web), in: :sequence do execute "forever stopall || true" execute "cd #{release_path}; NODE_ENV=#{fetch(:stage)} forever start server/cluster.js" end end after :updating, :npm after :publishing, :restart end
willrstern/mean-boilerplate
config/deploy/production.rb
<reponame>willrstern/mean-boilerplate server 'server.com', user: 'deploy', roles: %w{web}
Marketcircle/Specs
grabKit/1.3.1/grabKit.podspec
<reponame>Marketcircle/Specs Pod::Spec.new do |s| s.name = "grabKit" s.version = "1.3.1" s.summary = "Drop-in iOS component to easily import photos from Facebook, FlickR, Instagram, Picasa, and more." s.description = <<-DESC GrabKit allows you to retrieve photos from : * Facebook * FlickR * Picasa * Instagram * iPhone/iPad * ... and more to come. DESC s.homepage = "https://github.com/pierrotsmnrd/grabKit" s.screenshots = "https://github.com/pierrotsmnrd/grabKit/blob/master/doc/demo.gif" s.license = { :type => 'MIT', :file => 'LICENSE.txt' } s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/pierrotsmnrd/grabKit.git", :tag => "v1.3.1" } s.platform = :ios, '5.1' s.requires_arc = true s.source_files = 'grabKit/grabKit/**/*.{h,m}' s.dependency 'Facebook-iOS-SDK', '~> 3.2.0' s.dependency 'ISO8601DateFormatter', '~> 0.6' s.dependency 'MBProgressHUD', '~> 0.6' s.dependency 'NVUIGradientButton', '~> 1.3.0' s.dependency 'PSTCollectionView', '~> 0.0.1' s.dependency 'objectiveflickr', '~> 2.0.2' s.subspec 'GData' do |gdata| gdata.dependency 'GData', '~> 0.0.1' gdata.requires_arc = false end end
Marketcircle/Specs
Chartbeat/0.0.1/Chartbeat.podspec
<filename>Chartbeat/0.0.1/Chartbeat.podspec Pod::Spec.new do |s| s.name = 'Chartbeat' s.version = '0.0.1' s.license = 'Commercial' s.summary = 'Chartbeat analytics library for iOS.' s.homepage = 'https://chartbeat.com/docs/ios/' s.author = { 'Chartbeat' => 'https://chartbeat.com' } s.source = { :git => 'https://github.com/segmentio/chartbeat.git', :tag => '0.0.1' } s.source_files = 'CBTracker.h' s.preserve_paths = '*.a' s.library = 'Chartbeat-iOS-SDK' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/Chartbeat"' } end
Marketcircle/Specs
UniversalDetector/1.0.0/UniversalDetector.podspec
<reponame>Marketcircle/Specs Pod::Spec.new do |s| s.name = 'UniversalDetector' s.version = '1.0.0' s.license = { :type => 'Mozilla Public License', :file => 'LICENSE' } s.summary = 'Wrapper of uchardet for Objective-C.' s.description = 'UniversalDetector takes a sequence of bytes in an unknown character encoding without any additional information, and attempts to determine the encoding of the text.' s.homepage = 'https://github.com/siuying/UniversalDetector' s.author = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/siuying/UniversalDetector.git', :tag => '1.0.0', :submodules => true } s.source_files = 'UniversalDetector/*.{h,m}', 'external/uchardet/src/*.{cpp,h,tab}', 'external/uchardet/src/tools/*.cpp' s.public_header_files = 'UniversalDetector/*.h', 'external/uchardet/src/uchardet.h' s.library = 'stdc++' s.requires_arc = true end
Marketcircle/Specs
QR-Code-Encoder-for-Objective-C/1.0.0/QR-Code-Encoder-for-Objective-C.podspec
Pod::Spec.new do |spec| spec.name = 'QR-Code-Encoder-for-Objective-C' spec.platform = :ios spec.version = '1.0.0' spec.license = 'Apache2.0' spec.summary = 'An implementation of QR code encoder for Objective-C ported from Psytec library.' spec.homepage = 'https://github.com/myang-git/QR-Code-Encoder-for-Objective-C' spec.author = { '<NAME>' => '<EMAIL>' } spec.source = { :git => 'https://github.com/myang-git/QR-Code-Encoder-for-Objective-C.git', :tag => '1.0.0' } spec.source_files = 'QRCodeEncoderObjectiveCAtGithub/**/*.{h,m,mm,cpp}' spec.requires_arc = false end
Marketcircle/Specs
STTwitter/0.0.1/STTwitter.podspec
<gh_stars>1-10 # # Be sure to run `pod spec lint STTwitter.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # To learn more about the attributes see http://docs.cocoapods.org/specification.html # Pod::Spec.new do |s| s.name = "STTwitter" s.version = "0.0.1" s.summary = "A lightweight Objective-C wrapper for Twitter's REST API 1.1." s.homepage = "https://github.com/nst/STTwitter" s.license = { :type => 'New BSD', :text => <<-LICENSE Copyright (c) 2012 <NAME>. All rights reserved. LICENSE } s.authors = '<NAME>', '<NAME>', 'xnyhps' s.source = { :git => "https://github.com/nst/STTwitter.git", :tag => '0.0.1' } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.source_files = 'STTwitter/*.{h,m}', 'STTwitter/Vendor/*.{h,m}' s.ios.frameworks = 'CoreGraphics', 'Foundation', 'QuartzCore', 'UIKit' s.requires_arc = false end
Marketcircle/Specs
iOS-GTLYouTube/0.0.3/iOS-GTLYouTube.podspec
<reponame>Marketcircle/Specs<filename>iOS-GTLYouTube/0.0.3/iOS-GTLYouTube.podspec # # iOS-GTLYouTube # CocoaPods podspec # Pod::Spec.new do |s| s.platform = :ios, '5.1' s.name = 'iOS-GTLYouTube' s.version = '0.0.3' s.author = { '<NAME>' => '<EMAIL>' } s.summary = 'Auto-generated Google GTL library for accessing YouTube\'s new JSON API.' s.homepage = 'http://github.com/brynbellomy/iOS-GTLYouTube' s.license = { :type => 'WTFPL', :file => 'LICENSE.md' } s.source = { :git => 'https://github.com/brynbellomy/iOS-GTLYouTube.git', :tag => "v#{s.version}" } s.requires_arc = false s.public_header_files = %w[ Services/YouTube/Generated/*.h Utilities/GTLBase64.h Objects/GTLBatchQuery.h Objects/GTLBatchResult.h Objects/GTLDateTime.h GTLDefines.h Objects/GTLErrorObject.h Utilities/GTLFramework.h Utilities/GTLJSONParser.h Objects/GTLObject.h Objects/GTLQuery.h Objects/GTLRuntimeCommon.h Objects/GTLService.h Utilities/GTLTargetNamespace.h Objects/GTLUploadParameters.h Utilities/GTLUtilities.h HTTPFetcher/GTMGatherInputStream.h HTTPFetcher/GTMHTTPFetcher.h HTTPFetcher/GTMHTTPFetcherLogging.h HTTPFetcher/GTMHTTPFetcherService.h HTTPFetcher/GTMHTTPFetchHistory.h HTTPFetcher/GTMHTTPUploadFetcher.h HTTPFetcher/GTMMIMEDocument.h OAuth2/GTMOAuth2Authentication.h OAuth2/GTMOAuth2SignIn.h OAuth2/Touch/GTMOAuth2ViewControllerTouch.h OAuth2/Mac/GTMOAuth2WindowController.h HTTPFetcher/GTMReadMonitorInputStream.h ] # s.source_files = FileList['./{Services/YouTube/Generated/{*.{h,m},GTLYouTubeConstants.m},GTLDefines.h,HTTPFetcher/GTM{GatherInputStream,HTTPFetchHistory,HTTPFetcher,HTTPFetcherLogging,HTTPFetcherService,HTTPUploadFetcher,MIMEDocument,ReadMonitorInputStream}.{h,m},OAuth2/{GTMOAuth2Authentication.{h,m},GTMOAuth2SignIn.{h,m},Touch/GTMOAuth2ViewControllerTouch.{h,m}},Objects/GTL{BatchQuery,BatchResult,DateTime,ErrorObject,Object,Query,RuntimeCommon,Service,UploadParameters}.{h,m},Utilities/GTL{{Base64,Framework,JSONParser,Utilities}.{h,m},TargetNamespace.h}}'] #source_files.resolve #puts '*************** ' #puts source_files.to_a.inspect #puts '*************** ' #s.source_files = source_files s.source_files = %w[ Services/YouTube/Generated/GTLQueryYouTube.h Services/YouTube/Generated/GTLServiceYouTube.h Services/YouTube/Generated/GTLYouTube.h Services/YouTube/Generated/GTLYouTubeActivity.h Services/YouTube/Generated/GTLYouTubeActivityContentDetails.h Services/YouTube/Generated/GTLYouTubeActivityListResponse.h Services/YouTube/Generated/GTLYouTubeActivitySnippet.h Services/YouTube/Generated/GTLYouTubeChannel.h Services/YouTube/Generated/GTLYouTubeChannelContentDetails.h Services/YouTube/Generated/GTLYouTubeChannelListResponse.h Services/YouTube/Generated/GTLYouTubeChannelSnippet.h Services/YouTube/Generated/GTLYouTubeChannelStatistics.h Services/YouTube/Generated/GTLYouTubeChannelStatus.h Services/YouTube/Generated/GTLYouTubeChannelTopicDetails.h Services/YouTube/Generated/GTLYouTubeConstants.h Services/YouTube/Generated/GTLYouTubeGeoPoint.h Services/YouTube/Generated/GTLYouTubeGuideCategory.h Services/YouTube/Generated/GTLYouTubeGuideCategoryListResponse.h Services/YouTube/Generated/GTLYouTubeGuideCategorySnippet.h Services/YouTube/Generated/GTLYouTubePageInfo.h Services/YouTube/Generated/GTLYouTubePlaylist.h Services/YouTube/Generated/GTLYouTubePlaylistContentDetails.h Services/YouTube/Generated/GTLYouTubePlaylistItem.h Services/YouTube/Generated/GTLYouTubePlaylistItemContentDetails.h Services/YouTube/Generated/GTLYouTubePlaylistItemListResponse.h Services/YouTube/Generated/GTLYouTubePlaylistItemSnippet.h Services/YouTube/Generated/GTLYouTubePlaylistListResponse.h Services/YouTube/Generated/GTLYouTubePlaylistPlayer.h Services/YouTube/Generated/GTLYouTubePlaylistSnippet.h Services/YouTube/Generated/GTLYouTubePlaylistStatus.h Services/YouTube/Generated/GTLYouTubeResourceId.h Services/YouTube/Generated/GTLYouTubeSearchListResponse.h Services/YouTube/Generated/GTLYouTubeSearchResult.h Services/YouTube/Generated/GTLYouTubeSearchResultSnippet.h Services/YouTube/Generated/GTLYouTubeSubscription.h Services/YouTube/Generated/GTLYouTubeSubscriptionContentDetails.h Services/YouTube/Generated/GTLYouTubeSubscriptionListResponse.h Services/YouTube/Generated/GTLYouTubeSubscriptionSnippet.h Services/YouTube/Generated/GTLYouTubeThumbnail.h Services/YouTube/Generated/GTLYouTubeVideo.h Services/YouTube/Generated/GTLYouTubeVideoCategory.h Services/YouTube/Generated/GTLYouTubeVideoCategoryListResponse.h Services/YouTube/Generated/GTLYouTubeVideoCategorySnippet.h Services/YouTube/Generated/GTLYouTubeVideoContentDetails.h Services/YouTube/Generated/GTLYouTubeVideoListResponse.h Services/YouTube/Generated/GTLYouTubeVideoPlayer.h Services/YouTube/Generated/GTLYouTubeVideoRecordingDetails.h Services/YouTube/Generated/GTLYouTubeVideoSnippet.h Services/YouTube/Generated/GTLYouTubeVideoStatistics.h Services/YouTube/Generated/GTLYouTubeVideoStatus.h Services/YouTube/Generated/GTLYouTubeVideoTopicDetails.h Services/YouTube/Generated/GTLQueryYouTube.m Services/YouTube/Generated/GTLServiceYouTube.m Services/YouTube/Generated/GTLYouTube_Sources.m Services/YouTube/Generated/GTLYouTubeActivity.m Services/YouTube/Generated/GTLYouTubeActivityContentDetails.m Services/YouTube/Generated/GTLYouTubeActivityListResponse.m Services/YouTube/Generated/GTLYouTubeActivitySnippet.m Services/YouTube/Generated/GTLYouTubeChannel.m Services/YouTube/Generated/GTLYouTubeChannelContentDetails.m Services/YouTube/Generated/GTLYouTubeChannelListResponse.m Services/YouTube/Generated/GTLYouTubeChannelSnippet.m Services/YouTube/Generated/GTLYouTubeChannelStatistics.m Services/YouTube/Generated/GTLYouTubeChannelStatus.m Services/YouTube/Generated/GTLYouTubeChannelTopicDetails.m Services/YouTube/Generated/GTLYouTubeConstants.m Services/YouTube/Generated/GTLYouTubeGeoPoint.m Services/YouTube/Generated/GTLYouTubeGuideCategory.m Services/YouTube/Generated/GTLYouTubeGuideCategoryListResponse.m Services/YouTube/Generated/GTLYouTubeGuideCategorySnippet.m Services/YouTube/Generated/GTLYouTubePageInfo.m Services/YouTube/Generated/GTLYouTubePlaylist.m Services/YouTube/Generated/GTLYouTubePlaylistContentDetails.m Services/YouTube/Generated/GTLYouTubePlaylistItem.m Services/YouTube/Generated/GTLYouTubePlaylistItemContentDetails.m Services/YouTube/Generated/GTLYouTubePlaylistItemListResponse.m Services/YouTube/Generated/GTLYouTubePlaylistItemSnippet.m Services/YouTube/Generated/GTLYouTubePlaylistListResponse.m Services/YouTube/Generated/GTLYouTubePlaylistPlayer.m Services/YouTube/Generated/GTLYouTubePlaylistSnippet.m Services/YouTube/Generated/GTLYouTubePlaylistStatus.m Services/YouTube/Generated/GTLYouTubeResourceId.m Services/YouTube/Generated/GTLYouTubeSearchListResponse.m Services/YouTube/Generated/GTLYouTubeSearchResult.m Services/YouTube/Generated/GTLYouTubeSearchResultSnippet.m Services/YouTube/Generated/GTLYouTubeSubscription.m Services/YouTube/Generated/GTLYouTubeSubscriptionContentDetails.m Services/YouTube/Generated/GTLYouTubeSubscriptionListResponse.m Services/YouTube/Generated/GTLYouTubeSubscriptionSnippet.m Services/YouTube/Generated/GTLYouTubeThumbnail.m Services/YouTube/Generated/GTLYouTubeVideo.m Services/YouTube/Generated/GTLYouTubeVideoCategory.m Services/YouTube/Generated/GTLYouTubeVideoCategoryListResponse.m Services/YouTube/Generated/GTLYouTubeVideoCategorySnippet.m Services/YouTube/Generated/GTLYouTubeVideoContentDetails.m Services/YouTube/Generated/GTLYouTubeVideoListResponse.m Services/YouTube/Generated/GTLYouTubeVideoPlayer.m Services/YouTube/Generated/GTLYouTubeVideoRecordingDetails.m Services/YouTube/Generated/GTLYouTubeVideoSnippet.m Services/YouTube/Generated/GTLYouTubeVideoStatistics.m Services/YouTube/Generated/GTLYouTubeVideoStatus.m Services/YouTube/Generated/GTLYouTubeVideoTopicDetails.m Services/YouTube/Generated/GTLYouTubeConstants.m GTLDefines.h HTTPFetcher/GTMGatherInputStream.h HTTPFetcher/GTMGatherInputStream.m HTTPFetcher/GTMHTTPFetchHistory.h HTTPFetcher/GTMHTTPFetchHistory.m HTTPFetcher/GTMHTTPFetcher.h HTTPFetcher/GTMHTTPFetcher.m HTTPFetcher/GTMHTTPFetcherLogging.h HTTPFetcher/GTMHTTPFetcherLogging.m HTTPFetcher/GTMHTTPFetcherService.h HTTPFetcher/GTMHTTPFetcherService.m HTTPFetcher/GTMHTTPUploadFetcher.h HTTPFetcher/GTMHTTPUploadFetcher.m HTTPFetcher/GTMMIMEDocument.h HTTPFetcher/GTMMIMEDocument.m HTTPFetcher/GTMReadMonitorInputStream.h HTTPFetcher/GTMReadMonitorInputStream.m OAuth2/GTMOAuth2Authentication.h OAuth2/GTMOAuth2Authentication.m OAuth2/GTMOAuth2SignIn.h OAuth2/GTMOAuth2SignIn.m OAuth2/Touch/GTMOAuth2ViewControllerTouch.h OAuth2/Touch/GTMOAuth2ViewControllerTouch.m Objects/GTLBatchQuery.h Objects/GTLBatchQuery.m Objects/GTLBatchResult.h Objects/GTLBatchResult.m Objects/GTLDateTime.h Objects/GTLDateTime.m Objects/GTLErrorObject.h Objects/GTLErrorObject.m Objects/GTLObject.h Objects/GTLObject.m Objects/GTLQuery.h Objects/GTLQuery.m Objects/GTLRuntimeCommon.h Objects/GTLRuntimeCommon.m Objects/GTLService.h Objects/GTLService.m Objects/GTLUploadParameters.h Objects/GTLUploadParameters.m Utilities/GTLBase64.h Utilities/GTLBase64.m Utilities/GTLFramework.h Utilities/GTLFramework.m Utilities/GTLJSONParser.h Utilities/GTLJSONParser.m Utilities/GTLUtilities.h Utilities/GTLUtilities.m Utilities/GTLTargetNamespace.h" ] end
Marketcircle/Specs
DHCCounter/0.0.1/DHCCounter.podspec
<reponame>Marketcircle/Specs # # Be sure to run `pod spec lint DHCCounter.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # To learn more about the attributes see http://docs.cocoapods.org/specification.html # Pod::Spec.new do |s| s.name = "DHCCounter" s.version = "0.0.1" s.summary = "Count Events and get notifications when that count changes, per event." s.homepage = "https://github.com/confidenceJuice/DHCCounter" s.license = 'MIT' s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/confidenceJuice/DHCCounter.git", :tag => "#{s.version}" } s.ios.deployment_target = '4.3' s.osx.deployment_target = '10.6' s.source_files = 'Classes' s.framework = 'Foundation' s.requires_arc = true end
Marketcircle/Specs
KASlideShow/1.0/KASlideShow.podspec
Pod::Spec.new do |s| s.name = 'KASlideShow' s.version = '1.0' s.platform = :ios s.license = {:type =>'Apache V2.0', :file =>'LICENSE'} s.summary = 'Minimal slideshow for iOS. Support manual or automatic slideshow, with fade and slide transitions.' s.homepage = 'http://alexiscreuzot.com/KASlideShow' s.author = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/kirualex/KASlideShow.git', :tag => '1.0'} s.description = 'Minimal slideshow for iOS. Support manual or automatic slideshow, with fade and slide transitions. A delegate mechanism is provided to detect when the slideshow is moving forward or backward.' s.source_files = 'KASlideShow/*.{h,m}' s.requires_arc = true s.framework = 'Foundation' end
Marketcircle/Specs
NNNetwork/0.0.1/NNNetwork.podspec
<filename>NNNetwork/0.0.1/NNNetwork.podspec # Specfile for NNNetwork Pod::Spec.new do |s| s.name = "NNNetwork" s.version = "0.0.1" s.summary = "Networking categories, OAuth and read later clients." s.description = <<-DESC `NNNetwork` is a collection of classes that power networking in Postr. It is built atop `AFNetworking` and it provides categories for networking, OAuth 1.0 utilities and read later integration classes (supports Instapaper, Pocket and Readability). It also includes iOS 6 `UIActivity` providers for these services that can be used in `UIActivityViewController`s. DESC s.homepage = "https://github.com/tomazsh/NNNetwork" s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/tomazsh/NNNetwork.git", :commit => '<PASSWORD>' } s.platform = :ios, '6.0' s.source_files = 'NNNetwork' s.exclude_files = 'Examples' s.resources = "Resources/*" s.requires_arc = true s.dependency 'AFNetworking', '~> 1.3.1' s.dependency 'SSKeychain', '0.1.4' end
Marketcircle/Specs
KANibHelper/0.4/KANibHelper.podspec
Pod::Spec.new do |s| s.name = 'KANibHelper' s.version = '0.4' s.platform = :ios s.license = {:type =>'Apache V2.0', :file =>'LICENSE'} s.summary = 'When you need to have two very distinct interfaces between 3.5 and 4 inches screens.' s.homepage = 'http://alexiscreuzot.com/KANibHelper' s.author = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/kirualex/KANibHelper.git', :tag => '0.4'} s.description = ' Autoresizing masks are not doing the trick? Autolayouts are lacking simplicity and flexibility ? Well then this library is made for you. I believe having separate Nib files for 3.5 and 4 inches screens are the way to go if you want to ease up the layout management process and improve your app maintanability.' s.source_files = 'KANibHelper/*.{h,m}' s.framework = 'Foundation', 'UIKit' end
Marketcircle/Specs
UICustomizeKit/0.0.1/UICustomizeKit.podspec
<filename>UICustomizeKit/0.0.1/UICustomizeKit.podspec Pod::Spec.new do |s| s.name = "UICustomizeKit" s.version = "0.0.1" s.summary = "The UICustomizeKit extends standard UIKit components to make amazing looking controls." s.homepage = "https://github.com/daltoniam/UICustomizeKit" s.license = 'Apache License, Version 2.0' s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/motou/UICustomizeKit.git", :commit => "<PASSWORD>"} s.platform = :ios, '5.0' s.source_files = 'base', 'bootstrap', 'flat' s.requires_arc = true end
Marketcircle/Specs
TICoreDataSync/1.0.2/TICoreDataSync.podspec
<gh_stars>1-10 Pod::Spec.new do |s| s.name = "TICoreDataSync" s.version = "1.0.2" s.summary = "Automatic synchronization for Core Data Apps, between any combination of Mac OS X and iOS." s.homepage = "http://nothirst.github.com/TICoreDataSync" s.license = { :type => 'MIT', :text => <<-LICENSE Copyright (c) 2013 No Thirst Software (http://nothirst.com/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. LICENSE } s.authors = { "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>" } s.ios.deployment_target = '5.1' s.osx.deployment_target = '10.7' s.source = { :git => "https://github.com/nothirst/TICoreDataSync.git", :tag => s.version.to_s, :submodules => true } s.source_files = 'TICoreDataSync/0[1235]*/**/*.{h,m}', 'TICoreDataSync/TICoreDataSync.h', 'TICoreDataSync/04*/*.{h,m}', 'TICoreDataSync/04*/FZACryptor/*.{h,m}', 'TICoreDataSync/04*/SSZipArchive/*.{h,m}', 'TICoreDataSync/04*/SSZipArchive/Objective-Zip/*.{h,m}', 'TICoreDataSync/04*/SSZipArchive/minizip/*.{h,c}', 'TICoreDataSync/06*/{NS,TI}*.{h,m}' s.ios.source_files = 'TICoreDataSync/06*/UI*.{h,m}' s.resources = 'TICoreDataSync/05*/*.{plist,txt}' s.framework = 'CoreData', 'Security', 'SystemConfiguration' s.library = 'z' s.requires_arc = true s.ios.dependency 'Dropbox-iOS-SDK', '~> 1.3.3' s.osx.dependency 'Dropbox-OSX-SDK', '~> 1.3.3' s.preserve_path = 'Submodules', 'TICoreDataSync/03 Internal Data Model/TICDSSyncChange.xcdatamodel', 'TICoreDataSync/03 Internal Data Model/TICDSSyncChangeSet.xcdatamodeld' s.xcconfig = { 'HEADER_SEARCH_PATHS' => '"$(PODS_ROOT)/TICoreDataSync/**"', 'OTHER_LDFLAGS' => '-ObjC' } s.prefix_header_contents = <<-EOS #ifdef __OBJC__ #import <CoreData/CoreData.h> #endif EOS s.post_install do |library_representation| config = s.config pod_root = config.project_pods_root + 'TICoreDataSync/' ['TICDSSyncChange.xcdatamodel', 'TICDSSyncChangeSet.xcdatamodeld'].each do |datamodelfile| datamodel = File.basename(datamodelfile, ".*") momext = File.extname(datamodelfile) == '.xcdatamodel' ? 'mom' : 'momd' momd_relative = "TICoreDataSync/03 Internal Data Model/#{datamodel}.#{momext}" momd_full = pod_root + momd_relative unless momd_full.exist? puts "\nCompiling #{datamodelfile} Core Data model\n".yellow if config.verbose? model = pod_root + "TICoreDataSync/03 Internal Data Model/#{datamodelfile}" command = "xcrun momc '#{model}' '#{momd_full}'" command << " 2>&1 > /dev/null" unless config.verbose? unless system(command) raise ::Pod::Informative, "Failed to compile #{datamodelfile} Core Data model" end end File.open(library_representation.copy_resources_script_path, 'a') do |file| file.puts "install_resource 'TICoreDataSync/#{momd_relative}'" end end end end
Marketcircle/Specs
PlaynomicsSDK/8/PlaynomicsSDK.podspec
<reponame>Marketcircle/Specs Pod::Spec.new do |s| s.name = 'PlaynomicsSDK' s.version = '8' s.license = { :type => 'Commercial', :text => 'See http://www.playnomics.com/platformpolicy/' } s.summary = 'Playnomics PlayRM iOS SDK.' s.homepage = 'http://www.playnomics.com' s.author = { 'Playnomics' => '<EMAIL>' } s.source = { :git => 'https://github.com/playnomics/ios-sdk.git', :tag => 'v8' } s.platform = :ios s.source_files = 'build/*.h' s.preserve_paths = 'build/libplaynomics.a' s.library = 'playnomics' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/PlaynomicsSDK/build"' } end
Marketcircle/Specs
nv-ios-http-status/0.0.1/nv-ios-http-status.podspec
# # Be sure to run `pod spec lint nv-ios-http-status.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # To learn more about the attributes see http://docs.cocoapods.org/specification.html # Pod::Spec.new do |s| s.name = "nv-ios-http-status" s.version = "0.0.1" s.summary = "List of HTTP status codes as typedef enum. kHTTPStatusCodeOK, kHTTPStatusCodeNotFound, and so on.." s.homepage = "https://github.com/TakahikoKawasaki/nv-ios-http-status" s.license = { :type => 'Apache' } s.author = '<NAME>' s.source = { :git => "https://github.com/TakahikoKawasaki/nv-ios-http-status.git", :commit => "<PASSWORD>" } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.source_files = 'nv-ios-http-status/*.{h,m}' end
Marketcircle/Specs
SqliteFTS/0.0.1/SqliteFTS.podspec
<gh_stars>0 Pod::Spec.new do |s| s.name = "SqliteFTS" s.version = "0.0.1" s.summary = "SQLiteFTS is a static library providing a rebuild SQLite database from source code to add FTS support." s.description = <<-DESC ## What's this project for? This project rebuild the SQLite database from source code, and provide a static library for other projects to link with. This project added **FTS** support for SQLite. ## Why create such a project while iOS already provide sqlite library? Because the SQLite library provided by Apple does not include FTS module. Thus, you can not use powerful SQLite FTS feature. ## How to use FTS with SQLite? Visit SQLite's [official FTS page](http://www.sqlite.org/fts3.html) for more detailed information. DESC s.homepage = 'https://github.com/ebosveld/sqliteFTS' s.license = { :type => 'Apache License 2.0', :text => <<-LICENSE SQLite is distributed in [Public Domain](http://en.wikipedia.org/wiki/Public_Domain), and does not require a license. This convient project is distributed in [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html), which means you can use it for open source/commercial software. LICENSE } s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/ebosveld/sqliteFTS.git", :tag => "v#{s.version}" } s.platform = :ios, '5.0' s.source_files = 'sqliteFTS', 'sqliteFTS/**/*.{h,c}' end
Marketcircle/Specs
NRGramKit/1.0/NRGramKit.podspec
# # Be sure to run `pod spec lint NRGramKit.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # # To learn more about the attributes see http://docs.cocoapods.org/specification.html # Pod::Spec.new do |s| s.name = "NRGramKit" s.version = "1.0" s.summary = "A simple library to access all the functions of the Instagram API." s.homepage = "https://github.com/NextRoot/NRGramKit" s.license = { :type => 'MIT', :file => 'LICENSE.txt' } s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/NextRoot/NRGramKit.git", :tag=>s.version.to_s } s.platform = :ios, '5.0' s.source_files = 'NRGramKit/*.{h,m,pch}','NRGramKit/Model/*.{h,m}' #s.exclude_files = 'NRGramKit/*.pch' s.prefix_header_file = 'NRGramKit/NRGramKit-Prefix.pch' s.frameworks = 'SystemConfiguration', 'CFNetwork','Security' # If this Pod uses ARC, specify it like so. # s.requires_arc = true s.dependency 'MKNetworkKit', '~> 0.87' s.dependency 'JSONKit','~>1.4' end
Marketcircle/Specs
flojack-ios/0.0.1/flojack-ios.podspec
<gh_stars>1-10 Pod::Spec.new do |s| s.name = "flojack-ios" s.version = "0.0.1" s.summary = "iOS static lib for FloJack NFC reader/writer." s.homepage = "https://github.com/flomio/flojack-ios" s.license = 'Apache v2' s.author = { "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>" } s.source = { :git => 'https://github.com/flomio/flojack-ios.git', :commit => '<PASSWORD>'} s.platform = :ios s.source_files = 'FloJack', 'FloJack/**/*.{h,m,mm}' s.frameworks = 'AudioToolbox', 'AVFoundation', 'CoreAudio', 'CoreData', 'CoreGraphics', 'Foundation', 'MediaPlayer', 'MobileCoreServices', 'QuartzCore', 'SenTestingKit' s.xcconfig = { 'GCC_INPUT_FILETYPE' => 'sourcecode.cpp.objcpp', 'OTHER_LDFLAGS' => '-all_load'} s.requires_arc = true end
Marketcircle/Specs
MRCEnumerable/0.1.1/MRCEnumerable.podspec
<gh_stars>1-10 # # Be sure to run `pod spec lint MRCEnumerable.podspec' to ensure this is a # valid spec and remove all comments before submitting the spec. # Pod::Spec.new do |s| s.name = "MRCEnumerable" s.version = "0.1.1" s.summary = "Collection of Ruby Enumerable style methods on common collection classes." s.homepage = "https://github.com/crafterm/MRCEnumerable" s.license = { :type => 'MIT', :file => 'MIT-LICENSE' } s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/crafterm/MRCEnumerable.git", :tag => "0.1.1" } s.ios.deployment_target = '5.0' s.osx.deployment_target = '10.7' s.source_files = 'Classes' end
Marketcircle/Specs
GoogleConversionTracking/1.2.0/GoogleConversionTracking.podspec
Pod::Spec.new do |s| s.name = 'GoogleConversionTracking' s.version = '1.2.0' s.summary = 'Google Conversion Tracking SDK for iOS.' s.description = 'If you\'d like to know which of your keywords best leads to clicks and conversions, such as sales, AdWords Conversion Tracking can help you.' s.homepage = 'https://support.google.com/adwords/answer/1722054?hl=en' s.license = { :type => 'Copyright', :text => <<-LICENSE Copyright (c) 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. LICENSE } s.author = 'Google Inc.' s.source = { :http => 'http://dl.google.com/googleadmobadssdk/googleconversiontrackingsdkios.zip', :flatten => true } s.platform = :ios s.preserve_paths = 'libGoogleConversionTracking.a' s.source_files = '*.h' s.library = 'GoogleConversionTracking' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/GoogleConversionTracking"' } end