String (String in, String what, String by, ReplaceOptions replaceOptions, Project project, boolean sourceIsFile, boolean createPhysicalFile, @NotNull LanguageFileType sourceFileType, @NotNull Language sourceDialect) { replaceOptions.setReplacement(by); final MatchOptions matchOptions = replaceOptions.getMatchOptions(); matchOptions.fillSearchCriteria(what); Matcher.validate(project, matchOptions); checkReplacementPattern(project, replaceOptions); final Replacer replacer = new Replacer(project, replaceOptions); final Matcher matcher = new Matcher(project, matchOptions); try { final PsiElement firstElement; final PsiElement lastElement; final PsiElement parent; if (matchOptions.getScope() == null) { final PsiElement[] elements = MatcherImplUtil.createTreeFromText( in, new PatternContextInfo(sourceIsFile ? PatternTreeContext.File : PatternTreeContext.Block), sourceFileType, sourceDialect, project, createPhysicalFile ); firstElement = elements[0]; lastElement = elements[elements.length-1]; parent = firstElement.getParent(); matchOptions.setScope(new LocalSearchScope(elements)); } else { parent = ((LocalSearchScope)matchOptions.getScope()).getScope()[0]; firstElement = parent.getFirstChild(); lastElement = parent.getLastChild(); } final CollectingMatchResultSink sink = new CollectingMatchResultSink(); matcher.testFindMatches(sink); final List<ReplacementInfo> replacements = new SmartList<>(); for (final MatchResult result : sink.getMatches()) { replacements.add(replacer.buildReplacement(result)); } int startOffset = firstElement.getTextRange().getStartOffset(); int endOffset = sourceIsFile ? 0 : (parent.getTextLength() - lastElement.getTextRange().getEndOffset()); // get nodes from text may contain final PsiElement prevSibling = firstElement.getPrevSibling(); if (prevSibling instanceof PsiWhiteSpace) { startOffset -= prevSibling.getTextLength(); } final PsiElement nextSibling = lastElement.getNextSibling(); if (nextSibling instanceof PsiWhiteSpace) { endOffset -= nextSibling.getTextLength(); } replacer.replaceAll(replacements); if (firstElement == lastElement && firstElement instanceof PsiFile) { return firstElement.getText(); } final String result = parent.getText(); return result.substring(startOffset, result.length() - endOffset); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IncorrectOperationException(e); } finally { matchOptions.setScope(null); } }