use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.
the class CommentByLineCommentHandler method invoke.
@Override
public // first pass - adjacent carets are grouped into blocks
void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull Caret caret, @NotNull PsiFile file) {
myProject = project;
file = file.getViewProvider().getPsi(file.getViewProvider().getBaseLanguage());
PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file);
if (context != null && (context.textContains('\'') || context.textContains('\"') || context.textContains('/'))) {
String s = context.getText();
if (StringUtil.startsWith(s, "\"") || StringUtil.startsWith(s, "\'") || StringUtil.startsWith(s, "/")) {
file = context.getContainingFile();
editor = editor instanceof EditorWindow ? ((EditorWindow) editor).getDelegate() : editor;
caret = caret instanceof InjectedCaret ? ((InjectedCaret) caret).getDelegate() : caret;
}
}
Document document = editor.getDocument();
boolean hasSelection = caret.hasSelection();
int startOffset = caret.getSelectionStart();
int endOffset = caret.getSelectionEnd();
FoldRegion fold = editor.getFoldingModel().getCollapsedRegionAtOffset(startOffset);
if (fold != null && fold.shouldNeverExpand() && fold.getStartOffset() == startOffset && fold.getEndOffset() == endOffset) {
// Foldings that never expand are automatically selected, so the fact it is selected must not interfere with commenter's logic
hasSelection = false;
}
if (document.getTextLength() == 0)
return;
while (true) {
int lastLineEnd = document.getLineEndOffset(document.getLineNumber(endOffset));
FoldRegion collapsedAt = editor.getFoldingModel().getCollapsedRegionAtOffset(lastLineEnd);
if (collapsedAt != null) {
final int regionEndOffset = collapsedAt.getEndOffset();
if (regionEndOffset <= endOffset) {
break;
}
endOffset = regionEndOffset;
} else {
break;
}
}
int startLine = document.getLineNumber(startOffset);
int endLine = document.getLineNumber(endOffset);
if (endLine > startLine && document.getLineStartOffset(endLine) == endOffset) {
endLine--;
}
Block lastBlock = myBlocks.isEmpty() ? null : myBlocks.get(myBlocks.size() - 1);
Block currentBlock;
if (lastBlock == null || lastBlock.editor != editor || lastBlock.psiFile != file || startLine > (lastBlock.endLine + 1)) {
currentBlock = new Block();
currentBlock.editor = editor;
currentBlock.psiFile = file;
currentBlock.startLine = startLine;
myBlocks.add(currentBlock);
} else {
currentBlock = lastBlock;
}
currentBlock.carets.add(caret);
currentBlock.endLine = endLine;
boolean wholeLinesSelected = !hasSelection || startOffset == document.getLineStartOffset(document.getLineNumber(startOffset)) && endOffset == document.getLineEndOffset(document.getLineNumber(endOffset - 1)) + 1;
boolean startingNewLineComment = !hasSelection && isLineEmpty(document, document.getLineNumber(startOffset)) && !Comparing.equal(IdeActions.ACTION_COMMENT_LINE, ActionManagerEx.getInstanceEx().getPrevPreformedActionId());
currentBlock.caretUpdate = startingNewLineComment ? CaretUpdate.PUT_AT_COMMENT_START : !hasSelection ? CaretUpdate.SHIFT_DOWN : wholeLinesSelected ? CaretUpdate.RESTORE_SELECTION : null;
}
use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.
the class JumpToColorsAndFontsAction method actionPerformed.
@Override
public void actionPerformed(AnActionEvent e) {
// todo handle ColorKey's as well
Project project = e.getData(CommonDataKeys.PROJECT);
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (project == null || editor == null)
return;
Map<TextAttributesKey, Pair<ColorSettingsPage, AttributesDescriptor>> keyMap = ContainerUtil.newHashMap();
Processor<RangeHighlighterEx> processor = r -> {
Object tt = r.getErrorStripeTooltip();
TextAttributesKey key = tt instanceof HighlightInfo ? ObjectUtils.chooseNotNull(((HighlightInfo) tt).forcedTextAttributesKey, ((HighlightInfo) tt).type.getAttributesKey()) : null;
Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
if (p != null)
keyMap.put(key, p);
return true;
};
JBIterable<Editor> editors = editor instanceof EditorWindow ? JBIterable.of(editor, ((EditorWindow) editor).getDelegate()) : JBIterable.of(editor);
for (Editor ed : editors) {
TextRange selection = EditorUtil.getSelectionInAnyMode(ed);
MarkupModel forDocument = DocumentMarkupModel.forDocument(ed.getDocument(), project, false);
if (forDocument != null) {
((MarkupModelEx) forDocument).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
}
((MarkupModelEx) ed.getMarkupModel()).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
EditorHighlighter highlighter = ed instanceof EditorEx ? ((EditorEx) ed).getHighlighter() : null;
SyntaxHighlighter syntaxHighlighter = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter) highlighter).getSyntaxHighlighter() : null;
if (syntaxHighlighter != null) {
HighlighterIterator iterator = highlighter.createIterator(selection.getStartOffset());
while (!iterator.atEnd()) {
for (TextAttributesKey key : syntaxHighlighter.getTokenHighlights(iterator.getTokenType())) {
Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
if (p != null)
keyMap.put(key, p);
}
if (iterator.getEnd() >= selection.getEndOffset())
break;
iterator.advance();
}
}
}
if (keyMap.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No text attributes found");
} else if (keyMap.size() == 1) {
Pair<ColorSettingsPage, AttributesDescriptor> p = keyMap.values().iterator().next();
if (!openSettingsAndSelectKey(project, p.first, p.second)) {
HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
}
} else {
ArrayList<Pair<ColorSettingsPage, AttributesDescriptor>> attrs = ContainerUtil.newArrayList(keyMap.values());
Collections.sort(attrs, (o1, o2) -> StringUtil.naturalCompare(o1.first.getDisplayName() + o1.second.getDisplayName(), o2.first.getDisplayName() + o2.second.getDisplayName()));
EditorColorsScheme colorsScheme = editor.getColorsScheme();
JBList<Pair<ColorSettingsPage, AttributesDescriptor>> list = new JBList<>(attrs);
list.setCellRenderer(new ColoredListCellRenderer<Pair<ColorSettingsPage, AttributesDescriptor>>() {
@Override
protected void customizeCellRenderer(@NotNull JList<? extends Pair<ColorSettingsPage, AttributesDescriptor>> list, Pair<ColorSettingsPage, AttributesDescriptor> value, int index, boolean selected, boolean hasFocus) {
TextAttributes ta = colorsScheme.getAttributes(value.second.getKey());
Color fg = ObjectUtils.chooseNotNull(ta.getForegroundColor(), colorsScheme.getDefaultForeground());
Color bg = ObjectUtils.chooseNotNull(ta.getBackgroundColor(), colorsScheme.getDefaultBackground());
SimpleTextAttributes sa = fromTextAttributes(ta);
SimpleTextAttributes saOpaque = sa.derive(STYLE_OPAQUE | sa.getStyle(), fg, bg, null);
SimpleTextAttributes saSelected = REGULAR_ATTRIBUTES.derive(sa.getStyle(), null, null, null);
SimpleTextAttributes saCur = REGULAR_ATTRIBUTES;
List<String> split = StringUtil.split(value.first.getDisplayName() + "//" + value.second.getDisplayName(), "//");
for (int i = 0, len = split.size(); i < len; i++) {
boolean last = i == len - 1;
saCur = !last ? REGULAR_ATTRIBUTES : selected ? saSelected : saOpaque;
if (last)
append(" ", saCur);
append(split.get(i), saCur);
if (last)
append(" ", saCur);
else
append(" > ", GRAYED_ATTRIBUTES);
}
Color stripeColor = ta.getErrorStripeColor();
boolean addStripe = stripeColor != null && stripeColor != saCur.getBgColor();
boolean addBoxed = ta.getEffectType() == EffectType.BOXED && ta.getEffectColor() != null;
if (addBoxed) {
append("▢" + (addStripe ? "" : " "), saCur.derive(-1, ta.getEffectColor(), null, null));
}
if (addStripe) {
append(" ", saCur.derive(STYLE_OPAQUE, null, stripeColor, null));
}
}
});
JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle(StringUtil.notNullize(e.getPresentation().getText())).setMovable(false).setResizable(false).setRequestFocus(true).setItemChoosenCallback(() -> {
Pair<ColorSettingsPage, AttributesDescriptor> p = list.getSelectedValue();
if (p != null && !openSettingsAndSelectKey(project, p.first, p.second)) {
HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
}
}).createPopup().showInBestPositionFor(editor);
}
}
use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.
the class SelectWordHandler method doExecute.
@Override
public void doExecute(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) {
assert caret != null;
if (LOG.isDebugEnabled()) {
LOG.debug("enter: execute(editor='" + editor + "')");
}
Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(editor.getComponent()));
if (project == null) {
if (myOriginalHandler != null) {
myOriginalHandler.execute(editor, caret, dataContext);
}
return;
}
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
TextRange range = selectWord(caret, project);
if (editor instanceof EditorWindow) {
if (range == null || !isInsideEditableInjection((EditorWindow) editor, range, project) || TextRange.from(0, editor.getDocument().getTextLength()).equals(new TextRange(caret.getSelectionStart(), caret.getSelectionEnd()))) {
editor = ((EditorWindow) editor).getDelegate();
caret = ((InjectedCaret) caret).getDelegate();
range = selectWord(caret, project);
}
}
if (range == null) {
if (myOriginalHandler != null) {
myOriginalHandler.execute(editor, caret, dataContext);
}
} else {
caret.setSelection(range.getStartOffset(), range.getEndOffset());
}
}
use of com.intellij.injected.editor.EditorWindow in project intellij-community by JetBrains.
the class TextEditorPsiDataProvider method getData.
@Override
@Nullable
public Object getData(@NotNull final String dataId, @NotNull final Editor e, @NotNull final Caret caret) {
if (e.isDisposed() || !(e instanceof EditorEx)) {
return null;
}
VirtualFile file = ((EditorEx) e).getVirtualFile();
if (file == null || !file.isValid())
return null;
Project project = e.getProject();
if (dataId.equals(injectedId(EDITOR.getName()))) {
if (project == null || PsiDocumentManager.getInstance(project).isUncommited(e.getDocument())) {
return e;
} else {
return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(e, caret, getPsiFile(e, file));
}
}
if (HOST_EDITOR.is(dataId)) {
return e instanceof EditorWindow ? ((EditorWindow) e).getDelegate() : e;
}
if (CARET.is(dataId)) {
return caret;
}
if (dataId.equals(injectedId(CARET.getName()))) {
Editor editor = (Editor) getData(injectedId(EDITOR.getName()), e, caret);
assert editor != null;
return getInjectedCaret(editor, caret);
}
if (dataId.equals(injectedId(PSI_ELEMENT.getName()))) {
Editor editor = (Editor) getData(injectedId(EDITOR.getName()), e, caret);
assert editor != null;
Caret injectedCaret = getInjectedCaret(editor, caret);
return getPsiElementIn(editor, injectedCaret, file);
}
if (PSI_ELEMENT.is(dataId)) {
return getPsiElementIn(e, caret, file);
}
if (dataId.equals(injectedId(LANGUAGE.getName()))) {
PsiFile psiFile = (PsiFile) getData(injectedId(PSI_FILE.getName()), e, caret);
Editor editor = (Editor) getData(injectedId(EDITOR.getName()), e, caret);
if (psiFile == null || editor == null)
return null;
Caret injectedCaret = getInjectedCaret(editor, caret);
return getLanguageAtCurrentPositionInEditor(injectedCaret, psiFile);
}
if (LANGUAGE.is(dataId)) {
final PsiFile psiFile = getPsiFile(e, file);
if (psiFile == null)
return null;
return getLanguageAtCurrentPositionInEditor(caret, psiFile);
}
if (dataId.equals(injectedId(VIRTUAL_FILE.getName()))) {
PsiFile psiFile = (PsiFile) getData(injectedId(PSI_FILE.getName()), e, caret);
if (psiFile == null)
return null;
return psiFile.getVirtualFile();
}
if (dataId.equals(injectedId(PSI_FILE.getName()))) {
Editor editor = (Editor) getData(injectedId(EDITOR.getName()), e, caret);
if (editor == null) {
return null;
}
if (project == null) {
return null;
}
return PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
}
if (PSI_FILE.is(dataId)) {
return getPsiFile(e, file);
}
if (IDE_VIEW.is(dataId)) {
final PsiFile psiFile = project == null ? null : PsiManager.getInstance(project).findFile(file);
final PsiDirectory psiDirectory = psiFile != null ? psiFile.getParent() : null;
if (psiDirectory != null && (psiDirectory.isPhysical() || ApplicationManager.getApplication().isUnitTestMode())) {
return new IdeView() {
@Override
public void selectElement(final PsiElement element) {
Editor editor = EditorHelper.openInEditor(element);
if (editor != null) {
ToolWindowManager.getInstance(element.getProject()).activateEditorComponent();
}
}
@NotNull
@Override
public PsiDirectory[] getDirectories() {
return new PsiDirectory[] { psiDirectory };
}
@Override
public PsiDirectory getOrChooseDirectory() {
return psiDirectory;
}
};
}
}
if (CONTEXT_LANGUAGES.is(dataId)) {
return computeLanguages(e, caret);
}
return null;
}
use of com.intellij.injected.editor.EditorWindow in project intellij by bazelbuild.
the class BuildEnterHandler method preprocessEnter.
@Override
public Result preprocessEnter(PsiFile file, Editor editor, Ref<Integer> caretOffset, Ref<Integer> caretAdvance, DataContext dataContext, EditorActionHandler originalHandler) {
int offset = caretOffset.get();
if (editor instanceof EditorWindow) {
file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
editor = InjectedLanguageUtil.getTopLevelEditor(editor);
offset = editor.getCaretModel().getOffset();
}
if (!isApplicable(file, dataContext)) {
return Result.Continue;
}
// Previous enter handler's (e.g. EnterBetweenBracesHandler) can introduce a mismatch
// between the editor's caret model and the offset we've been provided with.
editor.getCaretModel().moveToOffset(offset);
Document doc = editor.getDocument();
PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);
CodeStyleSettings currentSettings = CodeStyleSettingsManager.getSettings(file.getProject());
IndentOptions indentOptions = currentSettings.getIndentOptions(file.getFileType());
Integer indent = determineIndent(file, editor, offset, indentOptions);
if (indent == null) {
return Result.Continue;
}
removeTrailingWhitespace(doc, file, offset);
originalHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
LogicalPosition position = editor.getCaretModel().getLogicalPosition();
if (position.column == indent) {
return Result.Stop;
}
if (position.column > indent) {
// default enter handler has added too many spaces -- remove them
int excess = position.column - indent;
doc.deleteString(editor.getCaretModel().getOffset() - excess, editor.getCaretModel().getOffset());
} else if (position.column < indent) {
String spaces = StringUtil.repeatSymbol(' ', indent - position.column);
doc.insertString(editor.getCaretModel().getOffset(), spaces);
}
editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(position.line, indent));
return Result.Stop;
}
Aggregations