Java Code Examples for com.intellij.openapi.editor.Document#getText()

The following examples show how to use com.intellij.openapi.editor.Document#getText() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TagTextIntention.java    From weex-language-support with MIT License 6 votes vote down vote up
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {

    if (!WeexFileUtil.isOnWeexFile(element)) {
        return false;
    }

    int offset = editor.getCaretModel().getOffset();
    Document document = editor.getDocument();
    if (!element.isWritable() || element.getContext() == null || !element.getContext().isWritable()) {
        return false;
    }

    if (element instanceof XmlToken && ((XmlToken) element).getTokenType().toString().equals("XML_END_TAG_START")) {
        String next = document.getText(new TextRange(offset, offset + 1));
        if (next != null && next.equals("<")) {
            return true;
        }
    }

    return available(element);
}
 
Example 2
Source File: CurrentContentRevision.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public String getContent() {
  VirtualFile vFile = getVirtualFile();
  if (vFile == null) {
    myFile.refresh();
    vFile = getVirtualFile();
    if (vFile == null) return null;
  }
  final VirtualFile finalVFile = vFile;
  final Document doc = ApplicationManager.getApplication().runReadAction(new Computable<Document>() {
    public Document compute() {
      return FileDocumentManager.getInstance().getDocument(finalVFile);
  }});
  if (doc == null) return null;
  return doc.getText();
}
 
Example 3
Source File: ResolveRedSymbolsAction.java    From litho with Apache License 2.0 6 votes vote down vote up
private static Map<String, List<PsiElement>> collectRedSymbols(
    PsiFile psiFile, Document document, Project project, ProgressIndicator daemonIndicator) {
  Map<String, List<PsiElement>> redSymbolToElements = new HashMap<>();
  List<HighlightInfo> infos =
      ((DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(project))
          .runMainPasses(psiFile, document, daemonIndicator);
  for (HighlightInfo info : infos) {
    if (!info.getSeverity().equals(HighlightSeverity.ERROR)) continue;

    final String redSymbol = document.getText(new TextRange(info.startOffset, info.endOffset));
    if (!StringUtil.isJavaIdentifier(redSymbol) || !StringUtil.isCapitalized(redSymbol)) continue;

    final PsiJavaCodeReferenceElement ref =
        PsiTreeUtil.findElementOfClassAtOffset(
            psiFile, info.startOffset, PsiJavaCodeReferenceElement.class, false);
    if (ref == null) continue;

    redSymbolToElements.putIfAbsent(redSymbol, new ArrayList<>());
    redSymbolToElements.get(redSymbol).add(ref);
  }
  return redSymbolToElements;
}
 
Example 4
Source File: ParsingUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static GrammarRootAST parseGrammar(Project project, Tool antlr, VirtualFile grammarFile) {
	try {
		Document document = FileDocumentManager.getInstance().getDocument(grammarFile);
		String grammarText = document != null ? document.getText() : new String(grammarFile.contentsToByteArray());

		ANTLRStringStream in = new ANTLRStringStream(grammarText);
		in.name = grammarFile.getPath();
		return antlr.parse(grammarFile.getPath(), in);
	}
	catch (IOException ioe) {
		antlr.errMgr.toolError(ErrorType.CANNOT_OPEN_FILE, ioe, grammarFile);
	}
	return null;
}
 
Example 5
Source File: ExpectedHighlightingData.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void extractExpectedLineMarkerSet(Document document) {
  String text = document.getText();

  @NonNls String pat = ".*?((<" + LINE_MARKER + ")(?: descr=\"((?:[^\"\\\\]|\\\\\")*)\")?>)(.*)";
  final Pattern p = Pattern.compile(pat, Pattern.DOTALL);
  final Pattern pat2 = Pattern.compile("(.*?)(</" + LINE_MARKER + ">)(.*)", Pattern.DOTALL);

  while (true) {
    Matcher m = p.matcher(text);
    if (!m.matches()) break;
    int startOffset = m.start(1);
    final String descr = m.group(3) != null ? m.group(3) : ANY_TEXT;
    String rest = m.group(4);

    document.replaceString(startOffset, m.end(1), "");

    final Matcher matcher2 = pat2.matcher(rest);
    LOG.assertTrue(matcher2.matches(), "Cannot find closing </" + LINE_MARKER + ">");
    String content = matcher2.group(1);
    int endOffset = startOffset + matcher2.start(3);
    String endTag = matcher2.group(2);

    document.replaceString(startOffset, endOffset, content);
    endOffset -= endTag.length();

    LineMarkerInfo markerInfo = new LineMarkerInfo<PsiElement>(myFile, new TextRange(startOffset, endOffset), null, Pass.LINE_MARKERS,
                                                               new ConstantFunction<PsiElement, String>(descr), null,
                                                               GutterIconRenderer.Alignment.RIGHT);

    lineMarkerInfos.put(document.createRangeMarker(startOffset, endOffset), markerInfo);
    text = document.getText();
  }
}
 
Example 6
Source File: ReciteWords.java    From ReciteWords with MIT License 5 votes vote down vote up
public String getCurrentWords(Editor editor) {
    Document document = editor.getDocument();
    CaretModel caretModel = editor.getCaretModel();
    int caretOffset = caretModel.getOffset();
    int lineNum = document.getLineNumber(caretOffset);
    int lineStartOffset = document.getLineStartOffset(lineNum);
    int lineEndOffset = document.getLineEndOffset(lineNum);
    String lineContent = document.getText(new TextRange(lineStartOffset, lineEndOffset));
    char[] chars = lineContent.toCharArray();
    int start = 0, end = 0, cursor = caretOffset - lineStartOffset;

    if (!Character.isLetter(chars[cursor])) {
        Logger.warn("Caret not in a word");
        return null;
    }

    for (int ptr = cursor; ptr >= 0; ptr--) {
        if (!Character.isLetter(chars[ptr])) {
            start = ptr + 1;
            break;
        }
    }

    int lastLetter = 0;
    for (int ptr = cursor; ptr < lineEndOffset - lineStartOffset; ptr++) {
        lastLetter = ptr;
        if (!Character.isLetter(chars[ptr])) {
            end = ptr;
            break;
        }
    }
    if (end == 0) {
        end = lastLetter + 1;
    }

    String ret = new String(chars, start, end-start);
    Logger.info("Selected words: " + ret);
    return ret;
}
 
Example 7
Source File: LogView.java    From logviewer with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the selected text if there is any selection. If not return all based on parameter
 *
 * @param defaultToAll If no selection, then this decides whether to return all text
 */
String getSelectedText(boolean defaultToAll) {
    ConsoleView console = this.getConsole();
    Editor myEditor = console != null ? (Editor) CommonDataKeys.EDITOR.getData((DataProvider) console) : null;
    if (myEditor != null) {
        Document document = myEditor.getDocument();
        final SelectionModel selectionModel = myEditor.getSelectionModel();
        if (selectionModel.hasSelection()) {
            return selectionModel.getSelectedText();
        } else if (defaultToAll) {
            return document.getText();
        }
    }
    return null;
}
 
Example 8
Source File: BsCompilerImpl.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void refmtCount(@NotNull VirtualFile sourceFile, boolean isInterface, @NotNull String format, @NotNull Document document, final int retries) {
    if (!sourceFile.exists()) {
        return;
    }

    if (ReasonSettings.getInstance(m_project).isEnabled()) {
        long before = document.getModificationStamp();

        RefmtProcess refmt = RefmtProcess.getInstance(m_project);
        String oldText = document.getText();
        if (!oldText.isEmpty()) {
            String newText = refmt.run(sourceFile, isInterface, format, oldText);
            if (!newText.isEmpty() && !oldText.equals(newText)) { // additional protection
                ApplicationManager.getApplication().invokeLater(() -> {
                    long after = document.getModificationStamp();
                    if (after > before) {
                        // Document has changed, redo refmt one time
                        if (retries < 2) {
                            refmtCount(sourceFile, isInterface, format, document, retries + 1);
                        }
                    } else {
                        CommandProcessor.getInstance().executeCommand(m_project, () -> {
                            WriteAction.run(() -> {
                                document.setText(newText);
                                FileDocumentManager.getInstance().saveDocument(document);
                            });
                            sourceFile.putUserData(UndoConstants.FORCE_RECORD_UNDO, null);
                        }, "reason.refmt", "CodeFormatGroup", document);
                    }
                });
            }
        }
    }
}
 
Example 9
Source File: BsCompilerImpl.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@Override
@Nullable
public String convert(@NotNull VirtualFile virtualFile, boolean isInterface, @NotNull String fromFormat, @NotNull String toFormat,
                      @NotNull Document document) {
    RefmtProcess refmt = RefmtProcess.getInstance(m_project);
    String oldText = document.getText();
    String newText = refmt.convert(virtualFile, isInterface, fromFormat, toFormat, oldText);
    // additional protection
    return oldText.isEmpty() || newText.isEmpty() ? null : newText;
}
 
Example 10
Source File: SpringReformatter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private void reformat(PsiFile file, Collection<TextRange> ranges, Document document) {
	if (document != null) {
		Formatter formatter = new Formatter();
		String source = document.getText();
		IRegion[] regions = EclipseRegionAdapter.asArray(ranges);
		TextEdit edit = formatter.format(source, regions, NORMALIZED_LINE_SEPARATOR);
		applyEdit(document, edit);
	}
}
 
Example 11
Source File: CopySourceAction.java    From JHelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void performAction(AnActionEvent e) {
	Project project = e.getProject();
	if (project == null)
		throw new NotificationException("No project found", "Are you in any project?");

	Configurator configurator = project.getComponent(Configurator.class);
	Configurator.State configuration = configurator.getState();

	RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
	RunnerAndConfigurationSettings selectedConfiguration = runManager.getSelectedConfiguration();
	if (selectedConfiguration == null) {
		return;
	}

	RunConfiguration runConfiguration = selectedConfiguration.getConfiguration();
	if (!(runConfiguration instanceof TaskConfiguration)) {
		Notificator.showNotification(
				"Not a JHelper configuration",
				"You have to choose JHelper Task to copy",
				NotificationType.WARNING
		);
		return;
	}

	CodeGenerationUtils.generateSubmissionFileForTask(project, (TaskConfiguration)runConfiguration);

	VirtualFile file = project.getBaseDir().findFileByRelativePath(configuration.getOutputFile());
	if (file == null)
		throw new NotificationException("Couldn't find output file");
	Document document = FileDocumentManager.getInstance().getDocument(file);
	if (document == null)
		throw new NotificationException("Couldn't open output file");
	StringSelection selection = new StringSelection(document.getText());
	Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
}
 
Example 12
Source File: LSPIJUtils.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public static Position toPosition(int offset, Document document) {
    int line = document.getLineNumber(offset);
    int lineStart = document.getLineStartOffset(line);
    String lineTextBeforeOffset = document.getText(new TextRange(lineStart, offset));
    int column = lineTextBeforeOffset.length();
    return new Position(line, column);
}
 
Example 13
Source File: TabNineCompletionContributor.java    From tabnine-intellij with MIT License 5 votes vote down vote up
static boolean endsWith(Document doc, int pos, String s) {
    int begin = pos - s.length();
    if (begin < 0 || pos > doc.getTextLength()) {
        return false;
    } else {
        String tail = doc.getText(new TextRange(begin, pos));
        return tail.equals(s);
    }
}
 
Example 14
Source File: SingleFileExecutionAction.java    From SingleFileExecutionPlugin with MIT License 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {

    /* Get all the required data from data keys */
    //final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
    project = e.getRequiredData(CommonDataKeys.PROJECT);
    config = SingleFileExecutionConfig.getInstance(project);
    String cmakelistFilePath = project.getBasePath() + "/CMakeLists.txt";

    //Access document, caret, and selection
    //final Document document = editor.getDocument();
    //final SelectionModel selectionModel = editor.getSelectionModel();
    //final int start = selectionModel.getSelectionStart();
    //final int end = selectionModel.getSelectionEnd();

    File file = new File(cmakelistFilePath);
    VirtualFile cmakelistFile = LocalFileSystem.getInstance().findFileByIoFile(file);
    if (cmakelistFile == null) {
        /* CMakeLists.txt not exist */
        Notifications.Bus.notify (
                new Notification("singlefileexecutionaction", "Single File Execution Plugin", "Fail to access " + cmakelistFilePath, NotificationType.ERROR)
        );
        return;
    }
    Document cmakelistDocument = FileDocumentManager.getInstance().getDocument(cmakelistFile);

    // get source file (* currently selected file in editor)
    sourceFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    //vFile.getCanonicalPath();   // source file path (absolute path)
    //vFile.getPath();            // source file path (absolute path)
    String fileName = sourceFile != null ? sourceFile.getName() : null;  // source file name (but not include path)

    String exeName = buildExeName(config.getExecutableName());
    String sourceName = fileName;
    String relativeSourcePath = new File(project.getBasePath()).toURI().relativize(new File(sourceFile.getPath()).toURI()).getPath();

    /* parse cmakelistDocument to check existence of exe_name */
    /* See http://mmasashi.hatenablog.com/entry/20091129/1259511129 for lazy, greedy search */
    String regex = "^add_executable\\s*?\\(\\s*?" + exeName + "\\s+(((\\S+)\\s+)*\\S+)\\s*\\)";

    Pattern pattern = Pattern.compile(regex);

    Scanner scanner = new Scanner(cmakelistDocument.getText());
    int exeExistFlag = EXE_NOT_EXIST;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        Matcher m = pattern.matcher(line);
        if (m.find()) {
            //String existingExeName = m.group(1);
            String existingSourceName = m.group(1);
            if (existingSourceName.contains(relativeSourcePath)) {
                exeExistFlag = EXE_EXIST_SAME_SOURCE;
            } else {
                exeExistFlag = EXE_EXIST_DIFFERENT_SOURCE;
            }
            break;
        }
    }
    scanner.close();

    //LocalFileSystem.getInstance().findFileByIoFile();
    switch(exeExistFlag) {
        case EXE_NOT_EXIST:
            insertAddExecutable(cmakelistDocument, exeName, relativeSourcePath);
            Notifications.Bus.notify (
                    new Notification("singlefileexecutionaction", "Single File Execution Plugin", "add_executable added for " + sourceName + ".", NotificationType.INFORMATION)
            );
            break;
        case EXE_EXIST_SAME_SOURCE:
            // skip setText
            Notifications.Bus.notify (
                    new Notification("singlefileexecutionaction", "Single File Execution Plugin", "add_executable for this source already exists.", NotificationType.INFORMATION)
            );
            break;
        case EXE_EXIST_DIFFERENT_SOURCE:
            int okFlag;
            if (config.notShowOverwriteConfirmDialog) {
                // Do not show dialog & proceed
                okFlag = ExeOverwriteConfirmDialog.OK_FLAG_OK;
            } else {
                okFlag = ExeOverwriteConfirmDialog.show(project);
            }

            if (okFlag == ExeOverwriteConfirmDialog.OK_FLAG_OK) {
                // Ok
                updateAddExecutable(cmakelistDocument, exeName, relativeSourcePath);
                Notifications.Bus.notify(
                        new Notification("singlefileexecutionaction", "Single File Execution Plugin", "add_executable overwritten", NotificationType.INFORMATION)
                );
            } else {
                // cancel
                // do nothing so far
            }
            break;
    }

}
 
Example 15
Source File: QuoteHandler.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
private String getPreviousChar(Document document, int offset) {
  return offset <= 0 ? " " : document.getText(new TextRange(offset - 1, offset));
}
 
Example 16
Source File: QuoteHandler.java    From bamboo-soy with Apache License 2.0 4 votes vote down vote up
private String getNextChar(Document document, int offset) {
  return offset >= document.getTextLength()
      ? " "
      : document.getText(new TextRange(offset, offset + 1));
}
 
Example 17
Source File: MergeOperations.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static String getSubstring(Document document, TextRange range) {
  return document.getText(range);
}
 
Example 18
Source File: SingleFileExecutionAction.java    From SingleFileExecutionPlugin with MIT License 4 votes vote down vote up
private void updateAddExecutable(final Document cmakelistDocument, final String exeName, final String relativeSourcePath) {
    String runtimeDir = config.getRuntimeOutputDirectory();
    String updatedDocument = "";

    /*
     * This regular expression finds
     * "add_executable(XXXX YYYY.cpp ZZZZ.cpp)" where XXXX is executable name, YYYY.cpp and ZZZZ.cpp are the source files.
     */
    String regex = "^add_executable\\s*?\\(\\s*?" + exeName + "\\s+(((\\S+)\\s+)*\\S+)\\s*\\)";
    Pattern pattern = Pattern.compile(regex);

    String regex2 = "^set_target_properties\\s*?\\(\\s*?" + exeName + "\\s+(((\\S+)\\s+)*\\S+)\\s*\\)";
    Pattern pattern2 = Pattern.compile(regex2);

    Scanner scanner = new Scanner(cmakelistDocument.getText());

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        Matcher m = pattern.matcher(line);
        Matcher m2 = pattern2.matcher(line);
        if (m2.find()) {
            /* Skip adding line for old "set_target_properties()" statement */
            continue;
        }
        if (m.find()) {
            /* add_executable */
            line = m.replaceFirst(constructAddExecutable(exeName, relativeSourcePath));
            /* set_target_properties */
            if (runtimeDir != null && !runtimeDir.equals("")) {
                String outputDir = quoteString(buildRuntimeOutputDirectory());
                line += "\n" + constructSetTargetProperties(exeName, outputDir);
            }
        }
        updatedDocument += line + '\n';
    }
    scanner.close();
    final String updatedText = updatedDocument;
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            cmakelistDocument.setText(updatedText);
        }
    });
}
 
