aboutsummaryrefslogtreecommitdiff
path: root/commonmark.rb
blob: 06366c555394376e5f906cd75b7ef2ed3c22cb1f (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. attach_function :cmark_free_nodes, [:node], :void
  12. attach_function :cmark_node_unlink, [:node], :void
  13. attach_function :cmark_markdown_to_html, [:string, :int], :string
  14. attach_function :cmark_parse_document, [:string, :int], :node
  15. attach_function :cmark_node_first_child, [:node], :node
  16. attach_function :cmark_node_parent, [:node], :node
  17. attach_function :cmark_node_next, [:node], :node
  18. attach_function :cmark_node_previous, [:node], :node
  19. attach_function :cmark_node_get_type, [:node], :node_type
  20. attach_function :cmark_node_get_string_content, [:node], :string
  21. class Node
  22. attr_accessor :type, :children, :string_content
  23. def initialize(pointer)
  24. if pointer.null?
  25. return nil
  26. end
  27. @pointer = pointer
  28. @type = CMark::cmark_node_get_type(pointer)
  29. @children = []
  30. first_child = CMark::cmark_node_first_child(pointer)
  31. b = first_child
  32. while !b.null?
  33. @children << Node.new(b)
  34. b = CMark::cmark_node_next(b)
  35. end
  36. @string_content = CMark::cmark_node_get_string_content(pointer)
  37. # Free?
  38. end
  39. def print
  40. printf("%s\n", self.type)
  41. if self.string_content
  42. printf("'%s'\n", self.string_content)
  43. end
  44. for child in self.children do
  45. child.print
  46. end
  47. end
  48. def self.from_markdown(s)
  49. len = s.bytes.length
  50. Node.new(CMark::cmark_parse_document(s, len))
  51. end
  52. end
  53. end
  54. doc = CMark::Node.from_markdown(STDIN.read())
  55. doc.print
  56. # def markdown_to_html(s)
  57. # len = s.bytes.length
  58. # CMark::cmark_markdown_to_html(s, len)
  59. # end
  60. # print markdown_to_html(STDIN.read())