CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jupyterlab--codemirror

CodeMirror 6 editor provider for JupyterLab with comprehensive language support, themes, extensions, and collaborative editing capabilities

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

special-extensions.mddocs/

Special Extensions

Specialized extensions for advanced functionality including collaborative editing, rulers, custom styling, and Python highlighting.

Capabilities

Y.js Collaborative Editing

Real-time collaborative editing integration using Y.js for shared document synchronization.

/**
 * Extension for CodeMirror 6 binding the Yjs text and editor state
 * Enables real-time collaborative editing
 */
function ybinding(options: { ytext: Text; undoManager?: UndoManager }): Extension;

/**
 * Y.js range class for relative positioning
 */
class YRange {
  constructor(yanchor: RelativePosition, yhead: RelativePosition);
  
  /**
   * Convert the position to JSON
   */
  toJSON(): Range;
  
  /**
   * Convert a JSON range to a YRange
   */
  static fromJSON(json: Range): YRange;
}

/**
 * Y.js binding configuration
 */
class YSyncConfig {
  constructor(ytext: Text);
  
  readonly ytext: Text;
  
  /**
   * Transform absolute index position to Yjs-based relative position
   */
  toYPos(pos: number, assoc?: number): RelativePosition;
  
  /**
   * Transform relative position back to absolute position
   */
  fromYPos(rpos: RelativePosition | Record<string, any>): number;
  
  /**
   * Convert selection range to Y range
   */
  toYRange(range: SelectionRange): YRange;
  
  /**
   * Convert Y range to selection range
   */
  fromYRange(yrange: YRange): SelectionRange;
}

/**
 * Y.js undo manager integration
 */
class YUndoManagerConfig {
  constructor(undoManager: UndoManager);
  
  readonly undoManager: UndoManager;
}

// Facets and plugins
const ySyncFacet: Facet<YSyncConfig, YSyncConfig>;
const ySyncAnnotation: Annotation<YSyncConfig>;
const ySync: ViewPlugin;
const yUndoManagerFacet: Facet<YUndoManagerConfig, YUndoManagerConfig>;
const yUndoManager: ViewPlugin;

Usage Examples:

import { ybinding } from "@jupyterlab/codemirror";
import { Text, UndoManager } from "yjs";
import { WebsocketProvider } from "y-websocket";

// Create Y.js document and text
const ydoc = new Y.Doc();
const ytext = ydoc.getText('codemirror');
const undoManager = new UndoManager(ytext);

// Create collaborative editor
const editor = new EditorView({
  extensions: [
    ybinding({ ytext, undoManager }),
    // ... other extensions
  ],
  parent: document.body
});

// Set up network provider for real-time sync
const provider = new WebsocketProvider('ws://localhost:1234', 'my-room', ydoc);

// Handle collaboration events
provider.on('status', (event) => {
  console.log('Connection status:', event.status);
});

// Clean up
provider.destroy();
editor.destroy();

Ruler Extensions

Visual ruler lines for code layout guidance and style enforcement.

/**
 * Extension for CodeMirror 6 displaying rulers
 * Shows vertical lines at specified column positions
 */
function rulers(positions: number[]): Extension;

Usage Examples:

import { rulers } from "@jupyterlab/codemirror";

// Add rulers at columns 80 and 120
const rulerExtension = rulers([80, 120]);

// Create editor with rulers
const editor = new EditorView({
  extensions: [
    rulerExtension,
    // ... other extensions
  ]
});

// Dynamic ruler configuration
function createDynamicRulers(language: string): Extension {
  switch (language) {
    case 'python':
      return rulers([79, 88]); // PEP 8 guidelines
    case 'javascript':
    case 'typescript':
      return rulers([80, 100, 120]); // Common JS guidelines
    case 'java':
      return rulers([100, 120]); // Java conventions
    default:
      return rulers([80]); // Default ruler
  }
}

// Update rulers based on language
editor.dispatch({
  effects: StateEffect.reconfigure.of([
    createDynamicRulers('python'),
    // ... other extensions
  ])
});

Custom Styling

Dynamic custom styling system for font family, size, and line height configuration.

/**
 * Get the extension to customize an editor theme
 * Allows dynamic font and spacing configuration
 */
function customTheme(config: CustomTheme): Extension;

