Skip to content

Feature Request: Ability to initialise lazily and detect if language is already initalised #19

@yahya-uddin

Description

@yahya-uddin

Requirements

  • I want to initialise the highlighter language when it is required
  • I do not want re-load something that is already loaded

Problem

There is no way to detect if the langauge is already initalised. Also re-initalising unfortunatley re-loads the files, even when already initialised.

Solution

Currently the initialise method looks like:

 static Future<void> initialize(List<String> languages) async {
    for (var language in languages) {
      var json = await rootBundle.loadString(
        'packages/syntax_highlight/grammars/$language.json',
      );
      _cache[language] = Grammar.fromJson(jsonDecode(json));
    }
  }

This can be adjusted so it does not replace already loaded languages:

  static Future<void> initialize(List<String> languages, {bool forceReplace = false}) async {
    for (var language in languages) {
      if (forceReplace || !_cache.containsKey(language) {
         var json = await rootBundle.loadString(
           'packages/syntax_highlight/grammars/$language.json',
         );
         _cache[language] = Grammar.fromJson(jsonDecode(json));
      }
    }
  }

if forceReplace = true, then there will be no breaking changes.
If it is false this will be a minor breaking change.

We could optionally also add some utility methods like:

static bool isLanguageInitalised(String name) {
    return _cache.containsKey(name);
}

// Slightly different to addLanguage
static Future<void> loadLanguage(String name, String language) {
   var json = await rootBundle.loadString(
       'packages/syntax_highlight/grammars/$language.json',
    );
    _cache.putIfAbsent(name, () => Grammar.fromJson(jsonDecode(json)));
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions