Task 366: .M File Format

Task 366: .M File Format

File Format Specifications for the .M File Format

The .M file format refers to the plain text Live Code file format used by MATLAB for live scripts (introduced in MATLAB R2025a). It is an alternative to the binary .mlx format and is based on the standard MATLAB .m code file format. The format is plain text (UTF-8), with custom markup embedded as comments to support Live Editor features like formatted text, outputs, controls, tasks, and views. The markup is divided into inline markup (integrated with code) and an appendix (at the bottom of the file for larger data). Each markup is prefixed with % and uses a specific syntax for different elements. The format allows integration with external editors and source control. For full details, see the MATLAB documentation on Live Code File Format (.m).

  1. List of all the properties of this file format intrinsic to its file system:
  • Formatted Text
  • Table of Contents
  • Code Example
  • Table
  • Image
  • Hyperlink
  • Equation
  • Output
  • Control
  • Live Editor Task
  • Live Script View
  1. Two direct download links for files of format .M:
  1. Ghost blog embedded HTML JavaScript that allows a user to drag n drop a file of format .M and it will dump to screen all these properties:
.M File Property Dumper
Drag and drop a .M file here
  1. Python class that can open any file of format .M and decode read and write and print to console all the properties from the above list:
import os

class MFileHandler:
    def __init__(self, filepath):
        self.filepath = filepath
        self.properties = []
        self.content = ''

    def read_and_decode(self):
        with open(self.filepath, 'r', encoding='utf-8') as f:
            self.content = f.read()
            lines = self.content.split('\n')
            for line in lines:
                if line.strip().startswith('%['):
                    match = line.split('%[', 1)[1].split(']', 1)[0] if ']' in line else None
                    if match:
                        self.properties.append(match)
        return self.properties

    def print_properties(self):
        if not self.properties:
            print("No properties found.")
        else:
            for prop in self.properties:
                print(prop)

    def write(self, new_filepath=None):
        filepath = new_filepath or self.filepath
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(self.content)
        print(f"File written to {filepath}")

# Example usage:
# handler = MFileHandler('example.m')
# handler.read_and_decode()
# handler.print_properties()
# handler.write('new_example.m')
  1. Java class that can open any file of format .M and decode read and write and print to console all the properties from the above list:
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MFileHandler {
    private String filepath;
    private List<String> properties;
    private String content;

    public MFileHandler(String filepath) {
        this.filepath = filepath;
        this.properties = new ArrayList<>();
        this.content = "";
    }

    public List<String> readAndDecode() throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filepath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
                if (line.trim().startsWith("%[")) {
                    int start = line.indexOf("%[") + 2;
                    int end = line.indexOf("]", start);
                    if (end != -1) {
                        String prop = line.substring(start, end);
                        properties.add(prop);
                    }
                }
            }
        }
        content = sb.toString();
        return properties;
    }

    public void printProperties() {
        if (properties.isEmpty()) {
            System.out.println("No properties found.");
        } else {
            for (String prop : properties) {
                System.out.println(prop);
            }
        }
    }

    public void write(String newFilepath) throws IOException {
        if (newFilepath == null) {
            newFilepath = filepath;
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(newFilepath))) {
            writer.write(content);
        }
        System.out.println("File written to " + newFilepath);
    }

    // Example usage:
    // public static void main(String[] args) throws IOException {
    //     MFileHandler handler = new MFileHandler("example.m");
    //     handler.readAndDecode();
    //     handler.printProperties();
    //     handler.write("new_example.m");
    // }
}
  1. JavaScript class that can open any file of format .M and decode read and write and print to console all the properties from the above list:
const fs = require('fs'); // For Node.js

class MFileHandler {
  constructor(filepath) {
    this.filepath = filepath;
    this.properties = [];
    this.content = '';
  }

  readAndDecode() {
    this.content = fs.readFileSync(this.filepath, 'utf-8');
    const lines = this.content.split('\n');
    lines.forEach((line) => {
      if (line.trim().startsWith('%[')) {
        const match = line.match(/%\[([^\]]+)\]/);
        if (match) {
          this.properties.push(match[1]);
        }
      }
    });
    return this.properties;
  }

  printProperties() {
    if (this.properties.length === 0) {
      console.log('No properties found.');
    } else {
      this.properties.forEach((prop) => {
        console.log(prop);
      });
    }
  }

  write(newFilepath = this.filepath) {
    fs.writeFileSync(newFilepath, this.content, 'utf-8');
    console.log(`File written to ${newFilepath}`);
  }
}

// Example usage:
// const handler = new MFileHandler('example.m');
// handler.readAndDecode();
// handler.printProperties();
// handler.write('new_example.m');
  1. C class that can open any file of format .M and decode read and write and print to console all the properties from the above list:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 1024
#define MAX_PROPS 100

typedef struct {
    char *filepath;
    char *properties[MAX_PROPS];
    int prop_count;
    char *content;
    long content_size;
} MFileHandler;

MFileHandler* createMFileHandler(const char *filepath) {
    MFileHandler *handler = (MFileHandler*)malloc(sizeof(MFileHandler));
    handler->filepath = strdup(filepath);
    handler->prop_count = 0;
    handler->content = NULL;
    handler->content_size = 0;
    return handler;
}

void readAndDecode(MFileHandler *handler) {
    FILE *file = fopen(handler->filepath, "r");
    if (!file) {
        printf("Error opening file.\n");
        return;
    }

    fseek(file, 0, SEEK_END);
    handler->content_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    handler->content = (char*)malloc(handler->content_size + 1);
    fread(handler->content, 1, handler->content_size, file);
    handler->content[handler->content_size] = '\0';
    fclose(file);

    char *line = strtok(handler->content, "\n");
    while (line) {
        if (strstr(line, "%[")) {
            char *start = strstr(line, "%[") + 2;
            char *end = strchr(start, ']');
            if (end) {
                *end = '\0';
                handler->properties[handler->prop_count] = strdup(start);
                handler->prop_count++;
                *end = ']';
            }
        }
        line = strtok(NULL, "\n");
    }
}

void printProperties(MFileHandler *handler) {
    if (handler->prop_count == 0) {
        printf("No properties found.\n");
    } else {
        for (int i = 0; i < handler->prop_count; i++) {
            printf("%s\n", handler->properties[i]);
        }
    }
}

void write(MFileHandler *handler, const char *newFilepath) {
    const char *path = newFilepath ? newFilepath : handler->filepath;
    FILE *file = fopen(path, "w");
    if (!file) {
        printf("Error writing file.\n");
        return;
    }
    fwrite(handler->content, 1, handler->content_size, file);
    fclose(file);
    printf("File written to %s\n", path);
}

void destroyMFileHandler(MFileHandler *handler) {
    free(handler->filepath);
    for (int i = 0; i < handler->prop_count; i++) {
        free(handler->properties[i]);
    }
    free(handler->content);
    free(handler);
}

// Example usage:
// int main() {
//     MFileHandler *handler = createMFileHandler("example.m");
//     readAndDecode(handler);
//     printProperties(handler);
//     write(handler, "new_example.m");
//     destroyMFileHandler(handler);
//     return 0;
// }