CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jsoneditor

A web-based tool to view, edit, format, and validate JSON with multiple editing modes including tree, code, text, and preview

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

text-operations.mddocs/

Text Operations

Text-based editing features for code and plain text modes including text selection management, cursor positioning, and text manipulation capabilities.

Capabilities

Get Text Selection

Retrieve the currently selected text with position information in code or text mode.

/**
 * Get the current selected text with selection range
 * Only applicable for text and code modes
 * @returns Selection object with start/end positions and selected text
 */
getTextSelection(): TextSelection;

interface TextSelection {
  /** Selection start position */
  start: { row: number; column: number };
  
  /** Selection end position */
  end: { row: number; column: number };
  
  /** Selected text content */
  text: string;
}

Usage Example:

// Get current text selection
const selection = editor.getTextSelection();

if (selection.text) {
  console.log(`Selected text: "${selection.text}"`);
  console.log(`From (${selection.start.row}, ${selection.start.column})`);
  console.log(`To (${selection.end.row}, ${selection.end.column})`);
} else {
  console.log("No text selected");
}

Set Text Selection

Programmatically set text selection to a specific range in code or text mode.

/**
 * Set text selection for a specific range
 * Only applicable for text and code modes
 * @param startPos - Selection start position
 * @param endPos - Selection end position
 */
setTextSelection(startPos: Position, endPos: Position): void;

interface Position {
  /** Row number (0-based) */
  row: number;
  
  /** Column number (0-based) */
  column: number;
}

Format JSON Text

Format the JSON text with proper indentation and line breaks for improved readability.

/**
 * Format the JSON text with proper indentation
 * Only applicable for text and code modes
 */
format(): void;

Usage Example:

// Format the current JSON content
editor.format();

// The editor will automatically format the JSON with proper indentation
// Invalid JSON will be left unchanged

Compact JSON Text

Remove all unnecessary whitespace from the JSON text to minimize size.

/**
 * Compact the JSON text by removing whitespace
 * Only applicable for text and code modes
 */
compact(): void;

Usage Example:

// Compact the JSON to remove all whitespace
editor.compact();

// This reduces the JSON to its minimal representation
// Invalid JSON will be left unchanged

Repair JSON Text

Attempt to automatically repair invalid JSON by fixing common syntax errors.

/**
 * Attempt to repair invalid JSON syntax
 * Only applicable for text and code modes
 */
repair(): void;

Usage Example:

// Try to repair invalid JSON
editor.repair();

// Common repairs include:
// - Adding missing quotes around property names
// - Fixing trailing commas
// - Correcting bracket/brace mismatches
// - Converting single quotes to double quotes

Resize Editor

Force the editor to recalculate and adjust its size, useful after container size changes.

/**
 * Resize the editor to fit its container
 * Only applicable for code mode (Ace editor)
 * @param force - Force resize even if size hasn't changed
 */
resize(force?: boolean): void;

Usage Example:

// Resize editor after container size change
editor.resize();

// Force resize regardless of detected size change
editor.resize(true);

// Useful when:
// - Container is resized dynamically
// - Editor is shown/hidden with CSS
// - Parent container dimensions change

Usage Example:

// Select text from line 2, column 5 to line 4, column 10
editor.setTextSelection(
  { row: 2, column: 5 },
  { row: 4, column: 10 }
);

// Select entire line 3 (assuming line has content)
editor.setTextSelection(
  { row: 3, column: 0 },
  { row: 4, column: 0 }
);

// Position cursor at specific location (no selection)
editor.setTextSelection(
  { row: 1, column: 8 },
  { row: 1, column: 8 }
);

Text Selection Change Events

Handle text selection changes with event callbacks to respond to user text selection.

/**
 * Text selection change callback in editor options
 */
interface TextSelectionCallbacks {
  onTextSelectionChange?: (
    start: { row: number; column: number },
    end: { row: number; column: number },
    text: string
  ) => void;
}

Usage Example:

const options = {
  mode: "code",
  onTextSelectionChange: (start, end, text) => {
    const hasSelection = text.length > 0;
    
    if (hasSelection) {
      console.log(`Selected: "${text}"`);
      console.log(`Lines ${start.row + 1}-${end.row + 1}`);
      
      // Update UI for text selection
      document.getElementById('selection-info').textContent = 
        `${text.length} characters selected`;
        
      // Enable text-based actions
      document.getElementById('format-selection').disabled = false;
    } else {
      console.log(`Cursor at line ${start.row + 1}, column ${start.column + 1}`);
      
      // Update cursor position display
      document.getElementById('cursor-info').textContent = 
        `Line ${start.row + 1}, Col ${start.column + 1}`;
        
      // Disable selection-based actions
      document.getElementById('format-selection').disabled = true;
    }
  }
};

const editor = new JSONEditor(container, options);

Text Mode Features

Plain Text Editing

Text mode provides a simple text area for JSON editing without syntax highlighting.

// Text mode configuration
const textOptions = {
  mode: "text",
  indentation: 2,        // Spaces for JSON formatting
  statusBar: true,       // Show status bar with cursor position  
  mainMenuBar: true,     // Show menu with format/validate buttons
  escapeUnicode: false   // Display unicode characters normally
};

