public static string Format(string input, FormattingContext ctx) { var context = ctx ?? new FormattingContext(); // Aggregate is essentially a foreach loop through the FormattingSchemes, doing // current = current.Replace(...); return FormattingSchemes .Aggregate(input, (current, scheme) => current.Replace(scheme.Symbol, scheme.Factory(context))); }
internal override IEnumerable<TextEditInfo> Apply(FormattingContext formattingContext) { Token nextToken = formattingContext.NextToken.Token; // flag for the end of file token where whitespace should be deleted List<TextEditInfo> edits = this.GetEdits(nextToken, nextToken.Kind == SyntaxKind.EndOfFile); return edits; }
internal override IEnumerable<TextEditInfo> Apply(FormattingContext formattingContext) { Token leftToken = formattingContext.CurrentToken.Token; Token rightToken = formattingContext.NextToken.Token; int start = leftToken.Start + leftToken.Text.Length; int length = rightToken.Start - start; string replaceWith = this.GetTextFromAction(); return new List<TextEditInfo> { new TextEditInfo(new Range(start, length), replaceWith) }; }
internal bool InContext(FormattingContext formattingContext) { foreach (Func<FormattingContext, bool> contextFilter in this.contextFilters) { if (!contextFilter(formattingContext)) { return false; } } return true; }
internal Rule Get(FormattingContext formattingContext) { foreach (Rule rule in this.rules) { if (rule.AppliesTo(formattingContext)) { return rule; } } return null; }
// formattingContext is a struct, and therefore not nullable. internal override IEnumerable<TextEditInfo> Apply(FormattingContext formattingContext) { List<TextEditInfo> edits = new List<TextEditInfo>(); TextEditInfo edit = this.GetLastSpaceTriviaInfo(formattingContext.NextToken.Token); if (edit != null) { edits.Add(edit); } return edits; }
internal Rule Get(FormattingContext formattingContext) { SyntaxKind typeLeft = formattingContext.CurrentToken.Token.Kind; SyntaxKind typeRight = formattingContext.NextToken.Token.Kind; RuleBucket ruleBucket; Dictionary<SyntaxKind, RuleBucket> leftTokenMap; if (this.Map.TryGetValue(typeLeft, out leftTokenMap)) { if (leftTokenMap.TryGetValue(typeRight, out ruleBucket)) { return ruleBucket.Get(formattingContext); } } return null; }
/// <summary> /// Performs the Phases 1 and 2 of the formatting process. /// </summary> /// <param name="raw">The raw WikiMarkup to format.</param> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="context">The formatting context.</param> /// <param name="current">The current Page, if any.</param> /// <param name="linkedPages">The Pages linked by the current Page.</param> /// <returns>The formatted content.</returns> public static string FormatWithPhase1And2(string raw, bool forIndexing, FormattingContext context, PageInfo current, out string[] linkedPages) { ContextInformation info = null; string username = SessionFacade.CurrentUsername; info = new ContextInformation(forIndexing, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current, username, SessionFacade.GetCurrentGroupNames()); IList<IFormatterProviderV30> providers = GetSortedFormatters(); // Phase 1 foreach(IFormatterProviderV30 provider in providers) { if(provider.PerformPhase1) { try { raw = provider.Format(raw, info, FormattingPhase.Phase1); } catch(Exception ex) { if(!(ex is ThreadAbortException)) { // Consider Response.End() Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase1 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername); } } } } raw = Formatter.Format(raw, forIndexing, context, current, out linkedPages); // Phase 2 foreach(IFormatterProviderV30 provider in providers) { if(provider.PerformPhase2) { try { raw = provider.Format(raw, info, FormattingPhase.Phase2); } catch(Exception ex) { if(!(ex is ThreadAbortException)) { // Consider Response.End() Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase2 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername); } } } } return raw; }
public async Task <InlineCompletionList?> Handle(InlineCompletionRequest request, CancellationToken cancellationToken) { if (request is null) { throw new ArgumentNullException(nameof(request)); } _logger.LogInformation($"Starting request for {request.TextDocument.Uri} at {request.Position}."); var document = await _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync(() => { _documentResolver.TryResolveDocument(request.TextDocument.Uri.GetAbsoluteOrUNCPath(), out var documentSnapshot); return(documentSnapshot); }, cancellationToken).ConfigureAwait(false); if (document is null) { return(null); } var codeDocument = await document.GetGeneratedOutputAsync(); if (codeDocument.IsUnsupported()) { return(null); } var sourceText = await document.GetTextAsync(); var linePosition = new LinePosition(request.Position.Line, request.Position.Character); var hostDocumentIndex = sourceText.Lines.GetPosition(linePosition); var languageKind = _documentMappingService.GetLanguageKind(codeDocument, hostDocumentIndex); // Map to the location in the C# document. if (languageKind != RazorLanguageKind.CSharp || !_documentMappingService.TryMapToProjectedDocumentPosition(codeDocument, hostDocumentIndex, out var projectedPosition, out _)) { _logger.LogInformation($"Unsupported location for {request.TextDocument.Uri}."); return(null); } var razorRequest = new RazorInlineCompletionRequest { TextDocument = request.TextDocument, Context = request.Context, Position = projectedPosition, Kind = languageKind, Options = request.Options, }; request.Position = projectedPosition; var response = await _languageServer.SendRequestAsync(LanguageServerConstants.RazorInlineCompletionEndpoint, razorRequest).ConfigureAwait(false); var list = await response.Returning <InlineCompletionList>(cancellationToken).ConfigureAwait(false); if (list == null || !list.Items.Any()) { _logger.LogInformation($"Did not get any inline completions from delegation."); return(null); } var items = new List <InlineCompletionItem>(); var csharpDocOptions = codeDocument.GetCSharpDocument(); foreach (var item in list.Items) { var containsSnippet = item.TextFormat == InsertTextFormat.Snippet; var range = item.Range ?? new Range { Start = projectedPosition, End = projectedPosition }; if (!_documentMappingService.TryMapFromProjectedDocumentRange(codeDocument, range, out var rangeInRazorDoc)) { _logger.LogWarning($"Could not remap projected range {range} to razor document"); continue; } using var formattingContext = FormattingContext.Create(request.TextDocument.Uri, document, codeDocument, request.Options, _adhocWorkspaceFactory); if (!TryGetSnippetWithAdjustedIndentation(formattingContext, item.Text, hostDocumentIndex, out var newSnippetText)) { continue; } var remappedItem = new InlineCompletionItem { Command = item.Command, Range = rangeInRazorDoc, Text = newSnippetText.ToString(), TextFormat = item.TextFormat, }; items.Add(remappedItem); } if (items.Count == 0) { _logger.LogInformation($"Could not format / map the items from delegation."); return(null); } _logger.LogInformation($"Returning {items.Count} items."); return(new InlineCompletionList { Items = items.ToArray() }); }
/// <summary> /// Performs the Phases 1 and 2 of the formatting process. /// </summary> /// <param name="raw">The raw WikiMarkup to format.</param> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="context">The formatting context.</param> /// <param name="current">The current Page, if any.</param> /// <returns>The formatted content.</returns> public static string FormatWithPhase1And2(string raw, bool forIndexing, FormattingContext context, PageInfo current) { string[] tempLinks; return FormatWithPhase1And2(raw, forIndexing, context, current, out tempLinks); }
public async Task <IFormattedValue> FormatValueAsync(IUshortsFormatter ushortsFormatter, ushort[] ushorts, FormattingContext formattingContext) { try { return(await TryFormatAsync(ushortsFormatter, ushorts, formattingContext)); } catch (Exception e) { var error = _typesContainer.Resolve <IErrorValue>(); error.ErrorMessage = e.Message; return(error); } }
internal static bool NoCommentsBetweenTokens(FormattingContext formattingContext) { return(!formattingContext.ContainsCommentsBetweenTokens()); }
internal static bool NoCommentsBetweenTokens(FormattingContext formattingContext) { return !formattingContext.ContainsCommentsBetweenTokens(); }
public static bool ShouldFormatMultiLine(FormattingContext context, bool firstTriviaInTree, TriviaList triviaList) { var analyzer = new CodeShapeAnalyzer(context, firstTriviaInTree, triviaList); return(analyzer.ShouldFormat()); }
internal abstract bool AppliesTo(FormattingContext formattingContext);
static FormattingCodeGenerator GetCodeGenerator(string name, FormattingContext context) { return(new DefaultCSharpCodeGenerator(context)); }
public void Format(object value, FormattedObjectGraph formattedGraph, FormattingContext context, FormatChild formatChild) { var errors = (IEnumerable <IError>)value; formattedGraph.AddFragment(string.Join("; ", errors.Select(error => error.Message))); }
/// <summary> /// Performs the Phase 3 of the formatting process. /// </summary> /// <param name="raw">The raw WikiMarkup to format.</param> /// <param name="context">The formatting context.</param> /// <param name="current">The current Page, if any.</param> /// <returns>The formatted content.</returns> public static string FormatWithPhase3(string raw, FormattingContext context, PageInfo current) { raw = Formatter.FormatPhase3(raw, context, current); ContextInformation info = null; string username = SessionFacade.CurrentUsername; info = new ContextInformation(false, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current, username, SessionFacade.GetCurrentGroupNames()); // Phase 3 foreach(IFormatterProviderV30 provider in GetSortedFormatters()) { if(provider.PerformPhase3) { try { raw = provider.Format(raw, info, FormattingPhase.Phase3); } catch(Exception ex) { if(!(ex is ThreadAbortException)) { // Consider Response.End() Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase3 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername); } } } } return raw; }
protected override TriviaDataWithList <SyntaxTrivia> Format( FormattingContext context, ChainedFormattingRules formattingRules, int lines, int spaces, CancellationToken cancellationToken) { return(new FormattedComplexTrivia(context, formattingRules, this.Token1, this.Token2, lines, spaces, this.OriginalString, cancellationToken)); }
public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { throw new NotImplementedException(); }
internal abstract IEnumerable<TextEditInfo> Apply(FormattingContext formattingContext);
public override TriviaData WithIndentation( int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { return(_original.WithIndentation(indentation, context, formattingRules, cancellationToken)); }
public abstract bool TryResolveInsertion(Position position, FormattingContext context, out TextEdit edit, out InsertTextFormat format);
internal override bool AppliesTo(FormattingContext formattingContext) { return this.RuleOperationContext.Context.InContext(formattingContext); }
public async Task <Result <ushort[]> > FormatBackAsync(IUshortsFormatter ushortsFormatter, IFormattedValue formattedValue, FormattingContext formattingContext) { try { return(Result <ushort[]> .Create(await ushortsFormatter.Accept(new FormatterFormatBackVisitor(formattedValue, formattingContext)), true)); } catch (Exception e) { var error = _typesContainer.Resolve <IErrorValue>(); error.ErrorMessage = e.Message; return(Result <ushort[]> .CreateWithException(e)); } }
private static ParsedToken GetTokenOn(Side side, FormattingContext formattingContext) { return((side == Side.Left) ? formattingContext.CurrentToken : formattingContext.NextToken); }
public string Format(object value, FormattingContext context, FormatChild formatChild) { var errors = (IEnumerable <Error>)value; return(string.Join("; ", errors.Select(error => error.Message))); }
private Task <IFormattedValue> TryFormatAsync(IUshortsFormatter ushortsFormatter, ushort[] ushorts, FormattingContext formattingContext) { if (ushortsFormatter == null) { return(null); } return(ushortsFormatter.Accept(new FormatterFormatVisitor(ushorts, _typesContainer, _iterationDefinitionsCache, formattingContext))); }
/// <summary> /// Prepares the title of an item for display. /// </summary> /// <param name="title">The input title.</param> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="context">The context information.</param> /// <param name="current">The current page, if any.</param> /// <returns>The prepared title, properly sanitized.</returns> public static string PrepareTitle(string title, bool forIndexing, FormattingContext context, PageInfo current) { string temp = title; ContextInformation info = new ContextInformation(forIndexing, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current, SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames()); foreach(IFormatterProviderV30 prov in GetSortedFormatters()) { temp = prov.PrepareTitle(temp, info); } return PrepareItemTitle(temp); }
internal override bool AppliesTo(FormattingContext formattingContext) { return(this.RuleOperationContext.Context.InContext(formattingContext)); }
public FormatterFormatBackVisitor(IFormattedValue formattedValue, FormattingContext formattingContext) { _formattedValue = formattedValue; _formattingContext = formattingContext; }
/// <inheritdoc /> public string Format(object value, FormattingContext context, FormatChild formatChild) { var personIdentifier = (PersonIdentifier)value; return($"{personIdentifier.Definition.SystemName}: {formatChild("Value", personIdentifier.Value.Value)}"); }
public void Format(object value, FormattedObjectGraph formattedGraph, FormattingContext context, FormatChild formatChild) { formattedGraph.AddFragment("<null>"); }
/// <summary> /// Performs the Phases 1 and 2 of the formatting process. /// </summary> /// <param name="raw">The raw WikiMarkup to format.</param> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="context">The formatting context.</param> /// <param name="current">The current Page, if any.</param> /// <returns>The formatted content.</returns> public static string FormatWithPhase1And2(string raw, bool forIndexing, FormattingContext context, PageInfo current) { string[] tempLinks; return(FormatWithPhase1And2(raw, forIndexing, context, current, out tempLinks)); }
/// <inheritdoc /> public string Format(object value, FormattingContext context, FormatChild formatChild) { return("<null>"); }
public async Task <OnAutoInsertResponse> Handle(OnAutoInsertParams request, CancellationToken cancellationToken) { var document = await _projectSnapshotManagerDispatcher.RunOnDispatcherThreadAsync(() => { _documentResolver.TryResolveDocument(request.TextDocument.Uri.GetAbsoluteOrUNCPath(), out var documentSnapshot); return(documentSnapshot); }, cancellationToken).ConfigureAwait(false); if (document is null || cancellationToken.IsCancellationRequested) { return(null); } var codeDocument = await document.GetGeneratedOutputAsync(); if (codeDocument.IsUnsupported()) { return(null); } cancellationToken.ThrowIfCancellationRequested(); var character = request.Character; var applicableProviders = new List <RazorOnAutoInsertProvider>(); for (var i = 0; i < _onAutoInsertProviders.Count; i++) { var formatOnTypeProvider = _onAutoInsertProviders[i]; if (formatOnTypeProvider.TriggerCharacter == character) { applicableProviders.Add(formatOnTypeProvider); } } if (applicableProviders.Count == 0) { // There's currently a bug in the LSP platform where other language clients OnAutoInsert trigger characters influence every language clients trigger characters. // To combat this we need to pre-emptively return so we don't try having our providers handle characters that they can't. return(null); } var uri = request.TextDocument.Uri; var position = request.Position; using (var formattingContext = FormattingContext.Create(uri, document, codeDocument, request.Options, _workspaceFactory)) { for (var i = 0; i < applicableProviders.Count; i++) { if (applicableProviders[i].TryResolveInsertion(position, formattingContext, out var textEdit, out var format)) { return(new OnAutoInsertResponse() { TextEdit = textEdit, TextEditFormat = format, }); } } } // No provider could handle the text edit. return(null); }
/// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <param name="value">The value for which to create a <see cref="System.String"/>.</param> /// <param name="useLineBreaks"> </param> /// <param name="processedObjects"> /// A collection of objects that /// </param> /// <param name="nestedPropertyLevel"> /// The level of nesting for the supplied value. This is used for indenting the format string for objects that have /// no <see cref="object.ToString()"/> override. /// </param> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public string Format(object value, FormattingContext context, FormatChild formatChild) { return("0x" + ((byte)value).ToString("X2")); }
public abstract bool TryResolveInsertion(Position position, FormattingContext context, [NotNullWhen(true)] out TextEdit?edit, out InsertTextFormat format);
// ----------------------------------------------------------------- // // Internal Methods // // ------------------------------------------------------------------ #region Internal Methods /// <summary> /// Create and format text line. /// </summary> /// <param name="ctx"> /// Line formatting context. /// </param> /// <param name="dcp"> /// Character position where the line starts. /// </param> /// <param name="width"> /// Requested width of the line. /// </param> /// <param name="trackWidth"> /// Requested width of track. /// </param> /// <param name="lineProps"> /// Line properties. /// </param> /// <param name="textLineBreak"> /// Line break object. /// </param> internal void Format(FormattingContext ctx, int dcp, int width, int trackWidth, TextParagraphProperties lineProps, TextLineBreak textLineBreak) { // Set formatting context _formattingContext = ctx; _dcp = dcp; _host.Context = this; _wrappingWidth = TextDpi.FromTextDpi(width); _trackWidth = TextDpi.FromTextDpi(trackWidth); _mirror = (lineProps.FlowDirection == FlowDirection.RightToLeft); _indent = lineProps.Indent; try { // Create line object if(ctx.LineFormatLengthTarget == -1) { _line = _host.TextFormatter.FormatLine(_host, dcp, _wrappingWidth, lineProps, textLineBreak, ctx.TextRunCache); } else { _line = _host.TextFormatter.RecreateLine(_host, dcp, ctx.LineFormatLengthTarget, _wrappingWidth, lineProps, textLineBreak, ctx.TextRunCache); } _runs = _line.GetTextRunSpans(); Invariant.Assert(_runs != null, "Cannot retrieve runs collection."); // Submit inline objects (only in measure mode) if (_formattingContext.MeasureMode) { List<InlineObject> inlineObjects = new List<InlineObject>(1); int dcpRun = _dcp; // Enumerate through all runs in the current line and retrieve // all inline objects. // If there are any figures / floaters, store this information for later use. foreach (TextSpan<TextRun> textSpan in _runs) { TextRun run = (TextRun)textSpan.Value; if (run is InlineObjectRun) { inlineObjects.Add(new InlineObject(dcpRun, ((InlineObjectRun)run).UIElementIsland, (TextParagraph)_paraClient.Paragraph)); } else if (run is FloatingRun) { if (((FloatingRun)run).Figure) { _hasFigures = true; } else { _hasFloaters = true; } } // Do not use TextRun.Length, because it gives total length of the run. // So, if the run is broken between lines, it gives incorrect value. // Use length of the TextSpan instead, which gives the correct length here. dcpRun += textSpan.Length; } // Submit inline objects to the paragraph cache if (inlineObjects.Count == 0) { inlineObjects = null; } TextParagraph.SubmitInlineObjects(dcp, dcp + ActualLength, inlineObjects); } } finally { // Clear formatting context _host.Context = null; } }
public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) { throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the <b>FormatContext</b> class. /// </summary> /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param> /// <param name="forWysiwyg">A value indicating whether the formatting is being done for display in the WYSIWYG editor.</param> /// <param name="context">The formatting context.</param> /// <param name="page">The Page Information, if any, <c>null</c> otherwise.</param> /// <param name="language">The current Thread's language (for example "en-US").</param> /// <param name="httpContext">The current HTTP Context object.</param> /// <param name="username">The current User's Username (or <c>null</c>).</param> /// <param name="groups">The groups the user is member of (or <c>null</c>).</param> public ContextInformation(bool forIndexing, bool forWysiwyg, FormattingContext context, PageInfo page, string language, HttpContext httpContext, string username, string[] groups) { this.forIndexing = forIndexing; this.forWysiwyg = forWysiwyg; this.context = context; this.page = page; this.language = language; this.httpContext = httpContext; this.username = username; this.groups = groups; }
public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action <int, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) { throw new NotImplementedException(); }
public FormatterFormatVisitor(ushort[] ushortsPayload, ITypesContainer typesContainer, ConcurrentDictionary <string, ConcurrentBag <IterationDefinition> > iterationDefinitionsCache, FormattingContext formattingContext) { _ushortsPayload = ushortsPayload; _typesContainer = typesContainer; _iterationDefinitionsCache = iterationDefinitionsCache; _formattingContext = formattingContext; }
public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) { return(_original.WithSpace(space, context, formattingRules)); }
internal abstract bool AppliesTo(FormattingContext formattingContext);
internal static bool TokensAreNotOnSameLine(FormattingContext formattingContext) { return !formattingContext.TokensOnSameLine(); }
internal abstract IEnumerable <TextEditInfo> Apply(FormattingContext formattingContext);
private static ParsedToken GetTokenOn(Side side, FormattingContext formattingContext) { return (side == Side.Left) ? formattingContext.CurrentToken : formattingContext.NextToken; }
internal static bool TokensAreNotOnSameLine(FormattingContext formattingContext) { return(!formattingContext.TokensOnSameLine()); }