Fork de wikipp, le moteur de wiki en c++, basé sur cppcms. Le fork ajoute la langue française
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

markdown.cpp 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <vector>
  4. #include <stdexcept>
  5. #include "markdown.h"
  6. extern "C" {
  7. #include <mkdio.h>
  8. }
  9. std::string markdown_to_html(char const *str,int len,int flags)
  10. {
  11. /// It is safe to const cast as mkd_string does not
  12. /// alter original string
  13. MMIOT *doc = mkd_string(const_cast<char *>(str),len,flags);
  14. if(!doc) {
  15. throw std::runtime_error("Failed to read document");
  16. }
  17. mkd_compile(doc,flags);
  18. std::string result;
  19. result.reserve(len);
  20. char *content_ptr = 0;
  21. int content_size = 0;
  22. char *toc_ptr = 0;
  23. int toc_size = 0;
  24. content_size = mkd_document(doc,&content_ptr);
  25. if(flags & mkd::toc) {
  26. toc_size = mkd_toc(doc,&toc_ptr);
  27. result.assign(toc_ptr,toc_size);
  28. }
  29. result.append(content_ptr,content_size);
  30. free(toc_ptr);
  31. mkd_cleanup(doc);
  32. return result;
  33. }
  34. std::string markdown_format_for_highlighting(std::string const &input,std::string const &html_class)
  35. {
  36. enum { part_a , part_b } state = part_a;
  37. std::string repla = "<pre name=\"code\" class=\"" + html_class + "\">";
  38. std::string replb = "</pre>";
  39. std::string origa="<pre><code>";
  40. std::string origb="</code></pre>";
  41. std::string result;
  42. result.reserve(input.size());
  43. size_t pos = 0;
  44. while(pos < input.size()) {
  45. std::string const &orig = state == part_a ? origa : origb;
  46. std::string const &repl = state == part_a ? repla : replb;
  47. size_t next = input.find(orig,pos);
  48. if(next == std::string::npos)
  49. next = input.size();
  50. result.append(input.data() + pos, next - pos);
  51. if(next < input.size()) {
  52. result.append(repl);
  53. pos = next + orig.size();
  54. if(state == part_a)
  55. state = part_b;
  56. else
  57. state = part_a;
  58. }
  59. else {
  60. pos = next;
  61. }
  62. }
  63. return result;
  64. }