Cleanup (formatting)

This commit is contained in:
Roman Shevchenko
2014-01-24 12:55:53 +04:00
parent 1c85aca8ef
commit 4fa65829de
6 changed files with 122 additions and 134 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,9 @@
package com.intellij.ide;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
@@ -40,8 +41,8 @@ import java.awt.datatransfer.Transferable;
*/
public class JavaFilePasteProvider implements PasteProvider {
public void performPaste(@NotNull final DataContext dataContext) {
final Project project = DataKeys.PROJECT.getData(dataContext);
final IdeView ideView = DataKeys.IDE_VIEW.getData(dataContext);
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
final IdeView ideView = LangDataKeys.IDE_VIEW.getData(dataContext);
if (project == null || ideView == null) return;
final PsiJavaFile javaFile = createJavaFileFromClipboardContent(project);
if (javaFile == null) return;
@@ -59,7 +60,7 @@ public class JavaFilePasteProvider implements PasteProvider {
final PsiClass mainClass = publicClass;
new WriteCommandAction(project, "Paste class '" + mainClass.getName() + "'") {
@Override
protected void run(Result result) throws Throwable {
protected void run(@NotNull Result result) throws Throwable {
PsiFile file;
try {
file = targetDir.createFile(mainClass.getName() + ".java");
@@ -68,8 +69,10 @@ public class JavaFilePasteProvider implements PasteProvider {
return;
}
final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
document.setText(javaFile.getText());
PsiDocumentManager.getInstance(project).commitDocument(document);
if (document != null) {
document.setText(javaFile.getText());
PsiDocumentManager.getInstance(project).commitDocument(document);
}
if (file instanceof PsiJavaFile) {
updatePackageStatement((PsiJavaFile) file, targetDir);
}
@@ -113,8 +116,8 @@ public class JavaFilePasteProvider implements PasteProvider {
}
public boolean isPasteEnabled(@NotNull final DataContext dataContext) {
final Project project = DataKeys.PROJECT.getData(dataContext);
final IdeView ideView = DataKeys.IDE_VIEW.getData(dataContext);
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
final IdeView ideView = LangDataKeys.IDE_VIEW.getData(dataContext);
if (project == null || ideView == null || ideView.getDirectories().length == 0) {
return false;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.editorActions;
import com.intellij.codeInsight.CodeInsightSettings;
@@ -22,7 +21,6 @@ import com.intellij.ide.PasteProvider;
import com.intellij.lang.LanguageFormatting;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
@@ -55,39 +53,48 @@ import java.awt.datatransfer.Transferable;
import java.util.Map;
public class PasteHandler extends EditorActionHandler implements EditorTextInsertHandler {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.editorActions.PasteHandler");
public static final String TRANSFERABLE_PROVIDER = "PasteTransferableProvider";
private final EditorActionHandler myOriginalHandler;
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.editorActions.PasteHandler");
private static final ExtensionPointName<PasteProvider> EP_NAME = ExtensionPointName.create("com.intellij.customPasteProvider");
private final EditorActionHandler myOriginalHandler;
public PasteHandler(EditorActionHandler originalAction) {
myOriginalHandler = originalAction;
}
@Override
public void execute(final Editor editor, final DataContext dataContext) {
execute(editor, dataContext, new Producer<Transferable>() {
@Override
public Transferable produce() {
CopyPasteManager copyPasteManager = CopyPasteManager.getInstance();
Transferable contents = copyPasteManager.getContents();
if (contents != null) {
copyPasteManager.stopKillRings();
}
return contents;
}
});
}
@Override
public void execute(final Editor editor, final DataContext dataContext, final Producer<Transferable> transferableProvider) {
if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
final Document document = editor.getDocument();
final Document document = editor.getDocument();
if (!FileDocumentManager.getInstance().requestWriting(document, CommonDataKeys.PROJECT.getData(dataContext))) {
return;
}
DataContext context = new DataContext() {
final DataContext context = new DataContext() {
@Override
public Object getData(@NonNls String dataId) {
if (TRANSFERABLE_PROVIDER.equals(dataId)) {
return transferableProvider;
}
return dataContext.getData(dataId);
return TRANSFERABLE_PROVIDER.equals(dataId) ? transferableProvider : dataContext.getData(dataId);
}
};
final Project project = editor.getProject();
if (project == null || editor.isColumnMode() || editor.getSelectionModel().hasBlockSelection()) {
if (myOriginalHandler != null) {
@@ -95,9 +102,8 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
return;
}
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (file == null) {
if (myOriginalHandler != null) {
myOriginalHandler.execute(editor, context);
@@ -107,7 +113,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
document.startGuardedBlockChecking();
try {
for(PasteProvider provider: Extensions.getExtensions(EP_NAME)) {
for (PasteProvider provider : Extensions.getExtensions(EP_NAME)) {
if (provider.isPasteEnabled(context)) {
provider.performPaste(context);
return;
@@ -123,22 +129,6 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
}
@Override
public void execute(final Editor editor, final DataContext dataContext) {
execute(editor, dataContext, new Producer<Transferable>() {
@Override
public Transferable produce() {
CopyPasteManager copyPasteManager = CopyPasteManager.getInstance();
Transferable contents = copyPasteManager.getContents();
if (contents != null) {
copyPasteManager.stopKillRings();
}
return contents;
}
});
}
private static void doPaste(final Editor editor,
final Project project,
final PsiFile file,
@@ -170,7 +160,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
final CaretModel caretModel = editor.getCaretModel();
final SelectionModel selectionModel = editor.getSelectionModel();
final int col = caretModel.getLogicalPosition().column;
// There is a possible case that we want to perform paste while there is an active selection at the editor and caret is located
// inside it (e.g. Ctrl+A is pressed while caret is not at the zero column). We want to insert the text at selection start column
// then, hence, inserted block of text should be indented according to the selection start as well.
@@ -182,7 +172,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
else {
blockIndentAnchorColumn = col;
}
// We assume that EditorModificationUtil.insertStringAtCaret() is smart enough to understand that text that is currently
// selected at editor (if any) should be removed.
//
@@ -238,7 +228,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
e.getKey().processTransferableData(project, editor, bounds, caretOffset, indented, e.getValue());
}
boolean pastedTextContainsWhiteSpacesOnly =
boolean pastedTextContainsWhiteSpacesOnly =
CharArrayUtil.shiftForward(document.getCharsSequence(), bounds.getStartOffset(), " \n\t") >= bounds.getEndOffset();
VirtualFile virtualFile = file.getVirtualFile();
@@ -254,13 +244,13 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
indentBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset(), blockIndentAnchorColumn);
}
break;
case CodeInsightSettings.INDENT_EACH_LINE:
if (!indented.get()) {
indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
}
break;
case CodeInsightSettings.REFORMAT_BLOCK:
indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); // this is needed for example when inserting a comment before method
reformatBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
@@ -294,9 +284,9 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
else {
indentPlainTextBlock(document, startOffset, endOffset, originalCaretCol);
}
}
//boolean hasNewLine = false;
//for (int i = endOffset - 1; i >= startOffset; i--) {
// char c = chars.charAt(i);
@@ -350,7 +340,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
// int i = 1;
// int j = 1;
// }
//
//
//
// We get the following on paste then:
// if (true) {
@@ -409,17 +399,17 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
linesToAdjustIndent++;
}
String indentString = StringUtil.repeatSymbol(' ', indentLevel);
for (; linesToAdjustIndent > 0; linesToAdjustIndent--) {
int lineStartOffset = document.getLineStartOffset(++line);
document.insertString(lineStartOffset, indentString);
}
}
}
private static void indentBlockWithFormatter(Project project, Document document, int startOffset, int endOffset, PsiFile file) {
// Algorithm: the main idea is to process the first line of the pasted block, adjust its indent if necessary, calculate indent
// adjustment string and apply to each line of the pasted block starting from the second one.
//
@@ -449,12 +439,12 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
// Example:
// [pasted line 1
// pasted line 2]
// We adjust the first line via formatter then and apply first line's indent to all subsequent pasted lines.
// We adjust the first line via formatter then and apply first line's indent to all subsequent pasted lines.
CharSequence chars = document.getCharsSequence();
final int firstLine = document.getLineNumber(startOffset);
final int firstLineStart = document.getLineStartOffset(firstLine);
// There is a possible case that we paste block that ends with new line that is empty or contains only white space symbols.
// We want to preserve indent for the original document line where paste was performed.
// Example:
@@ -478,7 +468,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
break;
}
}
final int lastLine;
if (saveLastLineIndent) {
lastLine = document.getLineNumber(endOffset) - 1;
@@ -491,7 +481,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
document.deleteString(start, i);
}
}
// Insert white space from the start line of the pasted block.
int indentToKeepEndOffset = Math.min(startOffset, CharArrayUtil.shiftForward(chars, firstLineStart, " \t"));
if (indentToKeepEndOffset > firstLineStart) {
@@ -500,10 +490,10 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
else {
lastLine = document.getLineNumber(endOffset);
}
}
final int i = CharArrayUtil.shiftBackward(chars, startOffset - 1, " \t");
// Handle a situation when pasted block doesn't start a new line.
if (chars.charAt(startOffset) != '\n' && i > 0 && chars.charAt(i) != '\n') {
int firstNonWsOffset = CharArrayUtil.shiftForward(chars, firstLineStart, " \t");
@@ -511,7 +501,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
CharSequence toInsert = chars.subSequence(firstLineStart, firstNonWsOffset);
for (int line = firstLine + 1; line <= lastLine; line++) {
document.insertString(document.getLineStartOffset(line), toInsert);
}
}
}
return;
}
@@ -522,7 +512,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
return;
}
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
final int j = CharArrayUtil.shiftForward(chars, startOffset, " \t\n");
if (j >= endOffset) {
// Pasted text contains white space/line feed symbols only, do nothing.
@@ -532,7 +522,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
final int anchorLine = document.getLineNumber(j);
final int anchorLineStart = document.getLineStartOffset(anchorLine);
codeStyleManager.adjustLineIndent(file, j);
// Handle situation when pasted block starts with non-white space symbols.
if (anchorLine == firstLine && j == startOffset) {
int indentOffset = CharArrayUtil.shiftForward(chars, firstLineStart, " \t");
@@ -544,7 +534,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
return;
}
// Handle situation when pasted block starts from white space symbols. Assume that the pasted text started at the line start,
// i.e. correct indentation level is stored at the blocks structure.
final int firstNonWsOffset = CharArrayUtil.shiftForward(chars, anchorLineStart, " \t");
@@ -559,7 +549,7 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
return;
}
// We've pasted text to the non-first column and exact white space between the line start and caret position on the moment of paste
// has been removed by formatter during 'adjust line indent'
// Example:
@@ -582,8 +572,8 @@ public class PasteHandler extends EditorActionHandler implements EditorTextInser
}
else {
desiredSymbolsToRemove = -diff;
}
}
for (int line = anchorLine + 1; line <= lastLine; line++) {
int currentLineStart = document.getLineStartOffset(line);
int currentLineIndentOffset = CharArrayUtil.shiftForward(chars, currentLineStart, " \t");
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,13 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: max
* Date: Sep 5, 2006
* Time: 9:31:06 PM
*/
package com.intellij.openapi.editor;
import org.jetbrains.annotations.NonNls;
@@ -31,8 +24,14 @@ import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Serializable;
/**
* @author max
* @since Sep 5, 2006
*/
public class RawText implements Cloneable, Serializable {
/** @deprecated use {@link #getDataFlavor()} (to make private in IDEA 14) */
public static @NonNls DataFlavor ourFlavor;
public String rawText;
public RawText(final String rawText) {
@@ -40,45 +39,41 @@ public class RawText implements Cloneable, Serializable {
}
public Object clone() {
try{
try {
return super.clone();
}
catch(CloneNotSupportedException e){
catch (CloneNotSupportedException e) {
throw new RuntimeException();
}
}
@SuppressWarnings("deprecation")
public static DataFlavor getDataFlavor() {
if (ourFlavor != null) {
return ourFlavor;
}
if (ourFlavor != null) return ourFlavor;
try {
ourFlavor = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" + RawText.class.getName(), "Raw Text");
DataFlavor flavor = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" + RawText.class.getName(), "Raw Text");
ourFlavor = flavor;
return flavor;
}
catch (NoClassDefFoundError e) {
return null;
}
catch (IllegalArgumentException e) {
return null;
}
return ourFlavor;
catch (NoClassDefFoundError ignore) { }
catch (IllegalArgumentException ignore) { }
return null;
}
@Nullable
public static RawText fromTransferable(Transferable content) {
RawText raw = null;
final DataFlavor flavor = getDataFlavor();
DataFlavor flavor = getDataFlavor();
if (flavor != null) {
try {
raw = (RawText)content.getTransferData(flavor);
}
catch (UnsupportedFlavorException e) {
// OK. raw will be null and we'll get plain string
}
catch (IOException e) {
// OK. raw will be null and we'll get plain string
return (RawText)content.getTransferData(flavor);
}
catch (UnsupportedFlavorException ignore) { }
catch (IOException ignore) { }
}
return raw;
return null;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,11 +56,11 @@ public abstract class CopyPasteManager {
* <p/>
* However, there are situations when all 'kill rings' should be stopped manually (e.g. on undo). Hence, we need
* a handle to ask for that. This method works like such a handle.
*
*
* @see KillRingTransferable
*/
public abstract void stopKillRings();
public interface ContentChangedListener extends EventListener {
void contentChanged(@Nullable final Transferable oldTransferable, final Transferable newTransferable);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@ package com.intellij.ide;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.ide.CopyPasteManager;
@@ -81,7 +82,7 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
}
public boolean isCutElement(@Nullable final Object element) {
for(CutElementMarker marker: Extensions.getExtensions(CutElementMarker.EP_NAME)) {
for (CutElementMarker marker : Extensions.getExtensions(CutElementMarker.EP_NAME)) {
if (marker.isCutElement(element)) return true;
}
return false;
@@ -103,9 +104,9 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
/**
* Stores given content within the current manager. It is merged with already stored ones
* if necessary (see {@link KillRingTransferable}).
*
* @param content content to store
* @return content that is either the given one or the one that was assembled from it and already stored one
*
* @param content content to store
* @return content that is either the given one or the one that was assembled from it and already stored one
*/
@NotNull
private Transferable addNewContentToStack(@NotNull Transferable content) {
@@ -114,7 +115,7 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
if (clipString == null) {
return content;
}
if (content instanceof KillRingTransferable) {
KillRingTransferable killRingContent = (KillRingTransferable)content;
if (killRingContent.isReadyToCombine() && !myData.isEmpty()) {
@@ -132,7 +133,7 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
return killRingContent;
}
}
Transferable same = null;
for (Transferable old : myData) {
if (clipString.equals(getStringContent(old))) {
@@ -157,29 +158,28 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
myData.add(0, content);
deleteAfterAllowedMaximum();
}
/**
* Merges given new data with the given old one and returns merge result in case of success.
*
* @param newData new data to merge
* @param oldData old data to merge
* @return merge result of the given data if possible; <code>null</code> otherwise
* @throws IOException as defined by {@link Transferable#getTransferData(DataFlavor)}
* @throws UnsupportedFlavorException as defined by {@link Transferable#getTransferData(DataFlavor)}
*
* @param newData new data to merge
* @param oldData old data to merge
* @return merge result of the given data if possible; <code>null</code> otherwise
* @throws IOException as defined by {@link Transferable#getTransferData(DataFlavor)}
* @throws UnsupportedFlavorException as defined by {@link Transferable#getTransferData(DataFlavor)}
*/
@Nullable
private static Transferable merge(@NotNull KillRingTransferable newData, @NotNull KillRingTransferable oldData)
throws IOException, UnsupportedFlavorException
{
throws IOException, UnsupportedFlavorException {
if (!oldData.isReadyToCombine() || !newData.isReadyToCombine()) {
return null;
}
Document document = newData.getDocument();
if (document == null || document != oldData.getDocument()) {
return null;
}
Object newDataText = newData.getTransferData(DataFlavor.stringFlavor);
Object oldDataText = oldData.getTransferData(DataFlavor.stringFlavor);
if (newDataText == null || oldDataText == null) {
@@ -193,24 +193,24 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
);
}
}
if (newData.getStartOffset() == oldData.getEndOffset()) {
return new KillRingTransferable(
oldDataText.toString() + newDataText, document, oldData.getStartOffset(), newData.getEndOffset(), false
);
}
if (newData.getEndOffset() == oldData.getStartOffset()) {
return new KillRingTransferable(
newDataText.toString() + oldDataText, document, newData.getStartOffset(), oldData.getEndOffset(), false
);
}
return null;
}
private static String getStringContent(Transferable content) throws UnsupportedFlavorException, IOException {
return (String) content.getTransferData(DataFlavor.stringFlavor);
return (String)content.getTransferData(DataFlavor.stringFlavor);
}
private void deleteAfterAllowedMaximum() {
@@ -255,7 +255,7 @@ public class CopyPasteManagerEx extends CopyPasteManager implements ClipboardOwn
Transferable _new = null;
if (isCurrentClipboardContent) {
if (!myData.isEmpty()) {
_new = myData.get(0);
_new = myData.get(0);
setSystemClipboardContent(_new);
}
else {
@@ -5981,6 +5981,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
public void run() {
try {
editor.getSelectionModel().removeSelection();
final int offset;
if (myDraggedRange != null) {
editor.getCaretModel().moveToOffset(caretOffset);
@@ -5989,16 +5990,15 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
else {
offset = editor.getCaretModel().getOffset();
}
if (editor.getDocument().getRangeGuard(offset, offset) != null) return;
EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE);
if (editor.getDocument().getRangeGuard(offset, offset) != null) {
return;
}
editor.putUserData(LAST_PASTED_REGION, null);
EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE);
LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler);
EditorTextInsertHandler handler = (EditorTextInsertHandler)pasteHandler;
handler.execute(editor, editor.getDataContext(), new Producer<Transferable>() {
((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), new Producer<Transferable>() {
@Override
public Transferable produce() {
return t;