/**
 * Editor customizable styles
 */
interface CustomTheme {
  fontFamily: string | null;
  fontSize: number | null;
  lineHeight: number | null;
}

Usage Examples:

import { customTheme, CustomTheme } from "@jupyterlab/codemirror";

// Create custom theme configuration
const themeConfig: CustomTheme = {
  fontFamily: 'Monaco, "Courier New", monospace',
  fontSize: 14,
  lineHeight: 1.5
};

// Apply custom theme
const customThemeExtension = customTheme(themeConfig);

const editor = new EditorView({
  extensions: [
    customThemeExtension,
    // ... other extensions
  ]
});

// Dynamic theme updates
function updateTheme(config: Partial<CustomTheme>) {
  const currentConfig = getCurrentThemeConfig();
  const newConfig = { ...currentConfig, ...config };
  
  editor.dispatch({
    effects: StateEffect.reconfigure.of([
      customTheme(newConfig),
      // ... other extensions
    ])
  });
}

// Update font size
updateTheme({ fontSize: 16 });

// Update font family
updateTheme({ fontFamily: 'JetBrains Mono, monospace' });

// Responsive font sizing
function createResponsiveTheme(): CustomTheme {
  const screenWidth = window.innerWidth;
  
  if (screenWidth < 768) {
    return { fontFamily: null, fontSize: 12, lineHeight: 1.4 }; // Mobile
  } else if (screenWidth < 1024) {
    return { fontFamily: null, fontSize: 13, lineHeight: 1.5 }; // Tablet
  } else {
    return { fontFamily: null, fontSize: 14, lineHeight: 1.6 }; // Desktop
  }
}

Python Built-in Highlighting

Enhanced syntax highlighting for Python built-in functions and keywords.

/**
 * Create a view plugin for highlighting Python built-in functions
 * Provides enhanced highlighting for Python's 158 built-in functions
 */
function pythonBuiltin(langPython: Language): ViewPlugin;

/**
 * View plugin class for highlighting Python built-in functions
 */
class PythonBuiltin {
  constructor(view: EditorView, langPython: Language);
  
  decorations: DecorationSet;
  decoratedTo: number;
  langPython: Language;
  tree: Tree;
  mark: Decoration;
  
  update(update: ViewUpdate): void;
  buildDeco(view: EditorView): DecorationSet;
}

/**
 * List of Python built-in function names (158 functions)
 */
const builtins: string[];

Usage Examples:

import { pythonBuiltin, builtins } from "@jupyterlab/codemirror";
import { python } from "@codemirror/lang-python";

// Create Python language support
const pythonLang = python();

// Add Python built-in highlighting
const pythonBuiltinExtension = pythonBuiltin(pythonLang.language);

const editor = new EditorView({
  extensions: [
    pythonLang,
    pythonBuiltinExtension,
    // ... other extensions
  ]
});

// Check if function is built-in
function isPythonBuiltin(functionName: string): boolean {
  return builtins.includes(functionName);
}

// Get all Python built-ins
console.log(`Python has ${builtins.length} built-in functions`);
console.log('Built-ins include:', builtins.slice(0, 10).join(', '));

// Custom built-in highlighting
function createCustomPythonHighlighting(additionalBuiltins: string[]) {
  const allBuiltins = [...builtins, ...additionalBuiltins];
  
  return ViewPlugin.fromClass(class {
    constructor(view: EditorView) {
      // Custom highlighting logic for extended built-ins
    }
    
    update(update: ViewUpdate) {
      // Update highlighting when document changes
    }
  });
}

IPython Math Parsing

Mathematical expression parsing for IPython/Jupyter Markdown cells with LaTeX support.

/**
 * Define an IPython mathematical expression parser for Markdown
 * Enables LaTeX math rendering in Markdown cells
 */
function parseMathIPython(latexParser?: Parser): MarkdownConfig;

Usage Examples:

import { parseMathIPython } from "@jupyterlab/codemirror";
import { markdown } from "@codemirror/lang-markdown";

// Create IPython-compatible Markdown with math support
const ipythonMarkdown = markdown({
  extensions: [parseMathIPython()]
});

const editor = new EditorView({
  extensions: [
    ipythonMarkdown,
    // ... other extensions
  ]
});