Features:

  • JSON formatting and validation
  • Find and replace functionality
  • Undo/redo support
  • JSON repair capabilities
  • Schema validation with error highlighting

Code Mode Features

Code mode provides an advanced code editor powered by Ace with syntax highlighting.

// Code mode configuration  
const codeOptions = {
  mode: "code",
  theme: "ace/theme/jsoneditor", // Ace editor theme
  indentation: 2,                // Spaces for indentation
  ace: customAceInstance,        // Custom Ace editor instance (optional)
  allowSchemaSuggestions: true   // Enable schema-based autocomplete
};

Features:

  • Syntax highlighting for JSON
  • Code folding and bracket matching
  • Multiple cursors and selections
  • Find and replace with regex support
  • Extensive keyboard shortcuts
  • Auto-completion based on JSON schema
  • Error annotations in gutter

Advanced Text Operations

Find and Replace

Built-in search functionality available in both text and code modes.

// Text mode: Basic find functionality
// Code mode: Advanced find/replace via Ace editor
// - Ctrl+F: Find
// - Ctrl+H: Replace  
// - Ctrl+G: Go to line
// - F3/Shift+F3: Find next/previous

Text Formatting

Format and compact JSON text programmatically.

// Get current text
const currentText = editor.getText();

// Format JSON with indentation
try {
  const parsed = JSON.parse(currentText);
  const formatted = JSON.stringify(parsed, null, 2);
  editor.setText(formatted);
} catch (error) {
  console.error("Invalid JSON:", error.message);
}

// Compact JSON (remove whitespace)
try {
  const parsed = JSON.parse(currentText);
  const compacted = JSON.stringify(parsed);
  editor.setText(compacted);
} catch (error) {
  console.error("Invalid JSON:", error.message);
}

Text Selection Utilities

Helper functions for working with text selections.

function getSelectedLines(editor) {
  const selection = editor.getTextSelection();
  const lines = [];
  
  for (let row = selection.start.row; row <= selection.end.row; row++) {
    lines.push(row);
  }
  
  return lines;
}

function selectWord(editor, row, column) {
  const text = editor.getText();
  const lines = text.split('\n');
  
  if (row >= lines.length) return;
  
  const line = lines[row];
  let start = column;
  let end = column;
  
  // Find word boundaries
  const wordPattern = /[a-zA-Z0-9_]/;
  
  while (start > 0 && wordPattern.test(line[start - 1])) {
    start--;
  }
  
  while (end < line.length && wordPattern.test(line[end])) {
    end++;
  }
  
  editor.setTextSelection(
    { row, column: start },
    { row, column: end }
  );
}

function insertTextAtCursor(editor, textToInsert) {
  const selection = editor.getTextSelection();
  const currentText = editor.getText();
  const lines = currentText.split('\n');
  
  // Insert text at cursor position
  const line = lines[selection.start.row];
  const before = line.substring(0, selection.start.column);
  const after = line.substring(selection.end.column);
  
  lines[selection.start.row] = before + textToInsert + after;
  
  editor.setText(lines.join('\n'));
  
  // Position cursor after inserted text
  const newColumn = selection.start.column + textToInsert.length;
  editor.setTextSelection(
    { row: selection.start.row, column: newColumn },
    { row: selection.start.row, column: newColumn }
  );
}

Keyboard Shortcuts

Built-in keyboard shortcuts for text operations:

Text Mode:

  • Ctrl+A: Select all
  • Ctrl+Z: Undo
  • Ctrl+Y: Redo
  • Ctrl+F: Find
  • Tab: Indent selection
  • Shift+Tab: Unindent selection

Code Mode (Ace Editor):

  • Ctrl+D: Select next occurrence
  • Ctrl+Shift+D: Select all occurrences
  • Alt+Click: Add cursor
  • Ctrl+Shift+K: Delete line
  • Ctrl+/: Toggle comment
  • Ctrl+Shift+F: Find and replace
  • Ctrl+G: Go to line
  • Ctrl+Shift+L: Select all occurrences of selection

Text Mode Configuration

Status Bar Information

The status bar shows useful information in text and code modes:

const options = {
  mode: "text", // or "code"
  statusBar: true, // Enable status bar
  
  // Status bar shows:
  // - Current cursor position (line, column)
  // - Selected character count
  // - Total document size
  // - JSON validation status
};

Error Display

Configure how text parsing and validation errors are displayed:

const options = {
  mode: "text",
  
  // Show error table for validation errors
  showErrorTable: true,
  
  // Handle parse errors
  onError: (error) => {
    console.error("JSON parsing error:", error.message);
    
    // Custom error display
    showNotification(`Invalid JSON: ${error.message}`, 'error');
  }
};

Text Editor Customization

const options = {
  mode: "code",
  
  // Ace editor theme
  theme: "ace/theme/monokai",
  
  // Custom Ace configuration
  ace: customAceInstance,
  
  // Text selection callback
  onTextSelectionChange: (start, end, text) => {
    // Custom selection handling
    handleTextSelection(start, end, text);
  },
  
  // Enable schema autocomplete
  allowSchemaSuggestions: true,
  schema: jsonSchema
};

docs

configuration.md

editor-core.md

index.md

mode-management.md

preview-mode.md

schema-validation.md

text-operations.md

transform-operations.md

tree-operations.md

tile.json