syntaxhighlighter.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include "syntaxhighlighter.h"
  2. #include <set>
  3. SyntaxHighlighter::SyntaxHighlighter(QTextDocument *parent) :
  4. QSyntaxHighlighter(parent)
  5. {
  6. levelColor.push_back(QTextCharFormat());
  7. levelColor.push_back(QTextCharFormat());
  8. levelColor.push_back(QTextCharFormat());
  9. levelColor.push_back(QTextCharFormat());
  10. levelColor.push_back(QTextCharFormat());
  11. levelColor.push_back(QTextCharFormat());
  12. levelColor[0].setForeground(Qt::blue);
  13. levelColor[1].setForeground(Qt::red);
  14. levelColor[2].setForeground(Qt::darkGreen);
  15. levelColor[3].setForeground(Qt::darkRed);
  16. levelColor[4].setForeground(Qt::darkYellow);
  17. levelColor[5].setForeground(Qt::green);
  18. for (auto& tcf : levelColor) {
  19. tcf.setFontWeight(99);
  20. }
  21. comment.setForeground(Qt::gray);
  22. }
  23. void SyntaxHighlighter::highlightBlock(const QString &text)
  24. {
  25. struct FormatState {
  26. QTextCharFormat* currentFormat;
  27. int startIndex = 0;
  28. int length = 0;
  29. SyntaxHighlighter* sh;
  30. FormatState(SyntaxHighlighter* sh) : currentFormat{ &sh->comment }, sh{ sh } {}
  31. void upateFormat(int len, QTextCharFormat* format) {
  32. if (format == currentFormat) {
  33. length++;
  34. }
  35. else {
  36. sh->setFormat(startIndex, length, *currentFormat);
  37. currentFormat = format;
  38. startIndex += length;
  39. length = 1;
  40. }
  41. }
  42. void finish() {
  43. sh->setFormat(startIndex, length, *currentFormat);
  44. }
  45. };
  46. int level = previousBlockState();
  47. if (level < 0) level = 0;
  48. FormatState fs(this);
  49. for (int i = 0; i < text.length(); i++) {
  50. auto& c = text[i];
  51. if (c == '[') {
  52. level++;
  53. }
  54. if (isBfChar(c)) {
  55. fs.upateFormat(1, &levelColor[level % levelColor.size()]);
  56. }
  57. else {
  58. fs.upateFormat(1, &comment);
  59. }
  60. if (c == ']') {
  61. level--;
  62. }
  63. /*if (c == '[') {
  64. level++;
  65. }
  66. if (isBfChar(c)) {
  67. setFormat(i, 1, levelColor[level % levelColor.size()]);
  68. }
  69. else {
  70. setFormat(i, 1, comment);
  71. }
  72. if (c == ']') {
  73. level--;
  74. }*/
  75. }
  76. fs.finish();
  77. setCurrentBlockState(level);
  78. }
  79. bool SyntaxHighlighter::isBfChar(const QChar& c)
  80. {
  81. static const std::set<QChar> x{'+', '-', '<', '>', ',', '.', '[', ']'};
  82. return x.find(c) != x.end();
  83. }