hgmarkdownhighlighter.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* PEG Markdown Highlight
  2. * Copyright 2011-2016 Ali Rantakari -- http://hasseg.org
  3. * Licensed under the GPL2+ and MIT licenses (see LICENSE for more info).
  4. *
  5. * highlighter.h
  6. *
  7. * Qt 4.7 example for highlighting a rich text widget.
  8. */
  9. #ifndef HGMARKDOWNHIGHLIGHTER_H
  10. #define HGMARKDOWNHIGHLIGHTER_H
  11. #include <QTextCharFormat>
  12. #include <QSyntaxHighlighter>
  13. #include <QAtomicInt>
  14. extern "C" {
  15. #include "utils/peg-highlight/pmh_parser.h"
  16. }
  17. QT_BEGIN_NAMESPACE
  18. class QTextDocument;
  19. QT_END_NAMESPACE
  20. struct HighlightingStyle
  21. {
  22. pmh_element_type type;
  23. QTextCharFormat format;
  24. };
  25. // One continuous region for a certain markdown highlight style
  26. // within a QTextBlock.
  27. // Pay attention to the change of HighlightingStyles[]
  28. struct HLUnit
  29. {
  30. // Highlight offset @start and @length with style HighlightingStyles[styleIndex]
  31. // within a QTextBlock
  32. unsigned long start;
  33. unsigned long length;
  34. unsigned int styleIndex;
  35. };
  36. class HGMarkdownHighlighter : public QSyntaxHighlighter
  37. {
  38. Q_OBJECT
  39. public:
  40. HGMarkdownHighlighter(const QVector<HighlightingStyle> &styles, int waitInterval,
  41. QTextDocument *parent = 0);
  42. ~HGMarkdownHighlighter();
  43. void setStyles(const QVector<HighlightingStyle> &styles);
  44. protected:
  45. void highlightBlock(const QString &text) Q_DECL_OVERRIDE;
  46. private slots:
  47. void handleContentChange(int position, int charsRemoved, int charsAdded);
  48. void timerTimeout();
  49. private:
  50. QRegExp codeBlockStartExp;
  51. QRegExp codeBlockEndExp;
  52. QTextCharFormat codeBlockFormat;
  53. QTextDocument *document;
  54. QVector<HighlightingStyle> highlightingStyles;
  55. QVector<QVector<HLUnit> > blockHighlights;
  56. QAtomicInt parsing;
  57. QTimer *timer;
  58. int waitInterval;
  59. char *content;
  60. int capacity;
  61. pmh_element **result;
  62. static const int initCapacity;
  63. void resizeBuffer(int newCap);
  64. void highlightCodeBlock(const QString &text);
  65. void parse();
  66. void parseInternal();
  67. void initBlockHighlightFromResult(int nrBlocks);
  68. void initBlockHighlihgtOne(unsigned long pos, unsigned long end,
  69. int styleIndex);
  70. };
  71. #endif