syntax_highlighter.dart 9.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'package:string_scanner/string_scanner.dart';

class SyntaxHighlighterStyle {
  SyntaxHighlighterStyle({
    this.baseStyle,
    this.numberStyle,
    this.commentStyle,
    this.keywordStyle,
    this.stringStyle,
    this.punctuationStyle,
    this.classStyle,
    this.constantStyle
  });

20
  static SyntaxHighlighterStyle lightThemeStyle() {
21
    return new SyntaxHighlighterStyle(
22 23 24 25 26 27 28 29
      baseStyle: const TextStyle(color: Color(0xFF000000)),
      numberStyle: const TextStyle(color: Color(0xFF1565C0)),
      commentStyle: const TextStyle(color: Color(0xFF9E9E9E)),
      keywordStyle: const TextStyle(color: Color(0xFF9C27B0)),
      stringStyle: const TextStyle(color: Color(0xFF43A047)),
      punctuationStyle: const TextStyle(color: Color(0xFF000000)),
      classStyle: const TextStyle(color: Color(0xFF512DA8)),
      constantStyle: const TextStyle(color: Color(0xFF795548))
30 31 32
    );
  }

33 34
  static SyntaxHighlighterStyle darkThemeStyle() {
    return new SyntaxHighlighterStyle(
35 36 37 38 39 40 41 42
      baseStyle: const TextStyle(color: Color(0xFFFFFFFF)),
      numberStyle: const TextStyle(color: Color(0xFF1565C0)),
      commentStyle: const TextStyle(color: Color(0xFF9E9E9E)),
      keywordStyle: const TextStyle(color: Color(0xFF80CBC4)),
      stringStyle: const TextStyle(color: Color(0xFF009688)),
      punctuationStyle: const TextStyle(color: Color(0xFFFFFFFF)),
      classStyle: const TextStyle(color: Color(0xFF009688)),
      constantStyle: const TextStyle(color: Color(0xFF795548))
43 44 45
    );
  }

46 47 48 49 50 51 52 53 54 55
  final TextStyle baseStyle;
  final TextStyle numberStyle;
  final TextStyle commentStyle;
  final TextStyle keywordStyle;
  final TextStyle stringStyle;
  final TextStyle punctuationStyle;
  final TextStyle classStyle;
  final TextStyle constantStyle;
}

pq's avatar
pq committed
56
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
57 58 59 60 61 62
  TextSpan format(String src);
}

class DartSyntaxHighlighter extends SyntaxHighlighter {
  DartSyntaxHighlighter([this._style]) {
    _spans = <_HighlightSpan>[];
63
    _style ??= SyntaxHighlighterStyle.darkThemeStyle();
64 65 66 67
  }

  SyntaxHighlighterStyle _style;

68
  static const List<String> _keywords = <String>[
69 70 71 72 73 74 75 76 77
    'abstract', 'as', 'assert', 'async', 'await', 'break', 'case', 'catch',
    'class', 'const', 'continue', 'default', 'deferred', 'do', 'dynamic', 'else',
    'enum', 'export', 'external', 'extends', 'factory', 'false', 'final',
    'finally', 'for', 'get', 'if', 'implements', 'import', 'in', 'is', 'library',
    'new', 'null', 'operator', 'part', 'rethrow', 'return', 'set', 'static',
    'super', 'switch', 'sync', 'this', 'throw', 'true', 'try', 'typedef', 'var',
    'void', 'while', 'with', 'yield'
  ];

78
  static const List<String> _builtInTypes = <String>[
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    'int', 'double', 'num', 'bool'
  ];

  String _src;
  StringScanner _scanner;

  List<_HighlightSpan> _spans;

  @override
  TextSpan format(String src) {
    _src = src;
    _scanner = new StringScanner(_src);

    if (_generateSpans()) {
      // Successfully parsed the code
94
      final List<TextSpan> formattedText = <TextSpan>[];
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
      int currentPosition = 0;

      for (_HighlightSpan span in _spans) {
        if (currentPosition != span.start)
          formattedText.add(new TextSpan(text: _src.substring(currentPosition, span.start)));

        formattedText.add(new TextSpan(style: span.textStyle(_style), text: span.textForSpan(_src)));

        currentPosition = span.end;
      }

      if (currentPosition != _src.length)
        formattedText.add(new TextSpan(text: _src.substring(currentPosition, _src.length)));

      return new TextSpan(style: _style.baseStyle, children: formattedText);
    } else {
      // Parsing failed, return with only basic formatting
112
      return new TextSpan(style: _style.baseStyle, text: src);
113 114 115 116 117 118
    }
  }

