public PsiIntentionResult(List<ITemplateFieldHolder> holders, IDeclaration declaration, ITreeNode anchor, DocumentRange range) { myDeclaration = declaration; myHolders = holders; myPrefferedSelection = range; myAnchor = anchor; }
/// <summary>Initializes a new instance of the <see cref="SuggestionBase"/> class.</summary> /// <param name="suggestionName">Name of the suggestion.</param> /// <param name="element">The element.</param> /// <param name="highlightingRange">The highlighting range.</param> /// <param name="toolTip">The tool tip.</param> protected SuggestionBase(string suggestionName, IElement element, DocumentRange highlightingRange, string toolTip) { this.range = highlightingRange; this.toolTip = toolTip; this.element = element; this.suggestionName = suggestionName; }
public AttributeParamImpl(IXmlAttribute xmlAttribute,IParameterDescriptorProvider parameterDescriptorProvider) { name = xmlAttribute.AttributeName; nameDocumentRange = xmlAttribute.ToTreeNode().NameNode.GetDocumentRange(); stringValue = xmlAttribute.UnquotedValue; this.parameterDescriptorProvider = parameterDescriptorProvider; }
public ISelectedRange GetSelectedRange(IPsiSourceFile sourceFile, DocumentRange documentRange) { Pair<IT4File, IFile> pair = GetFiles(sourceFile, documentRange); IT4File t4File = pair.First; IFile codeBehindFile = pair.Second; if (t4File == null) return null; ITreeNode t4Node = t4File.FindNodeAt(documentRange); if (t4Node == null) return null; // if the current selection is inside C# code, use the C# extend selection directly if (codeBehindFile != null) { ISelectEmbracingConstructProvider codeBehindProvider = PsiShared.GetComponent<PsiProjectFileTypeCoordinator>() .GetByPrimaryPsiLanguageType(codeBehindFile.Language) .SelectNotNull(fileType => Shell.Instance.GetComponent<IProjectFileTypeServices>().TryGetService<ISelectEmbracingConstructProvider>(fileType)) .FirstOrDefault(); if (codeBehindProvider != null) { ISelectedRange codeBehindRange = codeBehindProvider.GetSelectedRange(sourceFile, documentRange); if (codeBehindRange != null) return new T4CodeBehindWrappedSelection(t4File, codeBehindRange); } } return new T4NodeSelection(t4File, t4Node); }
/// <summary> /// Gets the highlight for the specified StyleCop Violation. /// </summary> /// <param name="violation"> /// The <see cref="StyleCop.ViolationEventArgs"/> instance containing the event data. /// </param> /// <param name="documentRange"> /// <see cref="DocumentRange"/>where the Violation happened. /// </param> /// <param name="fileName"> /// <see cref="CsElement"/>of the violation. /// </param> /// <param name="lineNumber"> /// Line number where the violation happened. /// </param> /// <returns> /// An <see cref="IHighlighting"/> for the specified Violation. /// </returns> public static IHighlighting GetHighlight(ViolationEventArgs violation, DocumentRange documentRange, string fileName, int lineNumber) { string ruleID = violation.Violation.Rule.CheckId; string highlightID = HighlightingRegistering.GetHighlightID(ruleID); // To get the correct severity for a highlight we need to specify the current solution. ISolutionManager solutionManager = Shell.Instance.GetComponent<ISolutionManager>(); Severity severity = HighlightingSettingsManager.Instance.GetConfigurableSeverity(highlightID, solutionManager.CurrentSolution); switch (severity) { case Severity.ERROR: return new StyleCopViolationError(violation, documentRange, fileName, lineNumber); case Severity.HINT: return new StyleCopViolationHint(violation, documentRange, fileName, lineNumber); case Severity.INFO: return new StyleCopViolationError(violation, documentRange, fileName, lineNumber); case Severity.SUGGESTION: return new StyleCopViolationSuggestion(violation, documentRange, fileName, lineNumber); case Severity.WARNING: return new StyleCopViolationWarning(violation, documentRange, fileName, lineNumber); default: return new StyleCopViolationDoNotShow(violation, documentRange, fileName, lineNumber); } }
public static ICSharpStatement FixExpressionToStatement(DocumentRange expressionRange, [NotNull] IPsiServices psiServices) { var solution = psiServices.Solution; var offset = expressionRange.TextRange.StartOffset; var document = expressionRange.Document; var expressions = TextControlToPsi.GetElements<IRazorImplicitExpression>(solution, document, offset); foreach (var razorExpression in expressions) { var razorRange = razorExpression.GetDocumentRange(); const string commandName = "Replacing razor expression with statement"; using (solution.CreateTransactionCookie( DefaultAction.Commit, commandName, NullProgressIndicator.Instance)) { razorRange.Document.ReplaceText(razorRange.TextRange, "@using(null){}"); } solution.GetPsiServices().CommitAllDocuments(); var statements = TextControlToPsi.GetElements<IUsingStatement>(solution, document, offset); foreach (var razorStatement in statements) { return razorStatement; } break; } return null; }
/// <summary> /// Gets the highlight for the specified StyleCop Violation. /// </summary> /// <param name="violation"> /// The <see cref="StyleCop.ViolationEventArgs"/> instance containing the event data. /// </param> /// <param name="documentRange"> /// <see cref="DocumentRange"/>where the Violation happened. /// </param> /// <param name="fileName"> /// <see cref="CsElement"/>of the violation. /// </param> /// <param name="lineNumber"> /// Line number where the violation happened. /// </param> /// <returns> /// An <see cref="IHighlighting"/> for the specified Violation. /// </returns> public static IHighlighting GetHighlight(ViolationEventArgs violation, DocumentRange documentRange, string fileName, int lineNumber) { string ruleID = violation.Violation.Rule.CheckId; string highlightID = HighlightingRegistering.GetHighlightID(ruleID); VSSolutionManager solutionManager = Shell.Instance.GetComponent<VSSolutionManager>(); IContextBoundSettingsStore settingsStore = PsiSourceFileExtensions.GetSettingsStore(null, solutionManager.CurrentSolution); Severity severity = HighlightingSettingsManager.Instance.GetConfigurableSeverity(highlightID, settingsStore); switch (severity) { case Severity.ERROR: return new StyleCopHighlightingError(violation, documentRange, fileName, lineNumber); case Severity.HINT: return new StyleCopHighlightingHint(violation, documentRange, fileName, lineNumber); case Severity.INFO: return new StyleCopHighlightingError(violation, documentRange, fileName, lineNumber); case Severity.SUGGESTION: return new StyleCopHighlightingSuggestion(violation, documentRange, fileName, lineNumber); case Severity.WARNING: return new StyleCopHighlightingWarning(violation, documentRange, fileName, lineNumber); default: return new StyleCopHighlightingDoNotShow(violation, documentRange, fileName, lineNumber); } }
/// <summary> /// Returns a WhyBulb for the given highlighting. /// </summary> /// <param name="highlighting">Highlighting to process.</param> /// <param name="highlightingRange">Hihglighting range - not used here.</param> /// <returns></returns> public ICollection<IDisableHighlightingAction> Actions(IHighlighting highlighting, DocumentRange highlightingRange) { var cSharpHighlighting = highlighting as CSharpHighlightingBase; return (cSharpHighlighting == null) ? EmptyArray<IDisableHighlightingAction>.Instance : new IDisableHighlightingAction[] { new WhyBulb(highlighting.ErrorStripeToolTip, highlighting.GetType().Name) }; }
public InvalidRequiresMessageHighlighting(IInvocationExpression invocationExpression, Message contractMessage) { Contract.Requires(contractMessage != null); Contract.Requires(invocationExpression != null); _range = invocationExpression.GetHighlightingRange(); _contractMessage = contractMessage; }
public CreateMissedParameterFix(MissedParameterError missedParameterError) { if (missedParameterError == null) throw new ArgumentNullException("missedParameterError"); this.missedParameterError = missedParameterError; headerNameRange = ((IXmlTag) missedParameterError.Element).ToTreeNode().Header.Name.GetDocumentRange(); }
/// <summary> /// /// </summary> /// <param name="startLineNumber">Indexed from 1</param> /// <param name="endLineNumber">Indexed from 1</param> /// <param name="projectFile"></param> /// <param name="set"></param> /// <param name="range"></param> public Block(int startLineNumber, int endLineNumber, IProjectFile projectFile, Set set, DocumentRange? range) { Range = range; this.set = set; this.projectFile = projectFile; this.startLineNumber = startLineNumber; this.endLineNumber = endLineNumber; }
/// <summary> /// Initializes a new instance of the <see cref="StyleCopHighlightingBase"/> class. /// </summary> /// <param name="violationEventArgs"> /// The <see cref="StyleCop.ViolationEventArgs"/> instance containing the Violation data. /// </param> /// <param name="documentRange"> /// Range where the Violation happened. /// </param> protected StyleCopHighlightingBase(ViolationEventArgs violationEventArgs, DocumentRange documentRange) { this.CheckId = violationEventArgs.Violation.Rule.CheckId; this.ToolTip = violationEventArgs.Message + " [StyleCop Rule: " + this.CheckId + "]"; this.documentRange = documentRange; this.Rule = violationEventArgs.Violation.Rule; this.Violation = violationEventArgs.Violation; }
public NTriplesIntentionResult( List<ITemplateFieldHolder> holders, IDeclaration declaration, ITreeNode anchor, DocumentRange range) { this.myDeclaration = declaration; this.myHolders = holders; this.myPreferredSelection = range; this.myAnchor = anchor; }
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var methodDeclaration = _highlighting.MethodDeclaration; methodDeclaration.SetExtern(false); var textRange = LanguageManager.Instance.GetService<IMemberBodyOperations>(methodDeclaration.Language).SetBodyToDefault(methodDeclaration); var rangeMarker = new DocumentRange(methodDeclaration.GetDocumentRange().Document, textRange).CreateRangeMarker(DocumentManager.GetInstance(solution)); return control => control.Selection.SetRange(rangeMarker.Range); }
private void AddHighLighting(DocumentRange range, ITreeNode element, IHighlightingConsumer consumer, IHighlighting highlighting) { var info = new HighlightingInfo(range, highlighting, new Severity?()); IFile file = element.GetContainingFile(); if (file != null) { consumer.AddHighlighting(info.Highlighting, file); } }
/// <summary> /// Initializes a new instance of the <see cref="StyleCopViolationBase"/> class. /// </summary> /// <param name="violation"> /// The <see cref="StyleCop.ViolationEventArgs"/> instance containing the Violation data. /// </param> /// <param name="documentRange"> /// Range where the Violation happened. /// </param> /// <param name="fileName"> /// The file Name. /// </param> /// <param name="lineNumber"> /// Line number of where the violation happened. /// </param> protected StyleCopViolationBase(ViolationEventArgs violation, DocumentRange documentRange, string fileName, int lineNumber) { this.CheckId = violation.Violation.Rule.CheckId; this.ToolTip = violation.Message + " [StyleCop Rule: " + this.CheckId + "]"; this.DocumentRange = documentRange; this.FileName = fileName; this.LineNumber = lineNumber; this.Rule = violation.Violation.Rule; }
internal RequiresExceptionValidityHighlighting(IInvocationExpression invocationExpression, IClass exceptionDeclaration, MemberWithAccess preconditionContainer) { Contract.Requires(exceptionDeclaration != null); Contract.Requires(preconditionContainer != null); Contract.Requires(invocationExpression != null); _range = invocationExpression.GetHighlightingRange(); _exceptionDeclaration = exceptionDeclaration; _preconditionContainer = preconditionContainer; }
internal MalformedContractErrorHighlighting(ICSharpStatement statement, CodeContractStatement validatedStatement, ValidationResult validationResult) { Contract.Requires(validatedStatement != null); Contract.Requires(validationResult != null); _range = statement.GetHighlightingRange(); _validatedStatement = validatedStatement; _validationResult = validationResult; _toolTip = _validationResult.GetErrorText(); }
public void Execute(Action<DaemonStageResult> commiter) { try { // GetText gives the unsaved file contents, unlike file.ProjectFile.GetReadStream(). string codeText = myDaemonProcess.Document.GetText(); // I do not remember anymore why I created the Shallow version... var cloneFinder = new MethodsOnASingleClassCloneFinder(new ShallowExpansionFactory()); //var cloneFinder = new MethodsOnASingleClassCloneFinder(new OscillatingExtractMethodExpansionFactory()); cloneFinder.AddRefactoring(new LiteralToParameterExpansion()); ScanResult scan_result = cloneFinder.GetCloneReplacements(codeText); if (scan_result != null) { var document = myDaemonProcess.SourceFile.Document; var Highlightings = new List<HighlightingInfo>(); foreach (var info in scan_result.Clones) { // We basically highlight the first line of the clone. var start = document.GetLineStartOffset(((Int32<DocLine>) (info.HighlightStartLocationLine - 1))) + info.HighlightStartLocationColumn; var end = start + info.HighlightLength;// Hmm, HighlightLength seems sort of arbitrary. var warningHighlightRange = new DocumentRange(document, new TextRange(start, end)); // And this defines the chunk that gets replaced. var replacedCodeRange = new DocumentRange(document, new TextRange( document.GetLineStartOffset( (Int32<DocLine>) (info.ReplacementSectionStartLine-1)), document.GetLineStartOffset( (Int32<DocLine>) info.ReplacementSectionEndLine))); var highlight = new HighlightingInfo(warningHighlightRange, new CloneDetectionHighlighting(info, replacedCodeRange)); Highlightings.Add(highlight); } // Creating container to put highlightings into. DaemonStageResult ret = new DaemonStageResult(Highlightings); commiter(ret); } } catch (Exception e) { System.Diagnostics.Debug.Write(e); throw; } }
internal RequiresInconsistentVisibiityHighlighting(ICSharpStatement preconditionStatement, MemberWithAccess preconditionContainer, MemberWithAccess lessVisibleReferencedMember) { Contract.Requires(preconditionStatement != null); Contract.Requires(preconditionContainer != null); Contract.Requires(lessVisibleReferencedMember != null); _range = preconditionStatement.GetHighlightingRange(); _preconditionContainer = preconditionContainer; _lessVisibleReferencedMember = lessVisibleReferencedMember; }
internal CodeContractWarningHighlighting(ICSharpStatement statement, CodeContractWarningValidationResult warning, ValidatedContractBlock contractBlock) { Contract.Requires(warning != null); Contract.Requires(contractBlock != null); Contract.Requires(statement != null); _warning = warning; _contractBlock = contractBlock; _range = statement.GetHighlightingRange(); _toolTip = warning.GetErrorText(); }
internal LegacyContractCustomWarningHighlighting(ICSharpFunctionDeclaration element, CustomWarningValidationResult warning, ValidatedContractBlock contractBlock) { Contract.Requires(warning != null); Contract.Requires(contractBlock != null); _toolTip = warning.GetErrorText(); _range = element.GetHighlightingRange(); _validationResult = warning; _contractBlock = contractBlock; MethodName = warning.GetEnclosingMethodName(); }
protected PostfixLookupItem( [NotNull] string shortcut, [NotNull] PrefixExpressionContext context) { myIdentifier = shortcut; myShortcut = shortcut.ToLowerInvariant(); myWasReparsed = !context.Expression.IsPhysical(); var shift = myWasReparsed ? +2 : 0; myExpressionRange = context.ExpressionRange.CreateRangeMarker(); myReferenceRange = context.Parent.PostfixReferenceRange.CreateRangeMarker(); myReferenceType = context.Parent.PostfixReferenceNode.GetType(); myReplaceRange = context.ReplaceRange.ExtendRight(shift); }
internal ContractCustomWarningHighlighting(ICSharpStatement statement, CustomWarningValidationResult warning, ValidatedContractBlock contractBlock) { Contract.Requires(warning != null); Contract.Requires(contractBlock != null); Contract.Assert(_range != null); _range = statement.GetHighlightingRange(); _toolTip = warning.GetErrorText(); _validationResult = warning; _contractBlock = contractBlock; MethodName = warning.GetEnclosingMethodName(); }
private static Pair<IT4File, IFile> GetFiles([NotNull] IPsiSourceFile sourceFile, DocumentRange documentRange) { IT4File primaryFile = null; IFile secondaryFile = null; foreach (Pair<IFile, TreeTextRange> pair in sourceFile.EnumerateIntersectingPsiFiles(documentRange)) { var t4File = pair.First as IT4File; if (t4File != null) primaryFile = t4File; else secondaryFile = pair.First; } return Pair.Of(primaryFile, secondaryFile); }
public static DocumentRange GetFooterTagRange(IElement element, DocumentRange range) { IXmlTag tag = element as IXmlTag; if (tag == null) return DocumentRange.InvalidRange; if (tag.ToTreeNode().Header.Name.GetDocumentRange().TextRange == range.TextRange) { IXmlTagFooterNode footer = tag.ToTreeNode().Footer; if (footer != null) return footer.Name.GetDocumentRange(); } return DocumentRange.InvalidRange; }
public UnityColorReference(IColorElement colorElement, IExpression owningExpression, ITreeNode owner, DocumentRange colorConstantRange) { myOwningExpression = owningExpression; ColorElement = colorElement; Owner = owner; ColorConstantRange = colorConstantRange; BindOptions = new ColorBindOptions { BindsToName = true, BindsToValue = true }; }
internal ContractPublicPropertyNameHighlighing(IFieldDeclaration fieldDeclaration, string referingFieldOrPropertyName, ICSharpTypeMemberDeclaration referingFieldOrProperty) { Contract.Requires(fieldDeclaration != null); Contract.Requires(referingFieldOrPropertyName != null); _range = fieldDeclaration.GetHighlightingRange(); _fieldDeclaration = fieldDeclaration; _referingFieldOrProperty = referingFieldOrProperty; FieldName = fieldDeclaration.NameIdentifier.With(x => x.Name); PropertyName = referingFieldOrPropertyName; FieldType = fieldDeclaration.Type.GetLongPresentableName(CSharpLanguage.Instance); }
private static Pair<IT4File, IFile> GetFiles([NotNull] IPsiSourceFile sourceFile, DocumentRange documentRange) { IT4File primaryFile = null; IFile secondaryFile = null; foreach (IFile file in sourceFile.EnumeratePsiFiles(documentRange)) { var t4File = file as IT4File; if (t4File != null) primaryFile = t4File; else secondaryFile = file; } return Pair.Of(primaryFile, secondaryFile); }
/// <summary> /// Gets the actions for changing the highlight options for StyleCop rules. /// </summary> /// <param name="highlighting"> /// The current highlighting. /// </param> /// <param name="highlightingRange"> /// The current highlighting range. /// </param> /// <returns> /// The available actions. /// </returns> public IEnumerable<IDisableHighlightingAction> Actions(IHighlighting highlighting, DocumentRange highlightingRange) { StyleCopViolationBase violation = highlighting as StyleCopViolationBase; if (violation == null) { return JB::JetBrains.Util.EmptyArray<IDisableHighlightingAction>.Instance; } string ruleID = violation.CheckId; string highlightID = HighlightingRegistering.GetHighlightID(ruleID); return new IDisableHighlightingAction[] { new ChangeStyleCopRuleAction { HighlightID = highlightID, Text = "Inspection Options for \"" + violation.ToolTip + "\"" } }; }
public Form1() { InitializeComponent(); ribbonControl1.SelectedPage = ribbonControl1.Pages[1]; myUserList.AddRange(new MyUser[] { new MyUser("Nancy Skywalker", "Skywalkers"), new MyUser("Andrew Nihlus", "Nihlus"), new MyUser("Janet Skywalker", "Skywalkers"), new MyUser("Margaret", "Editors") }); #region #RegisterUserListService richEditControl1.ReplaceService <IUserListService>(new MyUserListService(myUserList)); #endregion #RegisterUserListService #region #RegisterGroupListService richEditControl1.ReplaceService <IUserGroupListService>(new MyGroupListService()); #endregion #RegisterGroupListService richEditControl1.DocumentLoaded += richEditControl1_DocumentLoaded; richEditControl1.CreateNewDocument(); #region #AddPermissionsToRanges // Create document ranges. DocumentRange rangeAdmin = AppendDocument("Documents\\administrator.docx"); DocumentRange rangeBody = AppendDocument("Documents\\body.docx"); DocumentRange rangeSignature = AppendDocument("Documents\\signature.docx"); // Protect document ranges. RangePermissionCollection rangePermissions = richEditControl1.Document.BeginUpdateRangePermissions(); rangePermissions.AddRange(CreateRangePermissions(rangeAdmin, String.Empty, "*****@*****.**", "Nancy Skywalker")); rangePermissions.AddRange(CreateRangePermissions(rangeBody, "Everyone", String.Empty)); rangePermissions.AddRange(CreateRangePermissions(rangeSignature, "Skywalkers", String.Empty)); richEditControl1.Document.EndUpdateRangePermissions(rangePermissions); // Enforce protection and set password. richEditControl1.Document.Protect("123"); #endregion #AddPermissionsToRanges UpdateUserNameLoginCombo(); }
static void CreateNewCharacterStyle(Document document) { #region #CreateNewCharacterStyle document.LoadDocument("Documents//Grimm.docx", DevExpress.XtraRichEdit.DocumentFormat.OpenXml); CharacterStyle cstyle = document.CharacterStyles["MyCStyle"]; if (cstyle == null) { cstyle = document.CharacterStyles.CreateNew(); cstyle.Name = "MyCStyle"; cstyle.Parent = document.CharacterStyles["Default Paragraph Font"]; cstyle.ForeColor = System.Drawing.Color.DarkOrange; cstyle.Strikeout = StrikeoutType.Double; cstyle.FontName = "Verdana"; document.CharacterStyles.Add(cstyle); } DocumentRange myRange = document.Paragraphs[0].Range; CharacterProperties charProps = document.BeginUpdateCharacters(myRange); charProps.Style = cstyle; document.EndUpdateCharacters(charProps); #endregion #CreateNewCharacterStyle }
private void richEditControl1_DragDrop(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent(DataFormats.FileDrop)) { return; } string path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0]; RichEditDocumentServer server = new RichEditDocumentServer(); server.LoadDocument(path); richEditControl1.Document.BeginUpdate(); DocumentRange rangeInsertedContent = richEditControl1.Document.InsertDocumentContent( richEditControl1.Document.CaretPosition, server.Document.Range); DocumentRange rangeNewLine = richEditControl1.Document.CreateRange(rangeInsertedContent.End.ToInt() - 1, 1); richEditControl1.Document.Delete(rangeNewLine); richEditControl1.Document.EndUpdate(); richEditControl1.Options.Behavior.Drop = DevExpress.XtraRichEdit.DocumentCapability.Enabled; }
/// <summary> /// The format body. /// </summary> /// <param name="statement">The body.</param> public static void Format(this ITreeNode statement) { if (!statement.IsPhysical()) { return; } var documentRange = statement.GetDocumentRange(); if (!documentRange.IsValid()) { return; } var containingFile = statement.GetContainingFile(); var psiSourceFile = containingFile?.GetSourceFile(); if (psiSourceFile == null) { return; } var document = psiSourceFile.Document; var solution = statement.GetPsiServices().Solution; var languageService = statement.Language.LanguageService(); var codeFormatter = languageService?.CodeFormatter; if (codeFormatter == null) { return; } var rangeMarker = new DocumentRange(document, documentRange.TextRange).CreateRangeMarker(DocumentManager.GetInstance(solution)); containingFile.OptimizeImportsAndRefs(rangeMarker, false, true, NullProgressIndicator.Instance); codeFormatter.Format(statement, CodeFormatProfile.DEFAULT); }
private void FetchTextOccurences([NotNull] ITreeNode textToken, IFindResultConsumer <TResult> consumer) { var file = textToken.GetContainingFile(); if (file != null) { var text = textToken.GetText(); var textLength = text.Length; foreach (string name in myTexts) { var nameLength = name.Length; for (int start = 0; start < textLength;) { int pos = text.IndexOf(name, start, StringComparison.Ordinal); if (pos < 0) { break; } var range = textToken.GetDocumentRange(); if (range.IsValid()) { var textRange = new TextRange(range.TextRange.StartOffset + pos, range.TextRange.StartOffset + pos + nameLength); var nameDocumentRange = new DocumentRange(range.Document, textRange); var translatedRange = file.Translate(nameDocumentRange); if (!DeclarationExists(textToken, translatedRange) && !ReferenceExists(file, translatedRange)) { consumer.Accept(new FindResultText(file.GetSourceFile(), nameDocumentRange)); } } start = pos + nameLength; } } } }
public ISelectedRange GetSelectedRange(IPsiSourceFile sourceFile, DocumentRange documentRange) { Pair <IT4File, IFile> pair = GetFiles(sourceFile, documentRange); IT4File t4File = pair.First; IFile codeBehindFile = pair.Second; if (t4File == null) { return(null); } ITreeNode t4Node = t4File.FindNodeAt(documentRange); if (t4Node == null) { return(null); } // if the current selection is inside C# code, use the C# extend selection directly if (codeBehindFile != null) { ISelectEmbracingConstructProvider codeBehindProvider = PsiShared.GetComponent <PsiProjectFileTypeCoordinator>() .GetByPrimaryPsiLanguageType(codeBehindFile.Language) .SelectNotNull(fileType => Shell.Instance.GetComponent <IProjectFileTypeServices>().TryGetService <ISelectEmbracingConstructProvider>(fileType)) .FirstOrDefault(); if (codeBehindProvider != null) { ISelectedRange codeBehindRange = codeBehindProvider.GetSelectedRange(sourceFile, documentRange); if (codeBehindRange != null) { return(new T4CodeBehindWrappedSelection(t4File, codeBehindRange)); } } } return(new T4NodeSelection(t4File, t4Node)); }
// To fix offset issue had to implement ExecuteAfterPsiTransaction. // http://stackoverflow.com/questions/22545558/resharper-quickfix-highlighter-offset-issue protected override Action <ITextControl> ExecuteAfterPsiTransaction(ISolution solution, IProjectModelTransactionCookie cookie, IProgressIndicator progress) { DocumentRange docRange = _highlighter.Declaration.GetDocumentRange(); IDocument textDoc = _highlighter.Declaration.GetSourceFile().Document; if (textDoc != null) { for (int i = 0; i < textDoc.GetTextLength(); i++) { int docRangeEndOffSet = docRange.TextRange.EndOffset + i; int docRangeStart = docRange.TextRange.StartOffset; string docRangeString = docRange.Document.GetText(new TextRange(docRange.TextRange.StartOffset, docRangeEndOffSet)); int location; if (docRangeString.EndsWith("\r\n")) { var lineEnd = docRangeString.LastIndexOf(";\r\n"); if (lineEnd >= 0) { location = docRangeStart + lineEnd + 1; using (solution.CreateTransactionCookie(DefaultAction.Commit, "L10N insterted")) { textDoc.InsertText(location, " // Not L10N"); } break; } location = docRangeEndOffSet - 2; using (solution.CreateTransactionCookie(DefaultAction.Commit, "L10N insterted")) { textDoc.InsertText(location, " // Not L10N"); } break; } } } return(null); }
private void CheckWordSpelling( IClassMemberDeclaration decl, Range wordRange, IHighlightingConsumer highlightingConsumer, DocumentRange range, IFile file) { // If we dont have a spell checker then go no further if (this._xmlDocumentationSpellChecker == null) { return; } // First check the whole word range. if (!SpellCheckUtil.ShouldSpellCheck(wordRange.Word, _xmlDocumentationSettings.CompiledWordsToIgnore) || this._xmlDocumentationSpellChecker.TestWord(wordRange.Word, true)) { return; } // We are checking this word and the whole range doesn't spell anything so try breaking the word into bits. CamelHumpLexer camelHumpLexer = new CamelHumpLexer(wordRange.Word, 0, wordRange.Word.Length); foreach (LexerToken humpToken in camelHumpLexer) { if (SpellCheckUtil.ShouldSpellCheck(humpToken.Value, _xmlDocumentationSettings.CompiledWordsToIgnore) && !this._xmlDocumentationSpellChecker.TestWord(humpToken.Value, true)) { var highlighting = new WordIsNotInDictionaryHighlight(wordRange.Word, range, humpToken, _solution, this._xmlDocumentationSpellChecker, _settingsStore); highlightingConsumer.AddHighlighting(highlighting, range, file); break; } } }
public IParameterInfoContext CreateContext(ISolution solution, IDocument document, int caretOffset, int expectedLParenthOffset, char invocationChar, IContextBoundSettingsStore contextBoundSettingsStore) { if (!solution.GetComponent <PsiIntellisenseManager>().GetIntellisenseEnabled(contextBoundSettingsStore)) { return(null); } var documentRange = new DocumentRange(document, caretOffset); var file = solution.GetPsiServices().GetPsiFile <PsiLanguage>(documentRange); if (file == null) { return(null); } var contextRange = file.Translate(documentRange); if (!contextRange.IsValid()) { return(null); } var tokenElement = file.FindTokenAt(contextRange.StartOffset) as ITokenNode; if (tokenElement == null) { return(null); } var ruleNameUsage = tokenElement.GetContainingNode <RuleNameUsage>(); if (ruleNameUsage == null) { return(null); } return(new PsiParameterInfoContext(ruleNameUsage, 0)); }
private void CreateProtectedRanges(Document document) { DocumentPosition lastNonProtectedPosition = document.Range.Start; bool containsProtectedRanges = false; RangePermissionCollection rangePermissions = richEditControl1.Document.BeginUpdateRangePermissions(); for (int i = 0; i < document.Bookmarks.Count; i++) { Bookmark protectedBookmark = document.Bookmarks[i]; if (protectedBookmark.Name.Contains("protectedRange")) { containsProtectedRanges = true; rangePermissions.AddRange(CreateRangePermissions(protectedBookmark.Range, "Admin", "Admin")); if (protectedBookmark.Range.Start.ToInt() > lastNonProtectedPosition.ToInt()) { DocumentRange rangeAfterProtection = richEditControl1.Document.CreateRange(lastNonProtectedPosition, protectedBookmark.Range.Start.ToInt() - lastNonProtectedPosition.ToInt() - 1); rangePermissions.AddRange(CreateRangePermissions(rangeAfterProtection, "User", "User")); } lastNonProtectedPosition = protectedBookmark.Range.End; } } if (document.Range.End.ToInt() > lastNonProtectedPosition.ToInt()) { DocumentRange rangeAfterProtection = richEditControl1.Document.CreateRange(lastNonProtectedPosition, document.Range.End.ToInt() - lastNonProtectedPosition.ToInt() - 1); rangePermissions.AddRange(CreateRangePermissions(rangeAfterProtection, "User", "User")); } richEditControl1.Document.EndUpdateRangePermissions(rangePermissions); if (containsProtectedRanges) { document.Protect("123"); richEditControl1.Options.Authentication.UserName = "******"; richEditControl1.Options.Authentication.Group = "User"; richEditControl1.Options.RangePermissions.Visibility = DevExpress.XtraRichEdit.RichEditRangePermissionVisibility.Hidden; } }
private CompilerDirective ParseCompilerDirective() { DocumentRange location = this.Consume(TokenType.Pragma).Location; TokenIdentifier identifier = this.GetIdentifier(); string str = this.ParseSingleStringParameter(); string valueUpperCase = identifier.ValueUpperCase; string str1 = valueUpperCase; if (valueUpperCase != null) { if (str1 == "INCLUDE") { return(new PragmaInclude(location, str)); } else { if (str1 == "INSTANCELOCALE") { return(new PragmaInstanceLocale(location, str)); } else { if (str1 == "LOCALE") { return(new PragmaLocale(location, str)); } else { if (str1 == "NAMESPACE") { return(new PragmaNamespace(location, str)); } } } } } throw new ParseFailureException(string.Format("Unexpected #pragma type: {0}", identifier.Value), identifier.Location); }
static void SelectCellsAndMerge(Document document) { #region #SelectCellsAndMerge document.LoadDocument("Documents//SelectionCollection.docx", DocumentFormat.OpenXml); Table rootTable = document.Tables[0]; DocumentPosition position10 = rootTable.Rows[1].Cells[0].Range.Start; DocumentPosition position11 = rootTable.Rows[1].Cells[1].Range.Start; DocumentPosition position20 = rootTable.Rows[2].Cells[0].Range.Start; DocumentRange range1 = document.CreateRange(position10, position11.ToInt() - position10.ToInt()); DocumentRange range2 = document.CreateRange(position11, position20.ToInt() - position11.ToInt()); List <DocumentRange> ranges = new List <DocumentRange>() { range1, range2 }; document.Selections.Add(ranges); Comment comment = document.Comments.Create(document.Selection, ""); SubDocument commentDoc = comment.BeginUpdate(); commentDoc.AppendText(String.Format("\r\nSelectionCollection \r\ncontains {0} item(s).", document.Selections.Count)); comment.EndUpdate(commentDoc); #endregion #SelectCellsAndMerge }
private void DoTest([NotNull] params string[] fileNames) => WithSingleProject(fileNames, (lifetime, solution, project) => { foreach (string fileName in fileNames) { var projectFile = project.GetSubFiles(fileName).Single(); var psiFile = (IT4File)projectFile.GetPrimaryPsiFile().NotNull(); var translator = ((IT4FileLikeNode)psiFile).DocumentRangeTranslator; var document = projectFile.GetDocument(); for (int offset = 1; offset < document.GetTextLength() - 1; offset += 1) { // Do not want to analyze edge cases here if (IsEdgeOfIncludeCase(document, offset)) { continue; } var originalDocumentRange = new DocumentRange(new DocumentOffset(document, offset)); var treeRange = translator.Translate(originalDocumentRange); var resultingRange = translator.Translate(treeRange); Assert.AreEqual(originalDocumentRange, resultingRange); } } });
private IEnumerable <HighlightingInfo> GetHighlightings([NotNull] ITextControl textControl) { if (UseUnderCaretHighlighter) { var highlightingsUnderCaretProvider = Solution.GetComponent <HighlightingsUnderCaretProvider>(); var highlighter = highlightingsUnderCaretProvider.GetHighlighterUnderCaret(textControl) .NotNull("highlighter != null"); var analysisRange = new DocumentRange(textControl.Caret.DocumentOffset()); return(highlighter.GetHighlightingsForRange(analysisRange)); } var sourceFile = textControl.Document.GetPsiSourceFile(Solution).NotNull(); var daemonProcessMock = new DaemonProcessMock(sourceFile); daemonProcessMock.DoHighlighting(DaemonProcessKind.VISIBLE_DOCUMENT); // next line is only difference with QuickFixAvailabilityTestBase // CGTD overlook. is it even ok? daemonProcessMock.DoHighlighting(DaemonProcessKind.GLOBAL_WARNINGS); return(daemonProcessMock.Highlightings); }
static void EditFootnote(RichEditDocumentServer wordProcessor) { #region #EditFootnote wordProcessor.LoadDocument("Documents//Grimm.docx"); Document document = wordProcessor.Document; //Access the first footnote's content: SubDocument footnote = document.Footnotes[0].BeginUpdate(); //Exclude the reference mark and the space after it from the range to be edited: DocumentRange noteTextRange = footnote.CreateRange(footnote.Range.Start.ToInt() + 2, footnote.Range.Length - 2); //Clear the range: footnote.Delete(noteTextRange); //Append a new text: footnote.AppendText("the text is removed"); //Finalize the update: document.Footnotes[0].EndUpdate(footnote); #endregion #EditFootnote }
void CreateMenuItems(RichEditPopupMenu menu, DocumentRange range, string word) { SuggestionCollection suggestions = this.spellChecker1.GetSuggestions(word); int count = suggestions.Count; if (count > 0) { int lastIndex = Math.Min(count - 1, 5); for (int i = lastIndex; i >= 0; i--) { SuggestionBase suggestion = suggestions[i]; SuggestionMenuItem item = new SuggestionMenuItem(rtControl.Document, suggestion.Suggestion, range); menu.Items.Insert(0, item); } } else { DXMenuItem emptyItem = new DXMenuItem("no spelling suggestions"); emptyItem.Enabled = false; menu.Items.Insert(0, emptyItem); } }
private ClassDeclaration ParseClass(QualifierList qualifiers) { DocumentRange location = this.Consume(KeywordType.CLASS).Location; ClassName className = this.ParseClassName(); AliasIdentifier aliasIdentifier = null; if (!this.PeekKeyword(KeywordType.AS)) { ClassName className1 = null; if (this.TryConsume(TokenType.Colon)) { className1 = this.ParseClassName(); } this.Consume(TokenType.OpenBrace); ClassFeatureList classFeatureList = this.ParseClassFeatureList(); this.Consume(TokenType.Semicolon); return(new ClassDeclaration(location, className, aliasIdentifier, className1, qualifiers, classFeatureList)); } else { throw new NotSupportedException(); } }
public override void VisitRuleName(IRuleName ruleNameParam, IHighlightingConsumer consumer) { var ruleName = ruleNameParam as RuleName; if (ruleName != null) { DocumentRange colorConstantRange = ruleName.GetDocumentRange(); ResolveResultWithInfo resolve = ruleName.RuleNameReference.Resolve(); bool isRuleResolved = resolve.Result.DeclaredElement != null || (resolve.Result.Candidates.Count > 0); if (isRuleResolved) { AddHighLighting(colorConstantRange, ruleName, consumer, new PsiRuleHighlighting(ruleName)); } else { AddHighLighting(colorConstantRange, ruleName, consumer, new PsiUnresolvedRuleReferenceHighlighting(ruleName)); } base.VisitRuleName(ruleName, consumer); } }
private TextLookupRanges EvaluateRanges(ISpecificCodeCompletionContext context) { var file = context.BasicContext.File as IPsiFile; DocumentRange selectionRange = context.BasicContext.SelectedRange; if (file != null) { var token = file.FindNodeAt(selectionRange) as ITokenNode; if (token != null) { DocumentRange tokenRange = token.GetNavigationRange(); var insertRange = new TextRange(tokenRange.TextRange.StartOffset, selectionRange.TextRange.EndOffset); var replaceRange = new TextRange(tokenRange.TextRange.StartOffset, Math.Max(tokenRange.TextRange.EndOffset, selectionRange.TextRange.EndOffset)); return(new TextLookupRanges(insertRange, replaceRange)); } } return(new TextLookupRanges(TextRange.InvalidRange, TextRange.InvalidRange)); }
//------------------------------------------------------------------------------------------------------------------------ private static IList <IProjectFile> GetProjectFiles(DocumentManager documentManager, IDeclaredElement declaredElement) { IList <IProjectFile> results = new List <IProjectFile>(); foreach (var declaration in declaredElement.GetDeclarations()) { DocumentRange documentRange = declaration.GetNavigationRange(); if (!documentRange.IsValid()) { documentRange = TreeNodeExtensions.GetDocumentRange(declaration); } if (documentRange.IsValid()) { IProjectFile projectFile = documentManager.TryGetProjectFile(documentRange.Document); if (projectFile != null) { results.Add(projectFile); } } } return(results); }
private DeclaredElementInfo FindDeclaredElement(DocumentRange documentRange) { IDocument document = documentRange.Document; if (document == null || !documentRange.IsValid()) { return(null); } IPsiServices psiServices = _solution.GetPsiServices(); if (!psiServices.Files.AllDocumentsAreCommitted || psiServices.Caches.HasDirtyFiles) { return(null); } return(document .GetPsiSourceFiles(_solution) .SelectMany( psiSourceFile => psiServices.Files.GetPsiFiles(psiSourceFile, documentRange), (psiSourceFile, file) => FindDeclaredElement(documentRange, file)) .FirstOrDefault(info => info != null && info.DeclaredElement.IsValid())); }
static void ChangeHeaderCharacterProperties(Document doc, DocumentRange headerRange, int headerLevel) { CharacterProperties cp = doc.BeginUpdateCharacters(headerRange); cp.ForeColor = Color.Blue; if (headerLevel == 1) { cp.Bold = true; cp.FontSize = 16; } if (headerLevel == 2) { cp.Bold = true; cp.FontSize = 12; } if (headerLevel == 3) { cp.Bold = false; cp.FontSize = 12; } doc.EndUpdateCharacters(cp); }
// todo: make lazy private static void SearchInCurrentFile( [NotNull] string searchText, [NotNull] IPsiSourceFile sourceFile, [NotNull] List <LocalOccurrence> consumer) { var document = sourceFile.Document; var fileText = document.GetText(); if (fileText == null) { return; } var offset = 0; while ((offset = fileText.IndexOf(searchText, offset, StringComparison.OrdinalIgnoreCase)) >= 0) { var occurrenceRange = TextRange.FromLength(offset, searchText.Length); var documentRange = new DocumentRange(document, occurrenceRange); var coords = (int)document.GetCoordsByOffset(offset).Line; var foundText = fileText.Substring(offset, searchText.Length); var leftIndex = Math.Max(0, offset - 10); var leftFragment = fileText.Substring(leftIndex, offset - leftIndex); var endOffset = offset + searchText.Length; var rightIndex = Math.Min(endOffset + 10, fileText.Length); var rightFragment = fileText.Substring(endOffset, rightIndex - endOffset); consumer.Add(new LocalOccurrence( documentRange, coords, foundText, leftFragment, rightFragment)); offset++; } }
private IdentifierContentGroup GetIdentifierContentGroupCore( DocumentRange documentRange, [NotNull] IContextBoundSettingsStore settings, [CanBeNull] IHighlighter highlighter) { DeclaredElementInfo info = FindDeclaredElement(documentRange); if (info == null) { return(null); } IdentifierTooltipContent standardContent = TryPresentColorized(info, settings) ?? TryPresentNonColorized(highlighter, info.DeclaredElement, settings); bool replacesStandardContent; IdentifierTooltipContent additionalContent = TryGetAdditionalIdentifierContent(info, settings, out replacesStandardContent); if (replacesStandardContent) { standardContent = additionalContent; additionalContent = null; } var result = new IdentifierContentGroup(); if (standardContent != null) { result.Identifiers.Add(standardContent); } if (additionalContent != null) { result.Identifiers.Add(additionalContent); } result.ArgumentRole = TryGetArgumentRoleContent(info.TreeNode, settings); return(result); }
public void CheckCommentSpelling(IClassMemberDeclaration decl, [CanBeNull] IDocCommentBlock docNode, DefaultHighlightingConsumer consumer, bool spellCheck) { if (docNode == null) { return; } IFile file = decl.GetContainingFile(); if (file == null) { return; } foreach (Range wordRange in this.GetWordsFromXmlComment(docNode)) { DocumentRange range = file.GetDocumentRange(wordRange.TreeTextRange); string word = wordRange.Word; if (decl.DeclaredName != word) { if ((IdentifierResolver.IsIdentifier(decl, _solution, word, _identifierSettings.IdentifierLookupScope) || IdentifierResolver.IsKeyword(decl, _solution, word)) && IdentifierResolver.AnalyzeForMetaTagging(word, _xmlDocumentationSettings.CompiledWordsToIgnoreForMetatagging)) { consumer.AddHighlighting( new CanBeSurroundedWithMetatagsHighlight(word, range, decl, _solution), range); } else if (spellCheck) { this.CheckWordSpelling(decl, wordRange, consumer, range); } } } }
private static DeclaredElementInstance FindElement([NotNull] IFile file, DocumentRange range) { TreeTextRange treeTextRange = file.Translate(range); if (!treeTextRange.IsValid()) { return(null); } // First finds a reference. IReference[] references = file.FindReferencesAt(treeTextRange); if (references.Length > 0) { return(GetBestReference(references)); } // Or a declaration. ITreeNode nodeAt = file.FindNodeAt(treeTextRange); if (nodeAt == null) { return(null); } var containingNode = nodeAt.GetContainingNode <IDeclaration>(true); if (containingNode != null && containingNode.GetNameDocumentRange() == range) { IDeclaredElement declaredElement = containingNode.DeclaredElement; if (declaredElement != null) { return(new DeclaredElementInstance(declaredElement, EmptySubstitution.INSTANCE)); } } return(null); }
private void btn_ParStyle_Click(object sender, EventArgs e) { #region #parstyle Document doc = richEditControl1.Document; ParagraphStyle pstyle = doc.ParagraphStyles["MyParagraphStyle"]; if (pstyle == null) { pstyle = doc.ParagraphStyles.CreateNew(); pstyle.Name = "MyParagraphStyle"; pstyle.Parent = doc.ParagraphStyles["Normal"]; pstyle.Alignment = ParagraphAlignment.Justify; pstyle.LineSpacingType = ParagraphLineSpacing.Single; pstyle.FirstLineIndentType = ParagraphFirstLineIndent.None; doc.ParagraphStyles.Add(pstyle); } DocumentRange range = doc.Selection; ParagraphProperties parProps = doc.BeginUpdateParagraphs(range); parProps.FirstLineIndentType = null; parProps.Alignment = ParagraphAlignment.Justify; parProps.Style = pstyle; doc.EndUpdateParagraphs(parProps); #endregion #parstyle }
public void AssignFace(DocumentRange target, IStyleFace face) { if (face == null) { return; } var line = target.Start.Line; var column = target.Start.Column; while (line <= target.End.Line) { var chRange = line == target.End.Line ? new CharacterRange(column, target.End.Column - column) : new CharacterRange(column, Rows[line].Length); getRowStyles(line).Add(new FaceApplied(face.Name, chRange)); fireFaceChanged(Rows[line]); column = 0; line++; } }
private void simpleButton3_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = true; if (ofd.ShowDialog() == DialogResult.OK) { if (!Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\Fajlovi")) { Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\Fajlovi"); } List <string> fajlovi = ofd.FileNames.ToList(); foreach (string file in fajlovi) { string ime = Guid.NewGuid().ToString(); string uri = System.Windows.Forms.Application.StartupPath + "\\Fajlovi" + "\\" + ime + Path.GetExtension(file); File.Copy(file, uri); string file1 = Path.GetFileName(file) + System.Environment.NewLine; DocumentRange range = richEditControl1.Document.AppendText(file1); Hyperlink hyperlink = richEditControl1.Document.CreateHyperlink(range); hyperlink.NavigateUri = uri; } } }
private void btn_CharStyle_Click(object sender, EventArgs e) { #region #charstyle Document doc = richEditControl1.Document; CharacterStyle cstyle = doc.CharacterStyles["MyCharStyle"]; if (cstyle == null) { cstyle = doc.CharacterStyles.CreateNew(); cstyle.Name = "MyCharStyle"; cstyle.Parent = doc.CharacterStyles["Default Paragraph Font"]; cstyle.ForeColor = Color.DarkOrange; cstyle.Strikeout = StrikeoutType.Double; cstyle.FontName = "Verdana"; doc.CharacterStyles.Add(cstyle); } DocumentRange range = doc.Selection; CharacterProperties charProps = doc.BeginUpdateCharacters(range); charProps.Style = cstyle; doc.EndUpdateCharacters(charProps); #endregion #charstyle }