Skip to content

Instantly share code, notes, and snippets.

@Schwusch
Last active June 20, 2021 22:04
Show Gist options
  • Save Schwusch/60510ae0ae3d4eb2a6254d0fbd216fc3 to your computer and use it in GitHub Desktop.
Save Schwusch/60510ae0ae3d4eb2a6254d0fbd216fc3 to your computer and use it in GitHub Desktop.
Simple experiment to combine package:highlight with package:super_editor in Flutter
import 'package:super_editor/super_editor.dart';
import 'package:highlight/highlight.dart' show highlight;
import 'package:flutter_highlight/themes/github.dart';
Widget superEditorHighlighter(String code, String language, TextStyle defaultStyle) {
var result = highlight.parse(code, language: language);
var charCount = 0;
final myDoc = MutableDocument(nodes: [
ParagraphNode(
id: DocumentEditor.createNodeId(),
text: AttributedText(
text: code,
spans: AttributedSpans(
attributions: result.nodes
.map(
(e) {
final start = charCount;
charCount += e.value?.length ?? e.children.first.value.length;
return [
SpanMarker(
attribution: NamedAttribution(e.className),
offset: start,
markerType: SpanMarkerType.start,
),
SpanMarker(
attribution: NamedAttribution(e.className),
offset: charCount - 1,
markerType: SpanMarkerType.end,
)
];
},
)
.expand((element) => element)
.toList(),
),
),
)
]);
return SuperEditor.custom(
maxWidth: double.infinity,
editor: DocumentEditor(document: myDoc),
componentBuilders: defaultComponentBuilders,
selectionStyle: defaultSelectionStyle,
keyboardActions: defaultKeyboardActions,
textStyleBuilder: (attributions) {
if (attributions.isNotEmpty) {
final attribution = attributions.first as NamedAttribution;
return githubTheme[attribution.id];
}
return defaultStyle;
},
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment