public void execute() { if (!isEditable() || !isEnabled()) { return; } try { int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; Document document = getDocument(); String selectedText = getSelectedText(); if (selectedText != null && !CommonUtil.isEmpty(selectedText)) { final int selectionEnd = getSelectionEnd(); document.insertString(selectionEnd, selectedText, null); select(selectionEnd, selectionEnd + selectedText.length()); } else { final int docLen = document.getLength(); int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - fromIndex).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex; String textToDuplicate = getText(fromIndex, toIndex - fromIndex + 1); if (!textToDuplicate.startsWith("\n")) { textToDuplicate = "\n" + textToDuplicate; } if (textToDuplicate.endsWith("\n")) { textToDuplicate = textToDuplicate.substring(0, textToDuplicate.length() - 1); } document.insertString(Math.min(docLen, toIndex + 1), textToDuplicate, null); setCaretPosition(position + textToDuplicate.length()); } } catch (BadLocationException e1) { e1.printStackTrace(); } }
public void execute() { if (!isEditable() || !isEnabled()) { return; } int position = lastClickPoint != null ? viewToModel(lastClickPoint) : getCaretPosition(); lastClickPoint = null; Document document = getDocument(); String selectedText = getSelectedText(); try { if (selectedText != null && !CommonUtil.isEmpty(selectedText)) { String trimmed = selectedText.trim(); if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) { StringBuffer buffer = new StringBuffer(selectedText); int pos = buffer.indexOf("<!--"); buffer.delete(pos, pos + 4); pos = buffer.lastIndexOf("-->"); buffer.delete(pos, pos + 3); replaceSelection(buffer.toString()); } else { String newSelection = "<!--" + selectedText + "-->"; replaceSelection(newSelection); } } else { final int docLen = document.getLength(); int fromIndex = Math.max(0, getText(0, position).lastIndexOf('\n')); int toIndex = getText(fromIndex + 1, docLen - position).indexOf('\n'); toIndex = toIndex < 0 ? docLen : fromIndex + toIndex; String textToComment = getText(fromIndex, toIndex - fromIndex + 1); if (textToComment.startsWith("\n")) { textToComment = textToComment.substring(1); fromIndex++; } if (textToComment.endsWith("\n")) { textToComment = textToComment.substring(0, textToComment.length() - 1); toIndex--; } String trimmed = textToComment.trim(); if (trimmed.startsWith("<!--") && trimmed.endsWith("-->")) { int pos = textToComment.lastIndexOf("-->"); document.remove(fromIndex + pos, 3); pos = textToComment.indexOf("<!--"); document.remove(fromIndex + pos, 4); } else { document.insertString(Math.min(toIndex + 1, docLen), "-->", null); document.insertString(fromIndex, "<!--", null); } } } catch (BadLocationException e1) { e1.printStackTrace(); } }