aboutsummaryrefslogtreecommitdiff
path: root/commonmark.rb
blob: 0d7fa0ee8e05410d98c9be6d73f6635d9e9e4628 (plain)
  1. require 'ffi'
  2. module CMark
  3. extend FFI::Library
  4. ffi_lib ['libcmark', 'cmark']
  5. typedef :pointer, :node
  6. enum :node_type, [:document, :blockquote, :list, :list_item,
  7. :fenced_code, :indented_code, :html, :paragraph,
  8. :atx_header, :setext_header, :hrule, :reference_def,
  9. :str, :softbreak, :linebreak, :code, :inline_html,
  10. :emph, :strong, :link, :image]
  11. enum :node_type, []
  12. attach_function :cmark_markdown_to_html, [:string, :int], :string
  13. attach_function :cmark_parse_document, [:string, :int], :node
  14. attach_function :cmark_node_first_child, [:node], :node
  15. attach_function :cmark_node_next, [:node], :node
  16. attach_function :cmark_node_get_type, [:node], :node_type
  17. end
  18. def pointer_to_block(pointer)
  19. if pointer.null?
  20. raise NullPointer
  21. else
  22. node_type = CMark::cmark_node_get_type(pointer)
  23. if node_type == 0 # document
  24. children = []
  25. b = CMark::cmark_node_first_child(pointer)
  26. while !b.null?
  27. children << pointer_to_block(b)
  28. b = CMark::cmark_node_next(b)
  29. end
  30. return Document.new(children)
  31. elsif node_type == 7 # paragraph
  32. return Paragraph.new("TODO")
  33. else
  34. raise UnknownNodeType, node_type
  35. end
  36. end
  37. end
  38. class Block
  39. def initialize
  40. end
  41. end
  42. class Document < Block
  43. attr_accessor :children
  44. def initialize(children)
  45. @children = children
  46. end
  47. end
  48. class Paragraph < Block
  49. def initialize(inlines)
  50. @contents = "inlines" # TODO
  51. end
  52. def to_html
  53. "<p>" + @contents + "</p>"
  54. end
  55. end
  56. class Inline
  57. end
  58. def parse_markdown(s)
  59. len = s.bytes.length
  60. pointer_to_block(CMark::cmark_parse_document(s, len))
  61. end
  62. def markdown_to_html(s)
  63. len = s.bytes.length
  64. CMark::cmark_markdown_to_html(s, len)
  65. end
  66. doc = parse_markdown(STDIN.read())
  67. doc.children.each do |b|
  68. print(b)
  69. end
  70. # print markdown_to_html(STDIN.read())