xml.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* markdown: a C implementation of John Gruber's Markdown markup language.
  2. *
  3. * Copyright (C) 2007 David L Parsons.
  4. * The redistribution terms are provided in the COPYRIGHT file that must
  5. * be distributed with this source code.
  6. */
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <stdarg.h>
  10. #include <stdlib.h>
  11. #include <time.h>
  12. #include <ctype.h>
  13. #include "config.h"
  14. #include "cstring.h"
  15. #include "markdown.h"
  16. #include "amalloc.h"
  17. /* return the xml version of a character
  18. */
  19. static char *
  20. mkd_xmlchar(unsigned char c)
  21. {
  22. switch (c) {
  23. case '<': return "&lt;";
  24. case '>': return "&gt;";
  25. case '&': return "&amp;";
  26. case '"': return "&quot;";
  27. case '\'': return "&apos;";
  28. default: if ( isascii(c) || (c & 0x80) )
  29. return 0;
  30. return "";
  31. }
  32. }
  33. /* write output in XML format
  34. */
  35. int
  36. mkd_generatexml(char *p, int size, FILE *out)
  37. {
  38. unsigned char c;
  39. char *entity;
  40. while ( size-- > 0 ) {
  41. c = *p++;
  42. if ( entity = mkd_xmlchar(c) )
  43. DO_OR_DIE( fputs(entity, out) );
  44. else
  45. DO_OR_DIE( fputc(c, out) );
  46. }
  47. return 0;
  48. }
  49. /* build a xml'ed version of a string
  50. */
  51. int
  52. mkd_xml(char *p, int size, char **res)
  53. {
  54. unsigned char c;
  55. char *entity;
  56. Cstring f;
  57. CREATE(f);
  58. RESERVE(f, 100);
  59. while ( size-- > 0 ) {
  60. c = *p++;
  61. if ( entity = mkd_xmlchar(c) )
  62. Cswrite(&f, entity, strlen(entity));
  63. else
  64. Csputc(c, &f);
  65. }
  66. /* null terminate, strdup() into a free()able memory block,
  67. * and return the size of everything except the null terminator
  68. */
  69. EXPAND(f) = 0;
  70. *res = strdup(T(f));
  71. return S(f)-1;
  72. }