0
# Text Operations
1
2
Text-based editing features for code and plain text modes including text selection management, cursor positioning, and text manipulation capabilities.
3
4
## Capabilities
5
6
### Get Text Selection
7
8
Retrieve the currently selected text with position information in code or text mode.
9
10
```javascript { .api }
11
/**
12
* Get the current selected text with selection range
13
* Only applicable for text and code modes
14
* @returns Selection object with start/end positions and selected text
15
*/
16
getTextSelection(): TextSelection;
17
18
interface TextSelection {
19
/** Selection start position */
20
start: { row: number; column: number };
21
22
/** Selection end position */
23
end: { row: number; column: number };
24
25
/** Selected text content */
26
text: string;
27
}
28
```
29
30
**Usage Example:**
31
32
```javascript
33
// Get current text selection
34
const selection = editor.getTextSelection();
35
36
if (selection.text) {
37
console.log(`Selected text: "${selection.text}"`);
38
console.log(`From (${selection.start.row}, ${selection.start.column})`);
39
console.log(`To (${selection.end.row}, ${selection.end.column})`);
40
} else {
41
console.log("No text selected");
42
}
43
```
44
45
### Set Text Selection
46
47
Programmatically set text selection to a specific range in code or text mode.
48
49
```javascript { .api }
50
/**
51
* Set text selection for a specific range
52
* Only applicable for text and code modes
53
* @param startPos - Selection start position
54
* @param endPos - Selection end position
55
*/
56
setTextSelection(startPos: Position, endPos: Position): void;
57
58
interface Position {
59
/** Row number (0-based) */
60
row: number;
61
62
/** Column number (0-based) */
63
column: number;
64
}
65
```
66
67
### Format JSON Text
68
69
Format the JSON text with proper indentation and line breaks for improved readability.
70
71
```javascript { .api }
72
/**
73
* Format the JSON text with proper indentation
74
* Only applicable for text and code modes
75
*/
76
format(): void;
77
```
78
79
**Usage Example:**
80
81
```javascript
82
// Format the current JSON content
83
editor.format();
84
85
// The editor will automatically format the JSON with proper indentation
86
// Invalid JSON will be left unchanged
87
```
88
89
### Compact JSON Text
90
91
Remove all unnecessary whitespace from the JSON text to minimize size.
92
93
```javascript { .api }
94
/**
95
* Compact the JSON text by removing whitespace
96
* Only applicable for text and code modes
97
*/
98
compact(): void;
99
```
100
101
**Usage Example:**
102
103
```javascript
104
// Compact the JSON to remove all whitespace
105
editor.compact();
106
107
// This reduces the JSON to its minimal representation
108
// Invalid JSON will be left unchanged
109
```
110
111
### Repair JSON Text
112
113
Attempt to automatically repair invalid JSON by fixing common syntax errors.
114
115
```javascript { .api }
116
/**
117
* Attempt to repair invalid JSON syntax
118
* Only applicable for text and code modes
119
*/
120
repair(): void;
121
```
122
123
**Usage Example:**
124
125
```javascript
126
// Try to repair invalid JSON
127
editor.repair();
128
129
// Common repairs include:
130
// - Adding missing quotes around property names
131
// - Fixing trailing commas
132
// - Correcting bracket/brace mismatches
133
// - Converting single quotes to double quotes
134
```
135
136
### Resize Editor
137
138
Force the editor to recalculate and adjust its size, useful after container size changes.
139
140
```javascript { .api }
141
/**
142
* Resize the editor to fit its container
143
* Only applicable for code mode (Ace editor)
144
* @param force - Force resize even if size hasn't changed
145
*/
146
resize(force?: boolean): void;
147
```
148
149
**Usage Example:**
150
151
```javascript
152
// Resize editor after container size change
153
editor.resize();
154
155
// Force resize regardless of detected size change
156
editor.resize(true);
157
158
// Useful when:
159
// - Container is resized dynamically
160
// - Editor is shown/hidden with CSS
161
// - Parent container dimensions change
162
```
163
164
**Usage Example:**
165
166
```javascript
167
// Select text from line 2, column 5 to line 4, column 10
168
editor.setTextSelection(
169
{ row: 2, column: 5 },
170
{ row: 4, column: 10 }
171
);
172
173
// Select entire line 3 (assuming line has content)
174
editor.setTextSelection(
175
{ row: 3, column: 0 },
176
{ row: 4, column: 0 }
177
);
178
179
// Position cursor at specific location (no selection)
180
editor.setTextSelection(
181
{ row: 1, column: 8 },
182
{ row: 1, column: 8 }
183
);
184
```
185
186
### Text Selection Change Events
187
188
Handle text selection changes with event callbacks to respond to user text selection.
189
190
```javascript { .api }
191
/**
192
* Text selection change callback in editor options
193
*/
194
interface TextSelectionCallbacks {
195
onTextSelectionChange?: (
196
start: { row: number; column: number },
197
end: { row: number; column: number },
198
text: string
199
) => void;
200
}
201
```
202
203
**Usage Example:**
204
205
```javascript
206
const options = {
207
mode: "code",
208
onTextSelectionChange: (start, end, text) => {
209
const hasSelection = text.length > 0;
210
211
if (hasSelection) {
212
console.log(`Selected: "${text}"`);
213
console.log(`Lines ${start.row + 1}-${end.row + 1}`);
214
215
// Update UI for text selection
216
document.getElementById('selection-info').textContent =
217
`${text.length} characters selected`;
218
219
// Enable text-based actions
220
document.getElementById('format-selection').disabled = false;
221
} else {
222
console.log(`Cursor at line ${start.row + 1}, column ${start.column + 1}`);
223
224
// Update cursor position display
225
document.getElementById('cursor-info').textContent =
226
`Line ${start.row + 1}, Col ${start.column + 1}`;
227
228
// Disable selection-based actions
229
document.getElementById('format-selection').disabled = true;
230
}
231
}
232
};
233
234
const editor = new JSONEditor(container, options);
235
```
236
237
## Text Mode Features
238
239
### Plain Text Editing
240
241
Text mode provides a simple text area for JSON editing without syntax highlighting.
242
243
```javascript { .api }
244
// Text mode configuration
245
const textOptions = {
246
mode: "text",
247
indentation: 2, // Spaces for JSON formatting
248
statusBar: true, // Show status bar with cursor position
249
mainMenuBar: true, // Show menu with format/validate buttons
250
escapeUnicode: false // Display unicode characters normally
251
};
252
```
253
254
**Features:**
255
- JSON formatting and validation
256
- Find and replace functionality
257
- Undo/redo support
258
- JSON repair capabilities
259
- Schema validation with error highlighting
260
261
### Code Mode Features
262
263
Code mode provides an advanced code editor powered by Ace with syntax highlighting.
264
265
```javascript { .api }
266
// Code mode configuration
267
const codeOptions = {
268
mode: "code",
269
theme: "ace/theme/jsoneditor", // Ace editor theme
270
indentation: 2, // Spaces for indentation
271
ace: customAceInstance, // Custom Ace editor instance (optional)
272
allowSchemaSuggestions: true // Enable schema-based autocomplete
273
};
274
```
275
276
**Features:**
277
- Syntax highlighting for JSON
278
- Code folding and bracket matching
279
- Multiple cursors and selections
280
- Find and replace with regex support
281
- Extensive keyboard shortcuts
282
- Auto-completion based on JSON schema
283
- Error annotations in gutter
284
285
## Advanced Text Operations
286
287
### Find and Replace
288
289
Built-in search functionality available in both text and code modes.
290
291
```javascript
292
// Text mode: Basic find functionality
293
// Code mode: Advanced find/replace via Ace editor
294
// - Ctrl+F: Find
295
// - Ctrl+H: Replace
296
// - Ctrl+G: Go to line
297
// - F3/Shift+F3: Find next/previous
298
```
299
300
### Text Formatting
301
302
Format and compact JSON text programmatically.
303
304
```javascript
305
// Get current text
306
const currentText = editor.getText();
307
308
// Format JSON with indentation
309
try {
310
const parsed = JSON.parse(currentText);
311
const formatted = JSON.stringify(parsed, null, 2);
312
editor.setText(formatted);
313
} catch (error) {
314
console.error("Invalid JSON:", error.message);
315
}
316
317
// Compact JSON (remove whitespace)
318
try {
319
const parsed = JSON.parse(currentText);
320
const compacted = JSON.stringify(parsed);
321
editor.setText(compacted);
322
} catch (error) {
323
console.error("Invalid JSON:", error.message);
324
}
325
```
326
327
### Text Selection Utilities
328
329
Helper functions for working with text selections.
330
331
```javascript
332
function getSelectedLines(editor) {
333
const selection = editor.getTextSelection();
334
const lines = [];
335
336
for (let row = selection.start.row; row <= selection.end.row; row++) {
337
lines.push(row);
338
}
339
340
return lines;
341
}
342
343
function selectWord(editor, row, column) {
344
const text = editor.getText();
345
const lines = text.split('\n');
346
347
if (row >= lines.length) return;
348
349
const line = lines[row];
350
let start = column;
351
let end = column;
352
353
// Find word boundaries
354
const wordPattern = /[a-zA-Z0-9_]/;
355
356
while (start > 0 && wordPattern.test(line[start - 1])) {
357
start--;
358
}
359
360
while (end < line.length && wordPattern.test(line[end])) {
361
end++;
362
}
363
364
editor.setTextSelection(
365
{ row, column: start },
366
{ row, column: end }
367
);
368
}
369
370
function insertTextAtCursor(editor, textToInsert) {
371
const selection = editor.getTextSelection();
372
const currentText = editor.getText();
373
const lines = currentText.split('\n');
374
375
// Insert text at cursor position
376
const line = lines[selection.start.row];
377
const before = line.substring(0, selection.start.column);
378
const after = line.substring(selection.end.column);
379
380
lines[selection.start.row] = before + textToInsert + after;
381
382
editor.setText(lines.join('\n'));
383
384
// Position cursor after inserted text
385
const newColumn = selection.start.column + textToInsert.length;
386
editor.setTextSelection(
387
{ row: selection.start.row, column: newColumn },
388
{ row: selection.start.row, column: newColumn }
389
);
390
}
391
```
392
393
### Keyboard Shortcuts
394
395
Built-in keyboard shortcuts for text operations:
396
397
**Text Mode:**
398
- `Ctrl+A`: Select all
399
- `Ctrl+Z`: Undo
400
- `Ctrl+Y`: Redo
401
- `Ctrl+F`: Find
402
- `Tab`: Indent selection
403
- `Shift+Tab`: Unindent selection
404
405
**Code Mode (Ace Editor):**
406
- `Ctrl+D`: Select next occurrence
407
- `Ctrl+Shift+D`: Select all occurrences
408
- `Alt+Click`: Add cursor
409
- `Ctrl+Shift+K`: Delete line
410
- `Ctrl+/`: Toggle comment
411
- `Ctrl+Shift+F`: Find and replace
412
- `Ctrl+G`: Go to line
413
- `Ctrl+Shift+L`: Select all occurrences of selection
414
415
## Text Mode Configuration
416
417
### Status Bar Information
418
419
The status bar shows useful information in text and code modes:
420
421
```javascript
422
const options = {
423
mode: "text", // or "code"
424
statusBar: true, // Enable status bar
425
426
// Status bar shows:
427
// - Current cursor position (line, column)
428
// - Selected character count
429
// - Total document size
430
// - JSON validation status
431
};
432
```
433
434
### Error Display
435
436
Configure how text parsing and validation errors are displayed:
437
438
```javascript
439
const options = {
440
mode: "text",
441
442
// Show error table for validation errors
443
showErrorTable: true,
444
445
// Handle parse errors
446
onError: (error) => {
447
console.error("JSON parsing error:", error.message);
448
449
// Custom error display
450
showNotification(`Invalid JSON: ${error.message}`, 'error');
451
}
452
};
453
```
454
455
### Text Editor Customization
456
457
```javascript
458
const options = {
459
mode: "code",
460
461
// Ace editor theme
462
theme: "ace/theme/monokai",
463
464
// Custom Ace configuration
465
ace: customAceInstance,
466
467
// Text selection callback
468
onTextSelectionChange: (start, end, text) => {
469
// Custom selection handling
470
handleTextSelection(start, end, text);
471
},
472
473
// Enable schema autocomplete
474
allowSchemaSuggestions: true,
475
schema: jsonSchema
476
};
477
```