use of com.intellij.openapi.editor.event.DocumentEvent in project intellij-community by JetBrains.
the class AutoHardWrapHandler method wrapLineIfNecessary.
/**
* The user is allowed to configured IJ in a way that it automatically wraps line on right margin exceeding on typing
* (check {@link EditorSettings#isWrapWhenTypingReachesRightMargin(Project)}).
* <p/>
* This method encapsulates that functionality, i.e. it performs the following logical actions:
* <pre>
* <ol>
* <li>Check if IJ is configured to perform automatic line wrapping on typing. Return in case of the negative answer;</li>
* <li>Check if right margin is exceeded. Return in case of the negative answer;</li>
* <li>Perform line wrapping;</li>
* </ol>
</pre>
*
* @param editor active editor
* @param dataContext current data context
* @param modificationStampBeforeTyping document modification stamp before the current symbols typing
*/
public void wrapLineIfNecessary(@NotNull Editor editor, @NotNull DataContext dataContext, long modificationStampBeforeTyping) {
Project project = editor.getProject();
Document document = editor.getDocument();
AutoWrapChange change = myAutoWrapChanges.get(document);
if (change != null) {
change.charTyped(editor, modificationStampBeforeTyping);
}
// Return eagerly if we don't need to auto-wrap line, e.g. because of right margin exceeding.
if (/*editor.isOneLineMode()
|| */
project == null || !editor.getSettings().isWrapWhenTypingReachesRightMargin(project) || (TemplateManager.getInstance(project) != null && TemplateManager.getInstance(project).getActiveTemplate(editor) != null)) {
return;
}
CaretModel caretModel = editor.getCaretModel();
int caretOffset = caretModel.getOffset();
int line = document.getLineNumber(caretOffset);
int startOffset = document.getLineStartOffset(line);
int endOffset = document.getLineEndOffset(line);
final CharSequence endOfString = document.getCharsSequence().subSequence(caretOffset, endOffset);
final boolean endsWithSpaces = StringUtil.isEmptyOrSpaces(String.valueOf(endOfString));
// Check if right margin is exceeded.
int margin = editor.getSettings().getRightMargin(project);
if (margin <= 0) {
return;
}
VisualPosition visEndLinePosition = editor.offsetToVisualPosition(endOffset);
if (margin >= visEndLinePosition.column) {
if (change != null) {
change.modificationStamp = document.getModificationStamp();
}
return;
}
// We assume that right margin is exceeded if control flow reaches this place. Hence, we define wrap position and perform
// smart line break there.
LineWrapPositionStrategy strategy = LanguageLineWrapPositionStrategy.INSTANCE.forEditor(editor);
// We want to prevent such behavior, hence, we remove automatically generated wraps and wrap the line as a whole.
if (change == null) {
change = new AutoWrapChange();
myAutoWrapChanges.put(document, change);
} else {
final int start = change.change.getStart();
final int end = change.change.getEnd();
if (!change.isEmpty() && start < end) {
document.replaceString(start, end, change.change.getText());
}
change.reset();
}
change.update(editor);
// Is assumed to be max possible number of characters inserted on the visual line with caret.
int maxPreferredOffset = editor.logicalPositionToOffset(editor.visualToLogicalPosition(new VisualPosition(caretModel.getVisualPosition().line, margin - FormatConstants.RESERVED_LINE_WRAP_WIDTH_IN_COLUMNS)));
int wrapOffset = strategy.calculateWrapPosition(document, project, startOffset, endOffset, maxPreferredOffset, true, false);
if (wrapOffset < 0) {
return;
}
WhiteSpaceFormattingStrategy formattingStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(editor);
if (wrapOffset <= startOffset || wrapOffset > maxPreferredOffset || formattingStrategy.check(document.getCharsSequence(), startOffset, wrapOffset) >= wrapOffset) {
// on first non-white space symbol because wrapped part will have the same indent value).
return;
}
final int[] wrapIntroducedSymbolsNumber = new int[1];
final int[] caretOffsetDiff = new int[1];
final int baseCaretOffset = caretModel.getOffset();
DocumentListener listener = new DocumentListener() {
@Override
public void beforeDocumentChange(DocumentEvent event) {
if (event.getOffset() < baseCaretOffset + caretOffsetDiff[0]) {
caretOffsetDiff[0] += event.getNewLength() - event.getOldLength();
}
if (autoFormatted(event)) {
return;
}
wrapIntroducedSymbolsNumber[0] += event.getNewLength() - event.getOldLength();
}
private boolean autoFormatted(DocumentEvent event) {
return event.getNewLength() <= event.getOldLength() && endsWithSpaces;
}
@Override
public void documentChanged(DocumentEvent event) {
}
};
caretModel.moveToOffset(wrapOffset);
DataManager.getInstance().saveInDataContext(dataContext, AUTO_WRAP_LINE_IN_PROGRESS_KEY, true);
document.addDocumentListener(listener);
try {
EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER).execute(editor, dataContext);
} finally {
DataManager.getInstance().saveInDataContext(dataContext, AUTO_WRAP_LINE_IN_PROGRESS_KEY, null);
document.removeDocumentListener(listener);
}
change.modificationStamp = document.getModificationStamp();
change.change.setStart(wrapOffset);
change.change.setEnd(wrapOffset + wrapIntroducedSymbolsNumber[0]);
caretModel.moveToOffset(baseCaretOffset + caretOffsetDiff[0]);
}
use of com.intellij.openapi.editor.event.DocumentEvent in project intellij-community by JetBrains.
the class EditMigrationEntryDialog method createNorthPanel.
protected JComponent createNorthPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.insets = JBUI.insets(4);
gbConstraints.weighty = 0;
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weightx = 0;
myRbPackage = new JRadioButton(RefactoringBundle.message("migration.entry.package"));
panel.add(myRbPackage, gbConstraints);
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weightx = 0;
myRbClass = new JRadioButton(RefactoringBundle.message("migration.entry.class"));
panel.add(myRbClass, gbConstraints);
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.BOTH;
gbConstraints.weightx = 1;
panel.add(new JPanel(), gbConstraints);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(myRbPackage);
buttonGroup.add(myRbClass);
gbConstraints.weightx = 0;
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
gbConstraints.fill = GridBagConstraints.NONE;
JLabel oldNamePrompt = new JLabel(RefactoringBundle.message("migration.entry.old.name"));
panel.add(oldNamePrompt, gbConstraints);
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.weightx = 1;
final LanguageTextField.DocumentCreator documentCreator = new LanguageTextField.DocumentCreator() {
@Override
public Document createDocument(String value, @Nullable Language language, Project project) {
PsiPackage defaultPackage = JavaPsiFacade.getInstance(project).findPackage("");
final JavaCodeFragment fragment = JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment("", defaultPackage, true, true);
return PsiDocumentManager.getInstance(project).getDocument(fragment);
}
};
myOldNameField = new LanguageTextField(JavaLanguage.INSTANCE, myProject, "", documentCreator);
panel.add(myOldNameField, gbConstraints);
gbConstraints.weightx = 0;
gbConstraints.gridwidth = GridBagConstraints.RELATIVE;
gbConstraints.fill = GridBagConstraints.NONE;
JLabel newNamePrompt = new JLabel(RefactoringBundle.message("migration.entry.new.name"));
panel.add(newNamePrompt, gbConstraints);
gbConstraints.gridwidth = GridBagConstraints.REMAINDER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.weightx = 1;
myNewNameField = new LanguageTextField(JavaLanguage.INSTANCE, myProject, "", documentCreator);
panel.setPreferredSize(new Dimension(300, panel.getPreferredSize().height));
panel.add(myNewNameField, gbConstraints);
final DocumentAdapter documentAdapter = new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
validateOKButton();
}
};
myOldNameField.getDocument().addDocumentListener(documentAdapter);
myNewNameField.getDocument().addDocumentListener(documentAdapter);
return panel;
}
use of com.intellij.openapi.editor.event.DocumentEvent in project intellij-community by JetBrains.
the class CreateTestDialog method createCenterPanel.
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constr = new GridBagConstraints();
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.WEST;
int gridy = 1;
constr.insets = insets(4);
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
final JLabel libLabel = new JLabel(CodeInsightBundle.message("intention.create.test.dialog.testing.library"));
libLabel.setLabelFor(myLibrariesCombo);
panel.add(libLabel, constr);
constr.gridx = 1;
constr.weightx = 1;
constr.gridwidth = GridBagConstraints.REMAINDER;
panel.add(myLibrariesCombo, constr);
myFixLibraryPanel = new JPanel(new BorderLayout());
myFixLibraryLabel = new JLabel();
myFixLibraryLabel.setIcon(AllIcons.Actions.IntentionBulb);
myFixLibraryPanel.add(myFixLibraryLabel, BorderLayout.CENTER);
myFixLibraryPanel.add(myFixLibraryButton, BorderLayout.EAST);
constr.insets = insets(1);
constr.gridy = gridy++;
constr.gridx = 0;
panel.add(myFixLibraryPanel, constr);
constr.gridheight = 1;
constr.insets = insets(6);
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
constr.gridwidth = 1;
panel.add(new JLabel(CodeInsightBundle.message("intention.create.test.dialog.class.name")), constr);
myTargetClassNameField = new EditorTextField(suggestTestClassName(myTargetClass));
myTargetClassNameField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
getOKAction().setEnabled(PsiNameHelper.getInstance(myProject).isIdentifier(getClassName()));
}
});
constr.gridx = 1;
constr.weightx = 1;
panel.add(myTargetClassNameField, constr);
constr.insets = insets(1);
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
panel.add(new JLabel(CodeInsightBundle.message("intention.create.test.dialog.super.class")), constr);
mySuperClassField = new ReferenceEditorComboWithBrowseButton(new MyChooseSuperClassAction(), null, myProject, true, JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE, RECENT_SUPERS_KEY);
mySuperClassField.setMinimumSize(mySuperClassField.getPreferredSize());
constr.gridx = 1;
constr.weightx = 1;
panel.add(mySuperClassField, constr);
constr.insets = insets(1);
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
panel.add(new JLabel(CodeInsightBundle.message("dialog.create.class.destination.package.label")), constr);
constr.gridx = 1;
constr.weightx = 1;
String targetPackageName = myTargetPackage != null ? myTargetPackage.getQualifiedName() : "";
myTargetPackageField = new PackageNameReferenceEditorCombo(targetPackageName, myProject, RECENTS_KEY, CodeInsightBundle.message("dialog.create.class.package.chooser.title"));
new AnAction() {
public void actionPerformed(AnActionEvent e) {
myTargetPackageField.getButton().doClick();
}
}.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK)), myTargetPackageField.getChildComponent());
JPanel targetPackagePanel = new JPanel(new BorderLayout());
targetPackagePanel.add(myTargetPackageField, BorderLayout.CENTER);
panel.add(targetPackagePanel, constr);
constr.insets = insets(6);
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
panel.add(new JLabel(CodeInsightBundle.message("intention.create.test.dialog.generate")), constr);
constr.gridx = 1;
constr.weightx = 1;
panel.add(myGenerateBeforeBox, constr);
constr.insets = insets(1);
constr.gridy = gridy++;
panel.add(myGenerateAfterBox, constr);
constr.insets = insets(6);
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
final JLabel membersLabel = new JLabel(CodeInsightBundle.message("intention.create.test.dialog.select.methods"));
membersLabel.setLabelFor(myMethodsTable);
panel.add(membersLabel, constr);
constr.gridx = 1;
constr.weightx = 1;
panel.add(myShowInheritedMethodsBox, constr);
constr.insets = insets(1, 8);
constr.gridy = gridy++;
constr.gridx = 0;
constr.gridwidth = GridBagConstraints.REMAINDER;
constr.fill = GridBagConstraints.BOTH;
constr.weighty = 1;
panel.add(ScrollPaneFactory.createScrollPane(myMethodsTable), constr);
myLibrariesCombo.setRenderer(new ListCellRendererWrapper<TestFramework>() {
@Override
public void customize(JList list, TestFramework value, int index, boolean selected, boolean hasFocus) {
if (value != null) {
setText(value.getName());
setIcon(value.getIcon());
}
}
});
final boolean hasTestRoots = !ModuleRootManager.getInstance(myTargetModule).getSourceRoots(JavaModuleSourceRootTypes.TESTS).isEmpty();
final List<TestFramework> attachedLibraries = new ArrayList<>();
final String defaultLibrary = getDefaultLibraryName();
TestFramework defaultDescriptor = null;
final DefaultComboBoxModel model = (DefaultComboBoxModel) myLibrariesCombo.getModel();
final List<TestFramework> descriptors = new ArrayList<>();
descriptors.addAll(Arrays.asList(Extensions.getExtensions(TestFramework.EXTENSION_NAME)));
descriptors.sort((d1, d2) -> Comparing.compare(d1.getName(), d2.getName()));
for (final TestFramework descriptor : descriptors) {
model.addElement(descriptor);
if (hasTestRoots && descriptor.isLibraryAttached(myTargetModule)) {
attachedLibraries.add(descriptor);
if (defaultLibrary == null) {
defaultDescriptor = descriptor;
}
}
if (Comparing.equal(defaultLibrary, descriptor.getName())) {
defaultDescriptor = descriptor;
}
}
myLibrariesCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final Object selectedItem = myLibrariesCombo.getSelectedItem();
if (selectedItem != null) {
final DumbService dumbService = DumbService.getInstance(myProject);
dumbService.setAlternativeResolveEnabled(true);
try {
onLibrarySelected((TestFramework) selectedItem);
} finally {
dumbService.setAlternativeResolveEnabled(false);
}
}
}
});
if (defaultDescriptor != null && (attachedLibraries.contains(defaultDescriptor) || attachedLibraries.isEmpty())) {
myLibrariesCombo.setSelectedItem(defaultDescriptor);
} else {
myLibrariesCombo.setSelectedIndex(0);
}
myFixLibraryButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (mySelectedFramework instanceof JavaTestFramework) {
((JavaTestFramework) mySelectedFramework).setupLibrary(myTargetModule);
} else {
OrderEntryFix.addJarToRoots(mySelectedFramework.getLibraryPath(), myTargetModule, null);
}
myFixLibraryPanel.setVisible(false);
}
});
myShowInheritedMethodsBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateMethodsTable();
}
});
restoreShowInheritedMembersStatus();
updateMethodsTable();
return panel;
}
use of com.intellij.openapi.editor.event.DocumentEvent in project intellij-community by JetBrains.
the class ParameterNameHintsConfigurable method createBlacklistPanel.
@Nullable
private JPanel createBlacklistPanel(@NotNull Language language) {
InlayParameterHintsProvider provider = InlayParameterHintsExtension.INSTANCE.forLanguage(language);
if (!provider.isBlackListSupported())
return null;
String blackList = getLanguageBlackList(language);
EditorTextField editorTextField = createEditorField(blackList);
editorTextField.addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
updateOkEnabled(language, editorTextField);
}
});
updateOkEnabled(language, editorTextField);
myEditors.put(language, editorTextField);
JPanel blacklistPanel = new JPanel();
BoxLayout layout = new BoxLayout(blacklistPanel, BoxLayout.Y_AXIS);
blacklistPanel.setLayout(layout);
blacklistPanel.setBorder(IdeBorderFactory.createTitledBorder("Blacklist"));
blacklistPanel.add(new JBLabel(getBlacklistExplanationHTML(language)));
blacklistPanel.add(editorTextField);
return blacklistPanel;
}
use of com.intellij.openapi.editor.event.DocumentEvent in project intellij-community by JetBrains.
the class SearchDialog method createEditor.
protected Editor createEditor(final SearchContext searchContext, String text) {
Editor editor = null;
if (fileTypes != null) {
final FileType fileType = (FileType) fileTypes.getSelectedItem();
final Language dialect = (Language) dialects.getSelectedItem();
final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(fileType);
if (profile != null) {
editor = profile.createEditor(searchContext, fileType, dialect, text, useLastConfiguration);
}
}
if (editor == null) {
final EditorFactory factory = EditorFactory.getInstance();
final Document document = factory.createDocument("");
editor = factory.createEditor(document, searchContext.getProject());
editor.getSettings().setFoldingOutlineShown(false);
}
editor.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void beforeDocumentChange(final DocumentEvent event) {
}
@Override
public void documentChanged(final DocumentEvent event) {
initiateValidation();
}
});
return editor;
}
Aggregations