Example 19
Source File: EnterInStringLiteralHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Result preprocessEnter(@Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull Ref<Integer> caretOffsetRef,
                              @Nonnull final Ref<Integer> caretAdvanceRef, @Nonnull final DataContext dataContext,
                              final EditorActionHandler originalHandler) {
  int caretOffset = caretOffsetRef.get().intValue();
  int caretAdvance = caretAdvanceRef.get().intValue();
  if (!isInStringLiteral(editor, dataContext, caretOffset)) return Result.Continue;
  PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
  PsiElement psiAtOffset = file.findElementAt(caretOffset);
  if (psiAtOffset != null && psiAtOffset.getTextOffset() < caretOffset) {
    Document document = editor.getDocument();
    CharSequence text = document.getText();
    ASTNode token = psiAtOffset.getNode();
    JavaLikeQuoteHandler quoteHandler = getJavaLikeQuoteHandler(editor, psiAtOffset);

    if (quoteHandler != null &&
        quoteHandler.getConcatenatableStringTokenTypes() != null &&
        quoteHandler.getConcatenatableStringTokenTypes().contains(token.getElementType())) {
      TextRange range = token.getTextRange();
      final char literalStart = token.getText().charAt(0);
      final StringLiteralLexer lexer = new StringLiteralLexer(literalStart, token.getElementType());
      lexer.start(text, range.getStartOffset(), range.getEndOffset());

      while (lexer.getTokenType() != null) {
        if (lexer.getTokenStart() < caretOffset && caretOffset < lexer.getTokenEnd()) {
          if (StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(lexer.getTokenType())) {
            caretOffset = lexer.getTokenEnd();
          }
          break;
        }
        lexer.advance();
      }

      if (quoteHandler.needParenthesesAroundConcatenation(psiAtOffset)) {
        document.insertString(psiAtOffset.getTextRange().getEndOffset(), ")");
        document.insertString(psiAtOffset.getTextRange().getStartOffset(), "(");
        caretOffset++;
        caretAdvance++;
      }

      final String insertedFragment = literalStart + " " + quoteHandler.getStringConcatenationOperatorRepresentation();
      document.insertString(caretOffset, insertedFragment + " " + literalStart);
      caretOffset += insertedFragment.length();
      caretAdvance = 1;
      CommonCodeStyleSettings langSettings =
              CodeStyleSettingsManager.getSettings(file.getProject()).getCommonSettings(file.getLanguage());
      if (langSettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) {
        caretOffset -= 1;
        caretAdvance = 3;
      }
      caretOffsetRef.set(caretOffset);
      caretAdvanceRef.set(caretAdvance);
      return Result.DefaultForceIndent;
    }
  }
  return Result.Continue;
}
 
Example 20
Source File: ShelvedChange.java    From consulo with Apache License 2.0 4 votes vote down vote up
private String getBaseContent() {
  myBeforeFilePath.refresh();
  final Document doc = FileDocumentManager.getInstance().getDocument(myBeforeFilePath.getVirtualFile());
  return doc.getText();
}