### Example Code Block Source: https://github.com/no-context/moo/blob/main/_autodocs/INDEX.md Demonstrates a typical code block used for examples in the documentation. ```markdown **Source:** `moo.js:302` ``` -------------------------------- ### Block Constructor Examples Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Demonstrates equivalent ways to construct a Block object using different string formats for the block type. ```python >>> block = kurt.Block('say:duration:elapsed:from:', 'Hello!', 2) >>> block = kurt.Block('say %s for %s secs', 'Hello!', 2) >>> block = kurt.Block('sayforsecs', 'Hello!', 2) ``` -------------------------------- ### format Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Gets the file format of the project. ```APIDOC ## format ### Description The file format of the project. :class:`Project` is mainly a universal representation, and so a project has no specfic format. This is the format the project was loaded with. To convert to a different format, use :attr:`save()`. ### Returns - (str) - The name of the project's file format. ``` -------------------------------- ### Define Lexer States and Transitions Source: https://github.com/no-context/moo/blob/main/_autodocs/api-reference/lexer.md Example demonstrating how to define lexer states and transitions using `moo.states()`. The `next` option automatically switches to the 'inside' state upon matching 'BEGIN'. ```javascript const moo = require('moo') const lexer = moo.states({ main: { start: { match: 'BEGIN', next: 'inside' }, word: /\w+/, }, inside: { end: { match: 'END', next: 'main' }, text: /.+/, } }) lexer.reset('BEGIN stuff END') lexer.next() // { type: 'start', ... } -> automatically switches to 'inside' state ``` -------------------------------- ### Stateful Lexing with Moo Template Literals Example Source: https://github.com/no-context/moo/blob/main/_autodocs/README.md Illustrates stateful lexing using moo.states() for handling nested contexts like template literals. The lexer transitions between 'main' and 'lit' states. ```javascript const lexer = moo.states({ main: { strstart: { match: '`', push: 'lit' }, ident: /\w+/, lbrace: { match: '{', push: 'main' }, rbrace: { match: '}', pop: 1 }, }, lit: { interp: { match: '${', push: 'main' }, strend: { match: '`', pop: 1 }, const: /[^$`]+/, }, }) lexer.reset('`hello ${name} world`') ``` -------------------------------- ### Moo Correct Keyword Map Usage Source: https://github.com/no-context/moo/blob/main/_autodocs/errors.md Provides examples of correctly defining keywords in Moo's `moo.keywords` map, showing that single keywords should be strings and arrays of keywords are also acceptable. ```javascript moo.compile({ identifier: { match: /\w+/, type: moo.keywords({ 'kw-if': 'if', // Correct - single keyword keyword: ['if'], // Correct - array of keywords }), }, }) ``` -------------------------------- ### Get Project Format Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Returns the name of the file format the project was loaded with. Use save() to convert to a different format. This property is only available if a plugin is loaded. ```python @property def format(self): """The file format of the project. :class:`Project` is mainly a universal representation, and so a project has no specfic format. This is the format the project was loaded with. To convert to a different format, use :attr:`save()`. """ if self._plugin: return self._plugin.name ``` -------------------------------- ### Moo Lexer Non-Greedy Quantifier Example Source: https://github.com/no-context/moo/blob/main/README.md Illustrates the correct usage of non-greedy quantifiers (`*?`) to ensure tokens are matched accurately, preventing them from consuming subsequent tokens. ```javascript let lexer = moo.compile({ string: /\".*?\"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` -------------------------------- ### StatesDefinition Example Source: https://github.com/no-context/moo/blob/main/_autodocs/types.md Defines lexer states, mapping state names to RulesDefinitions. Includes an optional '$all' key for rules common to all states. ```javascript { [stateName: string]: RulesDefinition, $all?: RulesDefinition, } ``` ```javascript { main: { lparen: '(', rparen: ')', number: /\d+/, }, inside: { rparen: ')', text: /[^)]+/, }, $all: { space: /\s+/, } } ``` -------------------------------- ### Compile Lexer Rules with Value Transformation Source: https://github.com/no-context/moo/blob/main/README.md Define lexer rules using moo.compile, including a rule for strings that transforms the matched value by removing the surrounding quotes. This example demonstrates basic lexer setup and usage. ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\"|\\\\|[^"])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` -------------------------------- ### Getting Image File Extension Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Provides a property `extension` that returns the file extension corresponding to the image's format. ```python OP "@" NAME "property" NEWLINE "\n" NAME "def" NAME "extension" OP "(" NAME "self" OP ")" OP ":" NEWLINE "\n" INDENT " " STRING """The extension of the image's :attr:`format` when written to file.\n\n eg ``".png"``\n\n """ NEWLINE "\n" NAME "return" NAME "Image" OP "." NAME "image_extension" OP "(" NAME "self" OP "." NAME "format" OP ")" NEWLINE "\n" DEDENT "" ``` -------------------------------- ### moo.states(states, start) Source: https://github.com/no-context/moo/blob/main/_autodocs/api-reference/moo-module.md Compiles multiple rule sets into a stateful Lexer instance. Each state has its own rule set, and tokens can trigger state transitions. Supports a shared '$all' rule set. ```APIDOC ## moo.states(states, start) ### Description Compiles multiple rule sets into a stateful `Lexer` instance. Each state has its own rule set, and tokens can trigger state transitions via `next`, `push`, and `pop` options. A special `$all` key defines rules shared across all states. ### Method `states(states, start)` ### Parameters #### Path Parameters - **states** (object) - Required - Object mapping state names to rule definitions. - **start** (string) - Optional - Initial state name (defaults to first state). ### Returns `Lexer` - A new stateful `Lexer` instance. ### Throws - `Error` if referenced state doesn't exist - `Error` if pop value is not 1 - `Error` if state-switching rules reference non-existent states ### Request Example ```javascript const moo = require('moo') const lexer = moo.states({ main: { strstart: { match: '`', push: 'lit' }, ident: /\w+/, lbrace: { match: '{', push: 'main' }, rbrace: { match: '}', pop: 1 }, colon: ':', space: { match: /\s+/, lineBreaks: true }, }, lit: { interp: { match: '${', push: 'main' }, escape: /\\./, strend: { match: '`', pop: 1 }, const: { match: /(?:[^`$]|\$(?!\{))+/, lineBreaks: true }, }, }) // Template literal: `a${{c: d}}e` lexer.reset('`a${{c: d}}e`') for (let token of lexer) { console.log(token.type) } // Output: strstart, const, interp, lbrace, ident, colon, space, // ident, rbrace, rbrace, const, strend ``` ``` -------------------------------- ### Define Nested States with Push and Pop Source: https://github.com/no-context/moo/blob/main/_autodocs/api-reference/lexer.md Example showing how to use `push` and `pop` options within token rules to manage nested states. The lexer enters 'nested' state on '{' and returns to 'main' on '}'. ```javascript const moo = require('moo') const lexer = moo.states({ main: { lbrace: { match: '{', push: 'nested' }, word: /\w+/, }, nested: { rbrace: { match: '}', pop: 1 }, word: /\w+/, } }) lexer.reset('word { nested }') lexer.next() // 'word' lexer.next() // '{' -> internally calls pushState('nested') lexer.next() // 'nested' lexer.next() // '}' -> internally calls popState(), back in 'main' ``` -------------------------------- ### Get Block Inserts Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Extracts and returns a list of all 'Insert' instances from the block's parts. These represent the arguments to the block. ```python @property def inserts(self): """The type of each argument to the block. List of :class:`Insert` instances. """ return [p for p in self.parts if isinstance(p, Insert)] ``` -------------------------------- ### Create Independent Lexer Copy for Lookahead Source: https://github.com/no-context/moo/blob/main/_autodocs/api-reference/lexer.md Example demonstrating how to use `clone` to create a separate lexer instance. The cloned lexer operates on different input, allowing independent tokenization without affecting the original lexer. ```javascript const moo = require('moo') const lexer = moo.compile({ word: /\w+/, space: / +/ }) lexer.reset('hello world') const fork = lexer.clone() fork.reset('different input') lexer.next() // 'hello' fork.next() // 'different' ``` -------------------------------- ### Moo Lexer Greedy Quantifier Example Source: https://github.com/no-context/moo/blob/main/README.md Demonstrates how a greedy quantifier in a regular expression can lead to tokens being longer than expected. Use non-greedy quantifiers like `*?` for precise token matching. ```javascript let lexer = moo.compile({ string: /\".*\"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` -------------------------------- ### Get Image Extension Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Converts a given extension string (e.g., 'jpeg') to its standard representation ('.jpg'). Handles common image extension variations. ```python @staticmethod def image_extension(format_or_extension): if format_or_extension: extension = format_or_extension.lstrip(".").lower() if extension == "jpeg": extension = "jpg" return "." + extension ``` -------------------------------- ### Configure a Complete Moo Lexer Source: https://github.com/no-context/moo/blob/main/_autodocs/configuration.md Use moo.compile to define a lexer with various token types including whitespace, comments, strings, numbers, keywords, and operators. This example demonstrates how to set up custom values and types for tokens. ```javascript const moo = require('moo') const lexer = moo.compile({ // Whitespace ws: { match: /\s+/, lineBreaks: true }, // Comments comment: { match: /\/\/.*/, lineBreaks: false }, // Strings with escape sequences string: { match: /"(?:\\["\\rn]|[^"\\])*"/, value: x => x.slice(1, -1), // Remove quotes }, // Numbers (integer and decimal) number: [ { match: /\d+\.\d+/, value: x => parseFloat(x) }, { match: /\d+/, value: x => parseInt(x, 10) }, ], // Keywords with type detection identifier: { match: /[a-zA-Z_]\w*/, type: moo.keywords({ 'kw-if': 'if', 'kw-else': 'else', 'kw-while': 'while', 'identifier': ['foo', 'bar'], }), }, // Operators eq: '==', assign: '=', plus: '+', minus: '-', lparen: '(', rparen: ')', lbrace: '{', rbrace: '}', semicolon: ';', // Error handling error: moo.error, }) const input = 'while (x == 5) { x = x + 1; }' lexer.reset(input) console.log(Array.from(lexer)) ``` -------------------------------- ### Moo Custom Error Output Example Source: https://github.com/no-context/moo/blob/main/_autodocs/errors.md Shows the typical output format when using `lexer.formatError()` to report an error, including the error message, line and column number, and a visual indicator of the error location in the source text. ```text Error: spaces not allowed at line 1 col 6: hello world ^ ``` -------------------------------- ### Define Lexer States with moo.states Source: https://github.com/no-context/moo/blob/main/README.md Utilize `moo.states` to manage multiple lexer states, each with its own token rules. Use `next`, `push`, and `pop` annotations on rules to control state transitions. The lexer starts in the first state provided. ```javascript let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: 1}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: 1}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` -------------------------------- ### Load Project from File Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Loads a project from a file, determining the format based on the file extension or a provided format string. Handles unknown formats and ensures the correct plugin is used. ```python filename, extension = os.path.splitext(filename) if format is None: plugin = kurt.plugin.Kurt.get_plugin( extension ) if not plugin: raise UnknownFormat(extension) fp = open(path, "rb") else: fp = path assert format, "Format is required" plugin = kurt.plugin.Kurt.get_plugin( format ) if not plugin: raise ValueError("Unknown format %r" % format) project = plugin.load( fp ) if path_was_string: fp.close() project.convert( plugin ) if isinstance(path, basestring): project.path = path if not project.name: project.name = name return project ``` -------------------------------- ### Get Block Parts Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Retrieves the parts of the block. This is a property that calls the `convert` method to get the associated PluginBlockType and then accesses its parts. ```python @property def parts(self): return self.convert().parts ``` -------------------------------- ### Get Block Shape Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Retrieves the shape of the block. This is a property that calls the `convert` method to get the associated PluginBlockType and then accesses its shape. ```python @property def shape(self): return self.convert().shape ``` -------------------------------- ### Project Class Initialization Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Initializes a new Project object. This sets up default attributes like name and path, preparing the object to hold Scratch project data. ```Python class Project( object ): """The main kurt class. Stores the contents of a project file. Contents include global variables and lists, the :attr:`stage` and :attr:`sprites`, each with their own :attr:`scripts`, :attr:`costumes`, :attr:`sounds`, :attr:`variables` and :attr:`lists`. A Project can be loaded from or saved to disk in a format which can be read by a Scratch program or one of its derivatives. Loading a project:: p = kurt.Project.load("tests/game.sb") Getting all the scripts:: for scriptable in p.sprites + [p.stage]: for script in scriptable.scripts: print script Creating a new project:: p = kurt.Project() Converting between formats:: p = kurt.Project.load("tests/game.sb") p.convert("scratch20") # [] p.save() # 'tests/game.sb2' """ def __init__(self): self.name = u"" self.path = None ``` -------------------------------- ### Load Project from File Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Class method to load a project from a specified path or file-like object. Allows specifying the format to use, overriding the file extension. Raises UnknownFormat or ValueError for invalid formats or extensions. ```python @classmethod def load(cls, path, format=None): """Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you're responsible for closing the file. :param path: Path or file pointer. :param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``. Overrides the extension. :raises: :class:`UnknownFormat` if the extension is unrecognised. :raises: :py:class:`ValueError` if the format doesn't exist. """ path_was_string = isinstance(path, basestring) if path_was_string: (folder, filename) = os.path.split(path) (name, extension) = ``` -------------------------------- ### Get Watcher Value Property Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt A property to access the value of the watcher. This is a placeholder and its implementation is not shown in this snippet. ```python @property def value(self): ``` -------------------------------- ### Basic Moo Lexer Compilation and Usage Source: https://github.com/no-context/moo/blob/main/_autodocs/README.md Demonstrates how to compile a set of token rules using moo.compile() and then tokenize input by iterating through the lexer. Use this for stateless tokenization. ```javascript const moo = require('moo') // Create a lexer const lexer = moo.compile({ WS: /[ \t]+/, number: /0|[1-9][0-9]*/, string: /"(?:\\"|\\\\|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else'], NL: { match: /\n/, lineBreaks: true }, }) // Tokenize input lexer.reset('while (10) { x = "hello"; }') console.log(lexer.next()) // { type: 'keyword', value: 'while', ... } console.log(lexer.next()) // { type: 'WS', value: ' ', ... } // ... continue calling next() // Or iterate for (let token of lexer) { console.log(token.type, token.value) } ``` -------------------------------- ### Accessing Image Dimensions Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Get the size of an image in pixels. Returns cached size if available, otherwise calculates it. ```python OP "@" NAME "property" NAME "def" NAME "size" OP "(" NAME "self" OP ")" OP ":" NEWLINE "\n" INDENT " " STRING """``(width, height)`` in pixels.""" NEWLINE "\n" NAME "if" NAME "self" OP "." NAME "_size" NAME "and" NAME "not" NAME "self" OP "." NAME "_pil_image" OP ":" NEWLINE "\n" INDENT " " NAME "return" NAME "self" OP "." NAME "_size" NEWLINE "\n" DEDENT "" NAME "else" OP ":" NEWLINE "\n" INDENT " " NAME "return" NAME "self" OP "." NAME "pil_image" OP "." NAME "size" NEWLINE "\n" DEDENT "" DEDENT "" ``` -------------------------------- ### Color Class Value Property Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Provides a property to get or set the RGB tuple value of a Color object. ```Python @property def value(self): """Return ``(r, g, b)`` tuple.""" return (self.r, self.g, self.b) @value.setter def value(self, value): (self.r, self.g, self.b) = ``` -------------------------------- ### Create New Image Instance Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Creates a new Image instance with a specified size and fill color. Requires PIL library. ```python @classmethod def new(self, size, fill): """Return a new Image instance filled with a color.""" return Image( PIL.Image.new("RGB", size, fill) ) ``` -------------------------------- ### Compile Rules to Lexer Source: https://github.com/no-context/moo/blob/main/_autodocs/MANIFEST.txt Use the `compile` function to create a lexer instance from a set of rules. This is the primary entry point for setting up a lexer. ```javascript compile(rules) → Lexer ``` -------------------------------- ### Get Broadcasts from Block Arguments Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Extracts broadcast information by zipping block arguments and their corresponding insert points. ```python def get_broadcasts(block): for (arg, insert) in zip( ``` -------------------------------- ### Get Waveform Frame Rate Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Retrieves the frame rate of the waveform. This is useful for understanding the temporal resolution of the audio data. ```python def _rate(self): return self._wave.getframerate() ``` -------------------------------- ### Convert Project to Different Format Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Converts the project in-place to a different file format. It retrieves the appropriate plugin based on the format and normalizes the project. Returns a list of UnsupportedFeature objects. ```python NAME "def" NAME "convert" OP "(" NAME "self" OP "," NAME "format" OP ")" OP ":" NEWLINE "\n" INDENT " " STRING """Convert the project in-place to a different file format.\n\n Returns a list of :class:`UnsupportedFeature` objects, which may give\n warnings about the conversion.\n\n :param format: :attr:`KurtFileFormat.name` eg. ``\"scratch14\"``.\n\n :raises: :class:`ValueError` if the format doesn't exist.\n\n """ NEWLINE "\n" NAME "self" OP "." NAME "_plugin" OP "=" NAME "kurt" OP "." NAME "plugin" OP "." NAME "Kurt" OP "." NAME "get_plugin" OP "(" NAME "format" OP ")" NEWLINE "\n" NAME "return" NAME "list" OP "(" NAME "self" OP "." NAME "_normalize" OP "(" OP ")" OP ")" NEWLINE "\n" DEDENT "" ``` -------------------------------- ### Token Initialization and Content Assignment Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Handles the initial assignment of contents and format during token initialization. ```python NAME "self" OP "." NAME "_pil_image" OP "=" NAME "contents" NEWLINE "\n" DEDENT "" NAME "else" OP ":" NEWLINE "\n" INDENT " " NAME "self" OP "." NAME "_contents" OP "=" NAME "contents" NEWLINE "\n" NAME "self" OP "." NAME "_format" OP "=" NAME "Image" OP "." NAME "image_format" OP "(" NAME "format" OP ")" NEWLINE "\n" NL "\n" DEDENT "" DEDENT "" ``` -------------------------------- ### Load Sound from Path Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Class method to load a Sound object from a specified file path. Requires the path to a valid sound file. ```python @classmethod def load(self, path): ``` -------------------------------- ### Get Plugin Conversions Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Provides access to the list of registered PluginBlockType instances. This is a property that returns the values from the internal plugin storage. ```python @property def conversions(self): """Return the list of :class:`PluginBlockType` instances.""" return self._plugins.values() ``` -------------------------------- ### Initialize a new object with copied assets Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt This code initializes a new object 'o' by copying various assets from 'self'. It copies variables, lists, costumes, and sounds, and also transfers the costume index and volume. Use this when creating a duplicate or a new instance with existing asset references. ```python o = dict() o.lists = dict((n, l.copy()) for n, l in self.lists.items()) o.costumes = [c.copy() for c in self.costumes] o.sounds = [s.copy() for s in self.sounds] o.costume_index = self.costume_index o.volume = self.volume return o ``` -------------------------------- ### Get Waveform Sample Count Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Returns the number of samples in the sound. If the sample count is not already set, it calculates it from the underlying wave data. ```python def sample_count(self): """The number of samples in the sound.""" if self._sample_count: return self._sample_count else: return self._wave.getnframes() ``` -------------------------------- ### Value Transformation: Remove Quotes Source: https://github.com/no-context/moo/blob/main/_autodocs/configuration.md Use the `value` option with a function to transform the matched text. This example removes surrounding quotes from string literals. ```javascript moo.compile({ string: { match: /"(?:\\"|\\|[^\n"\\])*"/, value: x => x.slice(1, -1), } }) ``` -------------------------------- ### Construct Image Path Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Joins a folder and filename to create a full path. Ensure 'folder' and 'filename' are defined before use. ```python extension = "path" path = os.path.join(folder, filename) ``` -------------------------------- ### Iterating Over Lexer Tokens Source: https://github.com/no-context/moo/blob/main/_autodocs/api-reference/lexer.md Demonstrates how to use the Moo lexer with for...of loops and Array.from() to iterate over generated tokens. Ensure the lexer is compiled and reset with input before iteration. ```javascript const moo = require('moo') const lexer = moo.compile({ word: /\w+/, space: / +/ }) lexer.reset('hello world') // Using for...of for (let token of lexer) { console.log(token.type, token.value) } // Using Array.from const tokens = Array.from(lexer) ``` -------------------------------- ### Sound Class Initialization Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Initializes a Sound object with a name and waveform. The name is used for script references, and the waveform holds the raw sound data. ```python def __init__(self, name, waveform): self.name = name """Name used by scripts to refer to this Sound.""" self.waveform = waveform """A :class:`Waveform` instance containing the raw sound data.""" ``` -------------------------------- ### Get Stripped Block Text Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Provides a version of the block's text with spaces and inserts removed. This is used for looking up blocks by their text content. ```python @property def stripped_text(self): """The :attr:`text`, with spaces and inserts removed. Used by :class:`BlockType.get` to look up blocks. """ return BaseBlockType._strip_text( self.text % ``` -------------------------------- ### Get Block Default Values Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Returns a list of default values for the block's inserts. This is useful for providing initial values when the block is used. ```python @property def defaults(self): """Default values for block inserts. (See :attr:`Block.args`.)""" return [i.default for i in self.inserts] ``` -------------------------------- ### Get Block Text Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Retrieves the display text for a block, formatting inserts with '%s'. It also handles escaping percent signs to ensure correct display. ```python @property def text(self): """The text displayed on the block. String containing ``"%s"`` in place of inserts. eg. ``'say %s for %s secs'`` """ parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts] parts = [("%%" if p == "%" else p) for p in parts] # escape percent return "".join(parts) ``` -------------------------------- ### Initialize List Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Initializes a List object with a list of items and a cloud status. If no items are provided, an empty list is created. ```python def __init__(self, items=None, is_cloud=False): self.items = list(items) if items else [] """The items contained in the list. A Python list of unicode strings. """ self.is_cloud = bool(is_cloud) ``` -------------------------------- ### Get Next Token Source: https://github.com/no-context/moo/blob/main/_autodocs/MANIFEST.txt The `next` method advances the lexer and returns the next token found in the input. It returns `undefined` if the end of the input is reached. ```javascript next() → Token | undefined ``` -------------------------------- ### Copy Sound Instance Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Creates a new Sound instance with the same name and waveform as the original. Useful for duplicating sound objects. ```python def copy(self): """Return a new instance with the same attributes.""" return Sound(self.name, self.waveform) ``` -------------------------------- ### Load Sound from Wave File Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Loads a sound from a wave file, setting the waveform's name from the sound filename. Requires os.path module. ```python def load(folder, filename): (name, extension) = os.path.splitext(filename) return Sound(name, Waveform.load(path)) ``` -------------------------------- ### Get Watcher Kind Property Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt A property that returns the type of value to watch, determined by the watcher's block. Possible values are 'variable', 'list', or 'block'. ```python @property def kind(self): """The type of value to watch, based on :attr:`block`. One of ``variable``, ``list``, or ``block``. ``block`` watchers watch the value of a reporter block. """ if self.block.type.has_command('readVariable'): return 'variable' elif self.block.type.has_command('contentsOfList:'): return 'list' else: return 'block' ``` -------------------------------- ### Block Initialization and Attributes Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Shows the initialization of a Block object and how to access its type and arguments. ```python >>> block.type >>> block.args ['Hello!', 2] ``` -------------------------------- ### Define Lexer States Source: https://github.com/no-context/moo/blob/main/_autodocs/MANIFEST.txt The `states` function allows you to define named states for your lexer, enabling stateful parsing. Specify the initial state using the `start` parameter. ```javascript states(states, start) → Lexer ``` -------------------------------- ### Define Rule with Mixed Options and Match Source: https://github.com/no-context/moo/blob/main/_autodocs/configuration.md Combine match patterns with other rule options like `lineBreaks` and `value` transforms. This example removes surrounding quotes from matched strings. ```javascript moo.compile({ string: { match: /"(?:\\"|\\|[^\n"\\])*"/, lineBreaks: false, value: x => x.slice(1, -1), } }) ``` -------------------------------- ### Class Method to Get Block Type Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt A class method to retrieve a block type. This method is intended to be implemented by subclasses to provide specific block type retrieval logic. ```python @classmethod def get(cls, block_type): pass ``` -------------------------------- ### States Function Configuration Source: https://github.com/no-context/moo/blob/main/_autodocs/configuration.md Defines lexer states using the moo.states function. It accepts an object mapping state names to rule definitions and an optional starting state name. ```javascript moo.states({ main: { ... rules for main state ... }, string: { ... rules for string state ... }, comment: { ... rules for comment state ... }, $all: { ... rules active in all states ... }, }, 'main') // Start in 'main' state ``` -------------------------------- ### Creating a New Block from an Existing BlockType Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Illustrates creating a new block using an existing BlockType instance with different arguments. ```python >>> block2 = kurt.Block(block.type, 'Goodbye!', 5) ``` -------------------------------- ### Initialize Plugin Storage Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Initializes the storage for plugin block types using an OrderedDict. This is used to maintain the order of plugins. ```python self._plugins = OrderedDict([ (pbt.format, pbt) ]) ``` -------------------------------- ### load(path, format=None) Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Loads a Kurt project from a specified file path or file-like object. ```APIDOC ## load(path, format=None) ### Description Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you're responsible for closing the file. ### Parameters #### Path Parameters - **path** (str or file-like object) - Path or file pointer. - **format** (str, optional) - :attr:`KurtFileFormat.name` eg. ``"scratch14"``. Overrides the extension. ### Raises - :class:`UnknownFormat` if the extension is unrecognised. - :py:class:`ValueError` if the format doesn't exist. ``` -------------------------------- ### Reset Lexer and Get Next Token Source: https://github.com/no-context/moo/blob/main/README.md Feed input text to the compiled lexer and retrieve tokens one by one using `next()`. Reset the lexer with `reset()` to process more data. ```javascript lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... // When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. ``` -------------------------------- ### Load Costume from Image File Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Loads a costume from an image file, setting the costume's name based on the filename. It uses os.path functions to split the path and extension. ```Python import os @classmethod def load(self, path): """Load costume from image file. Uses :attr:`Image.load`, but will set the Costume's name based on the image filename. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Costume( name, Image.load(path) ) ``` -------------------------------- ### Moo File Organization Source: https://github.com/no-context/moo/blob/main/_autodocs/README.md Overview of the Moo project's file structure. This is useful for understanding where different components of the library and its tests are located. ```text moo.js Main library (645 lines) package.json Package metadata test/ Jest test suite test.js Comprehensive tests benchmark.js Performance benchmarks *.py Python lexer examples ``` -------------------------------- ### Stringifying a Block Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Demonstrates how to convert a Block object into its string representation. ```python >>> block.stringify() 'say [Hello!] for (2) secs' >>> block2.stringify() 'say [Goodbye!] for (5) secs' ``` -------------------------------- ### Nested Contexts with 'push' and 'pop' Source: https://github.com/no-context/moo/blob/main/_autodocs/configuration.md Use `push` to enter a new state, saving the current state on a stack, and `pop` to return to the previous state. This enables handling nested or recursive grammar structures. ```javascript // Nested contexts with push/pop const lexer = moo.states({ main: { lbrace: { match: '{', push: 'nested' }, word: /\w+/, }, nested: { rbrace: { match: '}', pop: 1 }, word: /\w+/, } }) lexer.reset('outer { inner } end') lexer.next() // outer lexer.next() // {, switches to 'nested' (saves 'main' on stack) lexer.next() // inner lexer.next() // }, pops state (returns to 'main') lexer.next() // end ``` -------------------------------- ### Generate Formatted Error with Context Lines Source: https://github.com/no-context/moo/blob/main/_autodocs/api-reference/lexer.md Example of using `formatError` to create a multi-line error message. It shows the line and column of the error, along with surrounding lines and a pointer to the exact location. ```javascript const moo = require('moo') const lexer = moo.compile({ word: /\w+/, space: / +/, }) lexer.reset('hello\nworld\ninvalid$token') let token while (token = lexer.next()) { // ... } // If an unexpected token causes a parse error: if (!token) { throw new Error(lexer.formatError(token, 'unexpected syntax')) } // Output: // Error: unexpected syntax at line 3 col 9: // // 2 world // 3 invalid$token // ^ ``` -------------------------------- ### Converting Image Format Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Returns an Image instance with the first matching format from the provided list. If no match, converts to the last specified format. ```python NAME "def" NAME "convert" OP "(" NAME "self" OP "," OP "*" NAME "formats" OP ")" OP ":" NEWLINE "\n" INDENT " " STRING """Return an Image instance with the first matching format.\n\n For each format in ``*args``: If the image's :attr:`format` attribute\n is the same as the format, return self, otherwise try the next format.\n\n If none of the formats match, return a new Image instance with the\n last format.\n\n """ NEWLINE "\n" NAME "for" NAME "format" NAME "in" NAME "formats" OP ":" NEWLINE "\n" INDENT " " NAME "format" OP "=" NAME "Image" OP "." NAME "image_format" OP "(" NAME "format" OP ")" NEWLINE "\n" NAME "if" NAME "self" OP "." NAME "format" OP "==" NAME "format" OP ":" NEWLINE "\n" INDENT " " NAME "return" NAME "self" NEWLINE "\n" DEDENT "" DEDENT "" NAME "else" OP ":" NEWLINE "\n" INDENT " " NAME "return" NAME "self" OP "." NAME "_convert" OP "(" NAME "format" OP ")" NEWLINE "\n" DEDENT "" DEDENT "" ``` -------------------------------- ### Resize Image Instance Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Returns a new Image instance with the specified dimensions. Uses PIL's ANTIALIAS for resizing. ```python def resize(self, size): """Return a new Image instance with the given size.""" return Image( self.pil_image.resize(size, PIL.Image.ANTIALIAS) ) ``` -------------------------------- ### Get Sprite by Name Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Retrieves a sprite from the project's sprites list by its name. Returns None if the sprite is not found. Ensure sprites are added to the 'actors' list on save if they are not already present. ```python def get_sprite(self, name): """Get a sprite from :attr:`sprites` by name. Returns None if the sprite isn't found. """ for sprite in self.sprites: if sprite.name == name: return sprite ``` -------------------------------- ### Moo 'keyword must be string' Error Example Source: https://github.com/no-context/moo/blob/main/_autodocs/errors.md Demonstrates the 'keyword must be string' error triggered by providing a non-string value (like an array) as a keyword in the `moo.keywords` map. Keywords must be strings for direct comparison. ```javascript moo.compile({ identifier: { match: /\w+/, type: moo.keywords({ 'kw-if': ['if'], // Array instead of string - Error }), }, }) ``` -------------------------------- ### Create a Copy of the Script Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Returns a new Script instance with copies of all its blocks and the same position. ```python def copy(self): """Return a new instance with the same attributes.""" return self.__class__([ b.copy() for b in self.blocks ], tuple(self.pos) if self.pos else None) ``` -------------------------------- ### Loading Image from File Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Loads an image from a given file path. Asserts that the file exists before proceeding. ```python OP "@" NAME "classmethod" NEWLINE "\n" NAME "def" NAME "load" OP "(" NAME "cls" OP "," NAME "path" OP ")" OP ":" NEWLINE "\n" INDENT " " STRING """Load image from file.""" NEWLINE "\n" NAME "assert" NAME "os" OP "." NAME "path" OP "." NAME "exists" OP "(" NAME "path" OP ")" OP "," STRING ""No such file: %r""" OP "%" NAME "path" NEWLINE "\n" NL "\n" OP "(" NAME "folder" OP "," NAME "filename" OP ")" OP "=" NAME "os" OP "." NAME "path" OP "." NAME "split" OP "(" NAME "path" OP ")" NEWLINE "\n" OP "(" NAME "name" OP "," NAME "extension" OP ")" OP "=" NAME "os" OP "." NAME "path" OP "." NAME "splitext" OP "(" NAME "filename" OP ")" NEWLINE "\n" NL "\n" NAME "image" OP "=" NAME "Image" OP "(" NAME "None" OP ")" NEWLINE "\n" NAME "image" OP "." NAME "_path" OP "=" NAME "path" NEWLINE "\n" NAME "image" OP "." NAME "_format" OP "=" NAME "Image" OP "." NAME "image_format" OP "(" NAME "extension" OP ")" NEWLINE "\n" NL "\n" NAME "return" NAME "image" NEWLINE "\n" DEDENT "" ``` -------------------------------- ### Moo 'invalid syntax' Error Example Source: https://github.com/no-context/moo/blob/main/_autodocs/errors.md Demonstrates how Moo throws an 'invalid syntax' error when no rule matches the current input and no error handling is defined. This occurs when the lexer encounters input that cannot be tokenized by any of its defined rules. ```javascript const lexer = moo.compile({ word: /\w+/, }) lexer.reset('hello $world') lexer.next() // OK: 'hello' lexer.next() // OK: ' ' matches... wait, no space rule. Error! ``` -------------------------------- ### Color Class Initialization Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Initializes a Color object, accepting RGB tuples, hex codes, or another Color object. ```Python def __init__(self, r, g=None, b=None): if g is None and b is None: if isinstance(r, Color): r = r.value elif isinstance(r, basestring): if not r.startswith("#"): raise ValueError, "invalid color hexcode: %r" % r r = r[1:] if len(r) == 3: r = r[0] + r[0] + r[1] + r[1] + r[2] + r[2] split = (r[0:2], r[2:4], r[4:6]) r = [int(x, 16) for x in split] (r, g, b) = r self.r = int(r) """Red component, 0-255""" self.g = int(g) """Green component, 0-255""" self.b = int(b) """Blue component, 0-255""" ``` -------------------------------- ### Compile a Lexer with Moo Source: https://github.com/no-context/moo/blob/main/README.md Define tokens using regular expressions and keywords. Use `lineBreaks: true` for rules that contain newlines to enable line number tracking. ```javascript const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\"|\\\\|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` -------------------------------- ### Import StringIO for Python 2/3 Compatibility Source: https://github.com/no-context/moo/blob/main/test/kurt-tokens.txt Imports the StringIO module, attempting to use the cStringIO version for performance in Python 2, and falling back to the standard StringIO in Python 3 or if cStringIO is unavailable. ```Python from cStringIO import StringIO ``` ```Python from StringIO import StringIO ```