  bool _generateSpans() {
    int lastLoopPosition = _scanner.position;

119
    while (!_scanner.isDone) {
120
      // Skip White space
121
      _scanner.scan(new RegExp(r'\s+'));
122 123

      // Block comments
124
      if (_scanner.scan(new RegExp(r'/\*(.|\n)*\*/'))) {
125 126 127 128 129 130 131 132 133
        _spans.add(new _HighlightSpan(
          _HighlightType.comment,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Line comments
134
      if (_scanner.scan('//')) {
135
        final int startComment = _scanner.lastMatch.start;
136 137 138

        bool eof = false;
        int endComment;
139
        if (_scanner.scan(new RegExp(r'.*\n'))) {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
          endComment = _scanner.lastMatch.end - 1;
        } else {
          eof = true;
          endComment = _src.length;
        }

        _spans.add(new _HighlightSpan(
          _HighlightType.comment,
          startComment,
          endComment
        ));

        if (eof)
          break;

        continue;
      }

      // Raw r"String"
      if (_scanner.scan(new RegExp(r'r".*"'))) {
        _spans.add(new _HighlightSpan(
          _HighlightType.string,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Raw r'String'
      if (_scanner.scan(new RegExp(r"r'.*'"))) {
        _spans.add(new _HighlightSpan(
          _HighlightType.string,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Multiline """String"""
      if (_scanner.scan(new RegExp(r'"""(?:[^"\\]|\\(.|\n))*"""'))) {
        _spans.add(new _HighlightSpan(
          _HighlightType.string,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Multiline '''String'''
      if (_scanner.scan(new RegExp(r"'''(?:[^'\\]|\\(.|\n))*'''"))) {
        _spans.add(new _HighlightSpan(
          _HighlightType.string,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // "String"
      if (_scanner.scan(new RegExp(r'"(?:[^"\\]|\\.)*"'))) {
        _spans.add(new _HighlightSpan(
          _HighlightType.string,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // 'String'
      if (_scanner.scan(new RegExp(r"'(?:[^'\\]|\\.)*'"))) {
        _spans.add(new _HighlightSpan(
          _HighlightType.string,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Double
219
      if (_scanner.scan(new RegExp(r'\d+\.\d+'))) {
220 221 222 223 224 225 226 227 228
        _spans.add(new _HighlightSpan(
          _HighlightType.number,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Integer
229
      if (_scanner.scan(new RegExp(r'\d+'))) {
230 231 232 233 234 235 236 237 238
        _spans.add(new _HighlightSpan(
          _HighlightType.number,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end)
        );
        continue;
      }

      // Punctuation
239
      if (_scanner.scan(new RegExp(r'[\[\]{}().!=<>&\|\?\+\-\*/%\^~;:,]'))) {
240 241 242 243 244 245 246 247
        _spans.add(new _HighlightSpan(
          _HighlightType.punctuation,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

248
      // Meta data
249
      if (_scanner.scan(new RegExp(r'@\w+'))) {
250 251 252 253 254 255 256 257 258
        _spans.add(new _HighlightSpan(
          _HighlightType.keyword,
          _scanner.lastMatch.start,
          _scanner.lastMatch.end
        ));
        continue;
      }

      // Words
259
      if (_scanner.scan(new RegExp(r'\w+'))) {
260 261 262
        _HighlightType type;

        String word = _scanner.lastMatch[0];
263
        if (word.startsWith('_'))
264 265
          word = word.substring(1);

266
        if (_keywords.contains(word))
267
          type = _HighlightType.keyword;
268
        else if (_builtInTypes.contains(word))
269 270 271
          type = _HighlightType.keyword;
        else if (_firstLetterIsUpperCase(word))
          type = _HighlightType.klass;
272
        else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1)))
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
          type = _HighlightType.constant;

        if (type != null) {
          _spans.add(new _HighlightSpan(
            type,
            _scanner.lastMatch.start,
            _scanner.lastMatch.end
          ));
        }
      }

      // Check if this loop did anything
      if (lastLoopPosition == _scanner.position) {
        // Failed to parse this file, abort gracefully
        return false;
      }
      lastLoopPosition = _scanner.position;
    }

    _simplify();
    return true;
  }

  void _simplify() {
297
    for (int i = _spans.length - 2; i >= 0; i -= 1) {
298 299 300 301 302 303 304 305 306 307 308 309
      if (_spans[i].type == _spans[i + 1].type && _spans[i].end == _spans[i + 1].start) {
        _spans[i] = new _HighlightSpan(
          _spans[i].type,
          _spans[i].start,
          _spans[i + 1].end
        );
        _spans.removeAt(i + 1);
      }
    }
  }

  bool _firstLetterIsUpperCase(String str) {
310
    if (str.isNotEmpty) {
311
      final String first = str.substring(0, 1);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
      return first == first.toUpperCase();
    }
    return false;
  }
}

enum _HighlightType {
  number,
  comment,
  keyword,
  string,
  punctuation,
  klass,
  constant
}

class _HighlightSpan {
  _HighlightSpan(this.type, this.start, this.end);
  final _HighlightType type;
  final int start;
  final int end;

  String textForSpan(String src) {
    return src.substring(start, end);
  }

  TextStyle textStyle(SyntaxHighlighterStyle style) {
    if (type == _HighlightType.number)
      return style.numberStyle;
    else if (type == _HighlightType.comment)
      return style.commentStyle;
    else if (type == _HighlightType.keyword)
      return style.keywordStyle;
    else if (type == _HighlightType.string)
      return style.stringStyle;
    else if (type == _HighlightType.punctuation)
      return style.punctuationStyle;
    else if (type == _HighlightType.klass)
      return style.classStyle;
    else if (type == _HighlightType.constant)
      return style.constantStyle;
    else
      return style.baseStyle;
  }
}