// With custom LaTeX parser
import { LaTeX } from "@codemirror/lang-tex";

const customLatexParser = LaTeX.parser;
const ipythonMarkdownCustom = markdown({
  extensions: [parseMathIPython(customLatexParser)]
});

// Example IPython math content
const mathContent = `
# Mathematical Expressions

Inline math: $E = mc^2$

Block math:
$$
\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}
$$

IPython display math:
$$\\begin{align}
x &= \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\\\
y &= mx + b
\\end{align}$$
`;

// Set content with math expressions
editor.dispatch({
  changes: { from: 0, to: editor.state.doc.length, insert: mathContent }
});

Advanced Extension Combinations

Complex scenarios combining multiple special extensions.

// Collaborative Python development environment
async function createCollaborativePythonEditor(
  roomId: string,
  ytext: Text
): Promise<EditorView> {
  const pythonLang = python();
  const undoManager = new UndoManager(ytext);
  
  return new EditorView({
    extensions: [
      // Language support
      pythonLang,
      pythonBuiltin(pythonLang.language),
      
      // Collaboration
      ybinding({ ytext, undoManager }),
      
      // Visual aids
      rulers([79, 88]), // PEP 8 guidelines
      customTheme({
        fontFamily: 'JetBrains Mono, Monaco, monospace',
        fontSize: 13,
        lineHeight: 1.6
      }),
      
      // ... other extensions
    ],
    parent: document.body
  });
}

// Multi-language notebook cell
function createNotebookCell(language: string): Extension[] {
  const baseExtensions = [
    customTheme({
      fontFamily: 'var(--jp-code-font-family)',
      fontSize: null, // Use CSS variable
      lineHeight: null // Use CSS variable
    })
  ];
  
  switch (language) {
    case 'python':
      const pythonLang = python();
      return [
        ...baseExtensions,
        pythonLang,
        pythonBuiltin(pythonLang.language),
        rulers([79])
      ];
      
    case 'markdown':
      return [
        ...baseExtensions,
        markdown({ extensions: [parseMathIPython()] }),
        rulers([80])
      ];
      
    case 'javascript':
      return [
        ...baseExtensions,
        javascript(),
        rulers([80, 120])
      ];
      
    default:
      return baseExtensions;
  }
}

// Dynamic extension reconfiguration
function reconfigureSpecialExtensions(
  editor: EditorView,
  options: {
    collaboration?: { ytext: Text; undoManager?: UndoManager };
    rulers?: number[];
    customTheme?: CustomTheme;
    pythonBuiltins?: boolean;
    mathSupport?: boolean;
  }
) {
  const extensions: Extension[] = [];
  
  if (options.collaboration) {
    extensions.push(ybinding(options.collaboration));
  }
  
  if (options.rulers) {
    extensions.push(rulers(options.rulers));
  }
  
  if (options.customTheme) {
    extensions.push(customTheme(options.customTheme));
  }
  
  if (options.pythonBuiltins) {
    const pythonLang = python();
    extensions.push(pythonLang, pythonBuiltin(pythonLang.language));
  }
  
  if (options.mathSupport) {
    extensions.push(markdown({ extensions: [parseMathIPython()] }));
  }
  
  editor.dispatch({
    effects: StateEffect.reconfigure.of(extensions)
  });
}

Types

// Y.js types
interface ID {
  client: number;
  clock: number;
}

interface Position {
  type: ID | null;
  tname: string | null;
  item: ID | null;
  assoc: number;
}

interface Range {
  yanchor: Position;
  yhead: Position;
}

// Custom theme types
interface CustomTheme {
  fontFamily: string | null;
  fontSize: number | null;
  lineHeight: number | null;
}

// Y.js binding functions
function ybinding(options: { ytext: Text; undoManager?: UndoManager }): Extension;

// Ruler function
function rulers(positions: number[]): Extension;

// Custom theme function
function customTheme(config: CustomTheme): Extension;

// Python built-in highlighting
function pythonBuiltin(langPython: Language): ViewPlugin;

// IPython math parsing
function parseMathIPython(latexParser?: Parser): MarkdownConfig;

docs

editor-commands.md

editor-core.md

editor-factory.md

extension-system.md

index.md

language-support.md

mime-type-service.md

search-replace.md

special-extensions.md

theme-system.md

tile.json