### Implementing a Custom Lexer and SyntaxKit in Java Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This example demonstrates how to implement the Lexer interface to parse a simple markup language. It also shows how to create a corresponding SyntaxKit and register it with the JSyntaxPane framework for use in a JEditorPane. ```java import javax.swing.*; import javax.swing.text.Segment; import jsyntaxpane.*; import java.util.List; import java.util.ArrayList; class SimpleMarkupLexer implements Lexer { @Override public void parse(Segment segment, int offset, List tokens) { char[] text = segment.array; int start = segment.offset; int end = segment.offset + segment.count; int tokenStart = start; boolean inTag = false; boolean inString = false; for (int i = start; i < end; i++) { char c = text[i]; if (inString) { if (c == '"') { tokens.add(new Token(TokenType.STRING, tokenStart - start + offset, i - tokenStart + 1)); inString = false; tokenStart = i + 1; } } else if (inTag) { if (c == '"') { if (i > tokenStart) { tokens.add(new Token(TokenType.KEYWORD, tokenStart - start + offset, i - tokenStart)); } tokenStart = i; inString = true; } else if (c == '>') { tokens.add(new Token(TokenType.KEYWORD, tokenStart - start + offset, i - tokenStart + 1)); inTag = false; tokenStart = i + 1; } } else { if (c == '<') { if (i > tokenStart) { tokens.add(new Token(TokenType.DEFAULT, tokenStart - start + offset, i - tokenStart)); } tokenStart = i; inTag = true; } } } if (tokenStart < end) { TokenType type = inTag ? TokenType.KEYWORD : (inString ? TokenType.STRING : TokenType.DEFAULT); tokens.add(new Token(type, tokenStart - start + offset, end - tokenStart)); } } } class SimpleMarkupSyntaxKit extends DefaultSyntaxKit { public SimpleMarkupSyntaxKit() { super(new SimpleMarkupLexer()); } } public class CustomLexerExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); DefaultSyntaxKit.registerContentType("text/simplemarkup", SimpleMarkupSyntaxKit.class.getName()); JFrame frame = new JFrame("Custom Lexer Example"); JEditorPane editor = new JEditorPane(); editor.setEditorKit(new SimpleMarkupSyntaxKit()); editor.setText("\n Hello World\n \n This is plain text content.\n Important!\n \n"); frame.add(new JScrollPane(editor)); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Customize Syntax Styles in Java Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This example demonstrates how to initialize the DefaultSyntaxKit and apply custom color and font styles to various token types. It shows both the Properties-based approach for bulk updates and the programmatic approach for individual token types. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxStyle; import jsyntaxpane.SyntaxStyles; import jsyntaxpane.TokenType; import java.awt.Color; import java.awt.Font; import java.util.Properties; public class CustomStylesExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); SyntaxStyles styles = SyntaxStyles.getInstance(); Properties customStyles = new Properties(); customStyles.setProperty("KEYWORD", "0x0000CC, 1"); customStyles.setProperty("KEYWORD2", "0x660099, 1"); customStyles.setProperty("STRING", "0x008800, 0"); customStyles.setProperty("STRING2", "0x008800, 2"); customStyles.setProperty("COMMENT", "0x808080, 2"); customStyles.setProperty("COMMENT2", "0x808080, 3"); customStyles.setProperty("NUMBER", "0xFF6600, 0"); customStyles.setProperty("OPERATOR", "0x000000, 1"); customStyles.setProperty("TYPE", "0x006699, 0"); customStyles.setProperty("IDENTIFIER", "0x000000, 0"); styles.mergeStyles(customStyles); styles.put(TokenType.ERROR, new SyntaxStyle(Color.RED, Font.BOLD)); styles.put(TokenType.WARNING, new SyntaxStyle(new Color(0xFF8800), Font.ITALIC)); JFrame frame = new JFrame("Custom Styles Example"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setBackground(new Color(0xFAFAFA)); editor.setText("package com.example;\n\n// This is a comment\n/* Multi-line\n comment */\n\npublic class CustomStyleDemo {\n private static final int MAX_VALUE = 100;\n private String message = \"Hello World\";\n\n public void process(List items) {\n for (String item : items) {\n System.out.println(item);\n }\n }\n}"); frame.add(new JScrollPane(editor)); frame.setSize(700, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Directly Install JavaSyntaxKit on JEditorPane Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates how to bypass content types and directly set a JavaSyntaxKit on a JEditorPane for enhanced control and customization. This allows for direct access to the kit's methods. It requires the jsyntaxpane library. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.syntaxkits.JavaSyntaxKit; public class EditorKitExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Java Editor"); JEditorPane editor = new JEditorPane(); // Create and set the Java syntax kit directly JavaSyntaxKit kit = new JavaSyntaxKit(); editor.setEditorKit(kit); // Set some sample Java code editor.setText( "package com.example;\n\n" + "import java.util.List;\n" + "import java.util.ArrayList;\n\n" + "/**\n" + " * Example class demonstrating syntax highlighting.\n" + " */\n" + "public class Example {\n" + " private List items = new ArrayList<>();\n\n" + " public void addItem(String item) {\n" + " if (item != null && !item.isEmpty()) {\n" + " items.add(item);\n" + " }\n" + " }\n" + "}" ); frame.add(new JScrollPane(editor)); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Enable Syntax Highlighting by Content Type Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates how to apply syntax highlighting to a JEditorPane by setting its content type. This example shows multiple language editors including Java, Python, SQL, and JavaScript within a tabbed interface. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; public class ContentTypeExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Multi-Language Editor"); JTabbedPane tabs = new JTabbedPane(); JEditorPane javaEditor = new JEditorPane(); javaEditor.setContentType("text/java"); javaEditor.setText("public class Example {\n private int count = 0;\n}"); tabs.addTab("Java", new JScrollPane(javaEditor)); JEditorPane pythonEditor = new JEditorPane(); pythonEditor.setContentType("text/python"); pythonEditor.setText("def hello(name):\n print(f'Hello, {name}!')\n\nhello('World')"); tabs.addTab("Python", new JScrollPane(pythonEditor)); JEditorPane sqlEditor = new JEditorPane(); sqlEditor.setContentType("text/sql"); sqlEditor.setText("SELECT id, name, email\nFROM users\nWHERE active = 1\nORDER BY name ASC;"); tabs.addTab("SQL", new JScrollPane(sqlEditor)); JEditorPane jsEditor = new JEditorPane(); jsEditor.setContentType("text/javascript"); jsEditor.setText("function greet(name) {\n return `Hello, ${name}!`;\n}\nconsole.log(greet('World'));"); tabs.addTab("JavaScript", new JScrollPane(jsEditor)); frame.add(tabs); frame.setSize(700, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### jsyntaxpane Loop Example Source: https://github.com/nordfalk/jsyntaxpane/blob/master/jsyntaxpane/src/main/resources/META-INF/services/jsyntaxpane/syntaxkits/javasyntaxkit/combocompletions.txt Illustrates a basic for loop structure commonly used in programming, applicable within jsyntaxpane contexts. ```APIDOC ## Basic For Loop ### Description This example demonstrates a standard for loop structure, useful for iterating a specific number of times. This pattern can be adapted for various programming tasks within jsyntaxpane. ### Method N/A (Illustrative example) ### Endpoint N/A ### Parameters #### Query Parameters - **max** (integer) - Required - The maximum number of iterations for the loop. ### Request Example ```java for(int i=0; i < max; i++) { // loop body } ``` ### Response #### Success Response (200) N/A (Illustrative example) #### Response Example N/A ``` -------------------------------- ### Build a Complete Code Editor with JSyntaxPane Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This example demonstrates the integration of JSyntaxPane into a JFrame. It includes a menu bar for file operations, a toolbar for language selection and syntax actions, and a status bar for tracking caret position. ```java import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.*; import java.io.*; import java.nio.file.*; import jsyntaxpane.*; import jsyntaxpane.actions.*; public class CompleteEditorExample { private JFrame frame; private JEditorPane editor; private JComboBox languageCombo; private JLabel statusLabel; private File currentFile; public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); new CompleteEditorExample().createAndShow(); }); } private void createAndShow() { frame = new JFrame("JSyntaxPane Editor"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); editor = new JEditorPane(); editor.setContentType("text/java"); editor.setFont(new Font("Monospaced", Font.PLAIN, 14)); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.add(createMenuItem("New", KeyEvent.VK_N, e -> newFile())); fileMenu.add(createMenuItem("Open...", KeyEvent.VK_O, e -> openFile())); fileMenu.add(createMenuItem("Save", KeyEvent.VK_S, e -> saveFile())); fileMenu.add(createMenuItem("Save As...", KeyEvent.VK_A, e -> saveFileAs())); fileMenu.addSeparator(); fileMenu.add(createMenuItem("Exit", KeyEvent.VK_Q, e -> System.exit(0))); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.add(createMenuItem("Undo", KeyEvent.VK_Z, e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null && doc.canUndo()) doc.doUndo(); })); editMenu.add(createMenuItem("Redo", KeyEvent.VK_Y, e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null && doc.canRedo()) doc.doRedo(); })); menuBar.add(editMenu); frame.setJMenuBar(menuBar); JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); toolbar.add(new JLabel("Language: ")); languageCombo = new JComboBox<>(DefaultSyntaxKit.getContentTypes()); languageCombo.setSelectedItem("text/java"); languageCombo.setMaximumSize(new Dimension(150, 30)); languageCombo.addActionListener(e -> changeLanguage()); toolbar.add(languageCombo); toolbar.addSeparator(); DefaultSyntaxKit kit = (DefaultSyntaxKit) editor.getEditorKit(); kit.addToolBarActions(editor, toolbar); frame.add(toolbar, BorderLayout.NORTH); frame.add(new JScrollPane(editor), BorderLayout.CENTER); JPanel statusBar = new JPanel(new BorderLayout()); statusLabel = new JLabel("Ready"); statusBar.add(statusLabel, BorderLayout.WEST); JLabel positionLabel = new JLabel("Line: 1, Col: 1"); statusBar.add(positionLabel, BorderLayout.EAST); statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5)); editor.addCaretListener(e -> { try { int pos = e.getDot(); int line = ActionUtils.getLineNumber(editor, pos) + 1; int col = ActionUtils.getColumnNumber(editor, pos) + 1; positionLabel.setText(String.format("Line: %d, Col: %d", line, col)); } catch (Exception ex) {} }); frame.add(statusBar, BorderLayout.SOUTH); frame.setSize(900, 700); frame.setLocationRelativeTo(null); frame.setVisible(true); } private JMenuItem createMenuItem(String text, int keyCode, ActionListener action) { JMenuItem item = new JMenuItem(text); item.addActionListener(action); return item; } } ``` -------------------------------- ### Java SyntaxDocument Line Operations Example Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates how to use SyntaxDocument's getLineAt, removeLineAt, and replaceLineAt methods in a Swing application. It allows users to interactively get, delete, or replace the current line in a text editor, and also displays information about the current line and document. ```Java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.actions.ActionUtils; import javax.swing.text.BadLocationException; public class LineOperationsExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Line Operations"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText( "Line 1: First line\n" + "Line 2: Second line\n" + "Line 3: Third line\n" + "Line 4: Fourth line\n" + "Line 5: Fifth line" ); JButton getLineBtn = new JButton("Get Current Line"); getLineBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { try { int pos = editor.getCaretPosition(); String line = doc.getLineAt(pos); int lineNum = doc.getLineNumberAt(pos); JOptionPane.showMessageDialog(frame, String.format("Line %d: %s", lineNum + 1, line)); } catch (BadLocationException ex) { ex.printStackTrace(); } } }); JButton deleteLineBtn = new JButton("Delete Current Line"); deleteLineBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { try { int pos = editor.getCaretPosition(); doc.removeLineAt(pos); } catch (BadLocationException ex) { ex.printStackTrace(); } } }); JButton replaceLineBtn = new JButton("Replace Current Line"); replaceLineBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { String newText = JOptionPane.showInputDialog(frame, "Enter replacement text:", "REPLACED LINE"); if (newText != null) { try { int pos = editor.getCaretPosition(); doc.replaceLineAt(pos, newText + "\n"); } catch (BadLocationException ex) { ex.printStackTrace(); } } } }); JButton lineInfoBtn = new JButton("Show Line Info"); lineInfoBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { int pos = editor.getCaretPosition(); int lineCount = doc.getLineCount(); int currentLine = doc.getLineNumberAt(pos); int lineStart = doc.getLineStartOffset(pos); int lineEnd = doc.getLineEndOffset(pos); JOptionPane.showMessageDialog(frame, String.format( "Total lines: %d%n" + "Current line: %d%n" + "Line start offset: %d%n" + "Line end offset: %d", lineCount, currentLine + 1, lineStart, lineEnd )); } }); JToolBar toolbar = new JToolBar(); toolbar.add(getLineBtn); toolbar.add(deleteLineBtn); toolbar.add(replaceLineBtn); toolbar.add(lineInfoBtn); frame.add(toolbar, java.awt.BorderLayout.NORTH); frame.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Analyze Token Types in Java using jsyntaxpane Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This Java code snippet demonstrates how to use jsyntaxpane to parse a Java code string, iterate through its tokens, count the occurrences of each TokenType, and display example tokens. It also shows how to use helper methods like TokenType.isComment() and TokenType.isKeyword() on individual tokens. This example requires the jsyntaxpane library. ```java import javax.swing.*; import jsyntaxpane.*; import jsyntaxpane.actions.ActionUtils; import java.util.Iterator; import java.util.HashMap; import java.util.Map; public class TokenTypeExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Token Types Example"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText( "// Comment example\n" + "public class Demo {\n" + " private String message = \"Hello\";\n" + " private int count = 42;\n" + " \n" + " public void test() {\n" + " if (count > 0) {\n" + " System.out.println(message);\n" + " }\n" + " }\n" + "}" ); JTextArea statsArea = new JTextArea(10, 30); statsArea.setEditable(false); JButton analyzeBtn = new JButton("Analyze Token Types"); analyzeBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { Map tokenCounts = new HashMap<>(); Map tokenExamples = new HashMap<>(); Iterator tokens = doc.getTokens(0, doc.getLength()); while (tokens.hasNext()) { Token t = tokens.next(); tokenCounts.merge(t.type, 1, Integer::sum); // Collect first example of each type if (!tokenExamples.containsKey(t.type)) { String text = t.getString(doc).trim(); if (!text.isEmpty() && text.length() < 20) { tokenExamples.put(t.type, new StringBuilder(text)); } } } StringBuilder stats = new StringBuilder("Token Analysis:\n\n"); for (TokenType type : TokenType.values()) { int count = tokenCounts.getOrDefault(type, 0); if (count > 0) { String example = tokenExamples.containsKey(type) ? " (e.g., \"" + tokenExamples.get(type) + "\")" : ""; stats.append(String.format("% -12s: %3d%s%n", type, count, example)); } } // Token type helper methods stats.append("\n--- Token Type Checks ---\n"); Token firstToken = doc.getTokenAt(0); if (firstToken != null) { stats.append(String.format("First token '%s':%n", firstToken.getString(doc).trim())); stats.append(String.format(" isComment: %b%n", TokenType.isComment(firstToken))); stats.append(String.format(" isKeyword: %b%n", TokenType.isKeyword(firstToken))); stats.append(String.format(" isString: %b%n", TokenType.isString(firstToken))); } statsArea.setText(stats.toString()); } }); JPanel panel = new JPanel(new java.awt.BorderLayout()); panel.add(analyzeBtn, java.awt.BorderLayout.NORTH); panel.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); panel.add(new JScrollPane(statsArea), java.awt.BorderLayout.EAST); frame.add(panel); frame.setSize(900, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### JEditorPane Text Manipulation and Information Retrieval (Java) Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates how to use ActionUtils to get line and column numbers, retrieve the current line's content, and count total lines in a JEditorPane. It also shows how to insert text with cursor positioning markers and extract selected lines. ```Java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.actions.ActionUtils; import javax.swing.text.BadLocationException; public class ActionUtilsExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("ActionUtils Example"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText( "public class Demo {\n" + " public void method() {\n" + " System.out.println(\"Hello\");\n" + " }\n" + "}" ); JLabel infoLabel = new JLabel("Caret info will appear here"); // Display line and column information on caret movement editor.addCaretListener(e -> { try { int pos = e.getDot(); int line = ActionUtils.getLineNumber(editor, pos); int column = ActionUtils.getColumnNumber(editor, pos); String currentLine = ActionUtils.getLine(editor); int lineCount = ActionUtils.getLineCount(editor); infoLabel.setText(String.format( "Line: %d/%d, Column: %d | Current line: %s", line + 1, lineCount, column + 1, currentLine.length() > 30 ? currentLine.substring(0, 30) + "..." : currentLine )); } catch (BadLocationException ex) { infoLabel.setText("Error: " + ex.getMessage()); } }); // Button to insert template with cursor positioning JButton insertBtn = new JButton("Insert For Loop"); insertBtn.addActionListener(e -> { // The | character marks where cursor will be placed after insertion String template = "for (int i = 0; i < |; i++) {\n \n}"; ActionUtils.insertMagicString(editor, template); editor.requestFocusInWindow(); }); // Button to get selected lines JButton getLinesBtn = new JButton("Get Selected Lines"); getLinesBtn.addActionListener(e -> { String[] lines = ActionUtils.getSelectedLines(editor); System.out.println("Selected lines:"); for (int i = 0; i < lines.length; i++) { System.out.printf(" %d: %s%n", i + 1, lines[i]); } }); JToolBar toolbar = new JToolBar(); toolbar.add(insertBtn); toolbar.add(getLinesBtn); JPanel panel = new JPanel(new java.awt.BorderLayout()); panel.add(toolbar, java.awt.BorderLayout.NORTH); panel.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); panel.add(infoLabel, java.awt.BorderLayout.SOUTH); frame.add(panel); frame.setSize(700, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Inspect and Iterate Tokens in SyntaxDocument Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This example demonstrates how to use SyntaxDocument to retrieve a token at the current caret position using a CaretListener and how to iterate over all tokens in the document using an iterator. It requires the jsyntaxpane library and standard Java Swing components. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.Token; import jsyntaxpane.actions.ActionUtils; import java.util.Iterator; public class TokenExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Token Inspector"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText("public class Demo {\n int value = 42;\n}"); JLabel tokenLabel = new JLabel("Click in editor to see token info"); editor.addCaretListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { Token token = doc.getTokenAt(e.getDot()); if (token != null) { String text = token.getString(doc); tokenLabel.setText(String.format("Token: %s, Type: %s, Start: %d, Length: %d", text, token.type, token.start, token.length)); } else { tokenLabel.setText("No token at cursor position"); } } }); JButton listTokensBtn = new JButton("List All Tokens"); listTokensBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { Iterator tokens = doc.getTokens(0, doc.getLength()); System.out.println("=== Document Tokens ==="); while (tokens.hasNext()) { Token t = tokens.next(); System.out.printf("%s: '%s'%n", t.type, t.getString(doc)); } } }); JPanel panel = new JPanel(new java.awt.BorderLayout()); panel.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); panel.add(tokenLabel, java.awt.BorderLayout.SOUTH); panel.add(listTokensBtn, java.awt.BorderLayout.NORTH); frame.add(panel); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### GET /tokens/analysis Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Retrieves token information from a SyntaxDocument, including counts and type-specific categorization. ```APIDOC ## GET /tokens/analysis ### Description Analyzes a SyntaxDocument to count occurrences of each TokenType and retrieve example text for each category. ### Method GET ### Endpoint /tokens/analysis ### Parameters #### Query Parameters - **startOffset** (int) - Required - The starting position in the document to begin tokenization. - **endOffset** (int) - Required - The ending position in the document to stop tokenization. ### Response #### Success Response (200) - **tokenCounts** (Map) - A map containing the frequency of each token type found. - **tokenExamples** (Map) - A map containing a representative string sample for each token type. #### Response Example { "tokenCounts": { "KEYWORD": 12, "COMMENT": 5 }, "tokenExamples": { "KEYWORD": "public", "COMMENT": "// Comment" } } ``` -------------------------------- ### GET /tokens/check Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Performs boolean checks on a specific token to determine its classification (e.g., is it a comment, keyword, or string). ```APIDOC ## GET /tokens/check ### Description Evaluates a specific token against predefined TokenType criteria to determine its semantic role. ### Method GET ### Endpoint /tokens/check ### Parameters #### Query Parameters - **tokenIndex** (int) - Required - The index of the token within the document. ### Response #### Success Response (200) - **isComment** (boolean) - True if the token is a comment. - **isKeyword** (boolean) - True if the token is a language keyword. - **isString** (boolean) - True if the token is a string literal. #### Response Example { "isComment": false, "isKeyword": true, "isString": false } ``` -------------------------------- ### Java Regex Pattern Matching with SyntaxDocument.getMatcher Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This Java code snippet demonstrates how to use the getMatcher() method of jsyntaxpane's SyntaxDocument to find all occurrences of a given regular expression pattern within a text document. It sets up a simple Swing application with a JEditorPane for text editing, a JTextField for the search pattern, and a JTextArea to display the results. The example highlights the process of obtaining the SyntaxDocument, compiling a Pattern, creating a Matcher using getMatcher(), and iterating through the matches to display their positions and content. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.actions.ActionUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Pattern Matching Example"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText( "public class Example {\n" + " private String name;\n" + " private int count;\n" + " private List items;\n" + " \n" + " public String getName() { return name; }\n" + " public int getCount() { return count; }\n" + "}" ); JTextField searchField = new JTextField("private \\w+", 20); JTextArea resultsArea = new JTextArea(5, 40); resultsArea.setEditable(false); JButton searchBtn = new JButton("Find All"); searchBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { Pattern pattern = Pattern.compile(searchField.getText()); Matcher matcher = doc.getMatcher(pattern); StringBuilder results = new StringBuilder(); int count = 0; if (matcher != null) { while (matcher.find()) { count++; results.append(String.format("Match %d at position %d: '%s'%n", count, matcher.start(), matcher.group())); } } if (count == 0) { results.append("No matches found."); } else { results.append(String.format("%nTotal: %d matches", count)); } resultsArea.setText(results.toString()); } }); JPanel searchPanel = new JPanel(); searchPanel.add(new JLabel("Pattern:")); searchPanel.add(searchField); searchPanel.add(searchBtn); JPanel panel = new JPanel(new java.awt.BorderLayout()); panel.add(searchPanel, java.awt.BorderLayout.NORTH); panel.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); panel.add(new JScrollPane(resultsArea), java.awt.BorderLayout.SOUTH); frame.add(panel); frame.setSize(700, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Build and Run JSyntaxPane Source: https://github.com/nordfalk/jsyntaxpane/blob/master/README.md Instructions on how to clone the repository, build the project using Maven, and run the SyntaxTester application to try out the library. ```bash git clone https://github.com/nordfalk/jsyntaxpane cd jsyntaxpane/jsyntaxpane mvn package java -jar target/jsyntaxpane-1.1.5.jar ``` -------------------------------- ### JSyntaxPane Initialization and Configuration Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt This section describes how to initialize the JSyntaxPane kit and configure the JEditorPane to support syntax highlighting for various programming languages. ```APIDOC ## Initialization and Setup ### Description Initializes the JSyntaxPane library and configures a JEditorPane instance to support syntax highlighting for specific content types. ### Method Java Method Call ### Parameters #### Configuration - **DefaultSyntaxKit.initKit()** (void) - Required - Initializes the default syntax kits for all supported languages. - **editor.setContentType(String)** (void) - Required - Sets the language type (e.g., "text/java", "text/javascript"). ### Request Example DefaultSyntaxKit.initKit(); editor.setContentType("text/java"); ### Response #### Success Response (void) - **Editor State** - The JEditorPane is now configured with the specified syntax highlighting kit. ``` -------------------------------- ### Initialize and Set Content Type for JEditorPane Source: https://github.com/nordfalk/jsyntaxpane/blob/master/README.md Demonstrates how to initialize the DefaultSyntaxKit and set the content type of a JEditorPane to enable syntax highlighting for Java. ```java DefaultSyntaxKit.initKit(); jEditorPane.setContentType("text/java") ``` -------------------------------- ### Initialize JSyntaxPane System Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt The initKit method registers all available syntax kits for JEditorPane components. This initialization is required at application startup to enable syntax highlighting across supported content types. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; public class InitExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Code Editor"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText("public class Hello {\n public static void main(String[] args) {\n System.out.println(\"Hello World\");\n }\n}"); frame.add(new JScrollPane(editor)); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Java Bracket Matching with getPairFor Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates using jsyntaxpane's getPairFor method to find matching brackets and implement navigation between them. It sets up a JEditorPane with syntax highlighting and adds functionality to jump to matching braces and display information about token pairs. Dependencies include Swing and jsyntaxpane libraries. ```java import javax.swing.*; import jsyntaxpane.*; import jsyntaxpane.actions.ActionUtils; public class BracketMatchingExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Bracket Matching"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText( "public class BracketDemo {\n" + " public void method() {\n" + " if (condition) {\n" + " doSomething();\n" + " } else {\n" + " doOther();\n" + " }\n" + " }\n" + " \n" + " public int calculate(int x, int y) {\n" + " return ((x + y) * (x - y));\n" + " }\n" + "}" ); JLabel matchLabel = new JLabel("Place cursor on a bracket to see its match"); JButton jumpToMatchBtn = new JButton("Jump to Match"); jumpToMatchBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { Token currentToken = doc.getTokenAt(editor.getCaretPosition()); if (currentToken != null && currentToken.pairValue != 0) { Token matchingToken = doc.getPairFor(currentToken); if (matchingToken != null) { editor.setCaretPosition(matchingToken.start); editor.requestFocusInWindow(); } } } }); // Show bracket match information on caret update editor.addCaretListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { Token token = doc.getTokenAt(e.getDot()); if (token != null && token.pairValue != 0) { Token match = doc.getPairFor(token); String tokenText = token.getString(doc); if (match != null) { String matchText = match.getString(doc); matchLabel.setText(String.format( "Token '%s' (pairValue=%d) matches '%s' at position %d", tokenText, token.pairValue, matchText, match.start)); } else { matchLabel.setText(String.format( "Token '%s' (pairValue=%d) - NO MATCH FOUND", tokenText, token.pairValue)); } } else { matchLabel.setText("No bracket at cursor"); } } }); JToolBar toolbar = new JToolBar(); toolbar.add(jumpToMatchBtn); JPanel panel = new JPanel(new java.awt.BorderLayout()); panel.add(toolbar, java.awt.BorderLayout.NORTH); panel.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); panel.add(matchLabel, java.awt.BorderLayout.SOUTH); frame.add(panel); frame.setSize(600, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### jsyntaxpane Basic Usage Source: https://github.com/nordfalk/jsyntaxpane/blob/master/jsyntaxpane/src/main/resources/META-INF/services/jsyntaxpane/syntaxkits/javasyntaxkit/combocompletions.txt Demonstrates how to set the content type and properties for jsyntaxpane. ```APIDOC ## Setting Content Type and Properties ### Description This section shows how to set the content type for syntax highlighting and how to set custom properties within jsyntaxpane. ### Method N/A (Illustrative examples) ### Endpoint N/A ### Parameters #### Request Body - **contentType** (string) - Required - The MIME type of the content to be highlighted (e.g., "text/java", "text/python"). - **key** (string) - Required - The name of the property to set. - **value** (string) - Required - The value of the property. ### Request Example ```json { "contentType": "text/java" } ``` ```json { "key": "someProperty", "value": "someValue" } ``` ### Response #### Success Response (200) N/A (Illustrative examples) #### Response Example N/A ``` -------------------------------- ### Managing Editor Actions Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Describes how to integrate built-in syntax kit actions such as undo, redo, and toolbar management into a Swing application. ```APIDOC ## Editor Actions API ### Description Provides access to document-level actions like undo/redo and dynamic toolbar generation provided by the syntax kit. ### Method Java Method Call ### Parameters #### Actions - **ActionUtils.getSyntaxDocument(editor)** (SyntaxDocument) - Required - Retrieves the document model for performing undo/redo operations. - **kit.addToolBarActions(editor, toolbar)** (void) - Required - Automatically populates a JToolBar with actions supported by the current syntax kit. ### Request Example SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc.canUndo()) doc.doUndo(); ### Response #### Success Response (void) - **Action Execution** - The requested editor operation (undo/redo/formatting) is applied to the document. ``` -------------------------------- ### Implement Undo/Redo with SyntaxDocument in Java Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates how to enable and control undo/redo functionality for a JEditorPane using jsyntaxpane's SyntaxDocument. It includes setting up buttons to trigger undo/redo actions and listening for changes in their availability. Dependencies include Swing, jsyntaxpane, and its DefaultSyntaxKit and ActionUtils. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.SyntaxDocument; import jsyntaxpane.actions.ActionUtils; public class UndoRedoExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Undo/Redo Example"); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText("// Edit this text and try undo/redo\npublic class Test {}"); JButton undoBtn = new JButton("Undo"); JButton redoBtn = new JButton("Redo"); JButton clearBtn = new JButton("Clear Undos"); Runnable updateButtons = () -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { undoBtn.setEnabled(doc.canUndo()); redoBtn.setEnabled(doc.canRedo()); } }; undoBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null && doc.canUndo()) { doc.doUndo(); updateButtons.run(); } }); redoBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null && doc.canRedo()) { doc.doRedo(); updateButtons.run(); } }); clearBtn.addActionListener(e -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { doc.clearUndos(); updateButtons.run(); } }); editor.addPropertyChangeListener("document", evt -> { SyntaxDocument doc = ActionUtils.getSyntaxDocument(editor); if (doc != null) { doc.addPropertyChangeListener(SyntaxDocument.CAN_UNDO, e -> undoBtn.setEnabled((Boolean) e.getNewValue())); doc.addPropertyChangeListener(SyntaxDocument.CAN_REDO, e -> redoBtn.setEnabled((Boolean) e.getNewValue())); } }); JToolBar toolbar = new JToolBar(); toolbar.add(undoBtn); toolbar.add(redoBtn); toolbar.addSeparator(); toolbar.add(clearBtn); frame.add(toolbar, java.awt.BorderLayout.NORTH); frame.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Configure jsyntaxpane Content Type and Properties Source: https://github.com/nordfalk/jsyntaxpane/blob/master/jsyntaxpane/src/main/resources/META-INF/services/jsyntaxpane/syntaxkits/javasyntaxkit/combocompletions.txt Demonstrates how to initialize the jsyntaxpane editor by setting the content type and custom properties. These methods are essential for enabling syntax highlighting for specific programming languages. ```java JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.putClientProperty("key", "value"); ``` -------------------------------- ### Register Custom Content Types with DefaultSyntaxKit Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Demonstrates how to initialize the JSyntaxPane kit and register custom content types using the registerContentType method. This allows developers to associate specific file formats with custom syntax highlighting kits. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; import jsyntaxpane.syntaxkits.PlainSyntaxKit; public class RegisterContentTypeExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); DefaultSyntaxKit.registerContentType("text/myformat", "jsyntaxpane.syntaxkits.PlainSyntaxKit"); DefaultSyntaxKit.registerContentType("application/json", "jsyntaxpane.syntaxkits.JavaScriptSyntaxKit"); JFrame frame = new JFrame("Custom Content Type"); JEditorPane editor = new JEditorPane(); editor.setContentType("application/json"); editor.setText("{\n \"name\": \"JSyntaxPane\",\n \"version\": \"1.1.5\"\n}"); System.out.println("Available content types:"); for (String type : DefaultSyntaxKit.getContentTypes()) { System.out.println(" " + type); } frame.add(new JScrollPane(editor)); frame.setSize(600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ``` -------------------------------- ### Add Editor Toolbar Actions using DefaultSyntaxKit Source: https://context7.com/nordfalk/jsyntaxpane/llms.txt Shows how to populate a JToolBar with standard editing actions provided by the SyntaxKit. This method simplifies adding common functionalities like undo, redo, and find/replace to the editor's toolbar. It depends on the jsyntaxpane library and a configured JEditorPane. ```java import javax.swing.*; import jsyntaxpane.DefaultSyntaxKit; public class ToolbarExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DefaultSyntaxKit.initKit(); JFrame frame = new JFrame("Editor with Toolbar"); frame.setLayout(new java.awt.BorderLayout()); JEditorPane editor = new JEditorPane(); editor.setContentType("text/java"); editor.setText("public class Hello {\n // Add your code here\n}"); // Create toolbar and populate with syntax kit actions JToolBar toolbar = new JToolBar(); toolbar.setFloatable(false); // Get the syntax kit and add its actions to the toolbar DefaultSyntaxKit kit = (DefaultSyntaxKit) editor.getEditorKit(); kit.addToolBarActions(editor, toolbar); frame.add(toolbar, java.awt.BorderLayout.NORTH); frame.add(new JScrollPane(editor), java.awt.BorderLayout.CENTER); frame.setSize(700, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } ```