ContainedDocument.cs 46.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
    /// <summary>
    /// An IVisualStudioDocument which represents the secondary buffer to the workspace API.
    /// </summary>
    internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument
    {
        private const string ReturnReplacementString = @"{|r|}";
        private const string NewLineReplacementString = @"{|n|}";

        private const string HTML = "HTML";
        private const string Razor = "Razor";

        private const char RazorExplicit = '@';

        private const string CSharpRazorBlock = "{";
        private const string VBRazorBlock = "code";

        private const string HelperRazor = "helper";
        private const string FunctionsRazor = "functions";

        private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions
        {
            DifferenceType = StringDifferenceTypes.Character,
            IgnoreTrimWhiteSpace = false
        });

        private readonly AbstractContainedLanguage _containedLanguage;
        private readonly SourceCodeKind _sourceCodeKind;
        private readonly IComponentModel _componentModel;
        private readonly Workspace _workspace;
        private readonly ITextDifferencingSelectorService _differenceSelectorService;
        private readonly IOptionService _optionService;
        private readonly HostType _hostType;
        private readonly ReiteratedVersionSnapshotTracker _snapshotTracker;
        private readonly IFormattingRule _vbHelperFormattingRule;
        private readonly string _itemMoniker;

        public AbstractProject Project { get { return _containedLanguage.Project; } }
        public DocumentId Id { get; private set; }
        public IReadOnlyList<string> Folders { get; private set; }
        public TextLoader Loader { get; private set; }
        public DocumentKey Key { get; private set; }
        public bool SupportsRename { get { return _hostType == HostType.Razor; } }

        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));
            var filePath = rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }

        private HostType GetHostType()
        {
            if (_containedLanguage.DataBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML)))
            {
                return HostType.HTML;
            }

            if (_containedLanguage.DataBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor)))
            {
                return HostType.Razor;
            }

            throw ExceptionUtilities.Unreachable;
        }

        public DocumentInfo GetInitialState()
        {
            return DocumentInfo.Create(
                this.Id,
                this.Name,
                folders: this.Folders,
                sourceCodeKind: _sourceCodeKind,
                loader: this.Loader,
                filePath: this.Key.Moniker);
        }

        public bool IsOpen
        {
            get
            {
                return true;
            }
        }

#pragma warning disable 67

        public event EventHandler UpdatedOnDisk;
        public event EventHandler<bool> Opened;
        public event EventHandler<bool> Closing;

#pragma warning restore 67

        IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } }

        public ITextBuffer GetOpenTextBuffer()
        {
            return _containedLanguage.SubjectBuffer;
        }

        public SourceTextContainer GetOpenTextContainer()
        {
            return this.GetOpenTextBuffer().AsTextContainer();
        }

        public IContentType ContentType
        {
            get
            {
                return _containedLanguage.SubjectBuffer.ContentType;
            }
        }

        public string Name
        {
            get
            {
                try
                {
                    return Path.GetFileName(this.FilePath);
                }
                catch (ArgumentException)
                {
                    return this.FilePath;
                }
            }
        }

        public SourceCodeKind SourceCodeKind
        {
            get
            {
                return _sourceCodeKind;
            }
        }

        public string FilePath
        {
            get
            {
                return Key.Moniker;
            }
        }

        public AbstractContainedLanguage ContainedLanguage
        {
            get
            {
                return _containedLanguage;
            }
        }

        public void Dispose()
        {
            _snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer);
            this.ContainedLanguage.Dispose();
        }

        public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint)
        {
            return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id;
        }

        public uint FindItemIdOfDocument(Document document)
        {
            return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId();
        }

        public void UpdateText(SourceText newText)
        {
            var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
            var originalSnapshot = subjectBuffer.CurrentSnapshot;
            var originalText = originalSnapshot.AsText();

            var changes = newText.GetTextChanges(originalText);

            IEnumerable<int> affectedVisibleSpanIndices = null;
            var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear();

            try
            {
                var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id);

                editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans());
                var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList();
                if (newChanges.Count == 0)
                {
                    // no change to apply
                    return;
                }

                ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices);
                AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices);
            }
            finally
            {
                SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices);
                SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal);
            }
        }

        private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes)
        {
            // no visible spans or changes
            if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0)
            {
                // return empty one
                yield break;
            }

            using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject())
            {
                var changeQueue = pooledObject.Object;
                changeQueue.AddRange(changes);

                var spanIndex = 0;
                var changeIndex = 0;
                for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++)
                {
                    var visibleSpan = editorVisibleSpansInOriginal[spanIndex];
                    var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true);

                    for (; changeIndex < changeQueue.Count; changeIndex++)
                    {
                        var change = changeQueue[changeIndex];

                        // easy case first
                        if (change.Span.End < visibleSpan.Start)
                        {
                            // move to next change
                            continue;
                        }

                        if (visibleSpan.End < change.Span.Start)
                        {
                            // move to next visible span
                            break;
                        }

                        // make sure we are not replacing whitespace around start and at the end of visible span
                        if (WhitespaceOnEdges(originalText, visibleTextSpan, change))
                        {
                            continue;
                        }

                        if (visibleSpan.Contains(change.Span))
                        {
                            yield return change;
                            continue;
                        }

                        // now it is complex case where things are intersecting each other
                        var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList();
                        if (subChanges.Count > 0)
                        {
                            if (subChanges.Count == 1 && subChanges[0] == change)
                            {
                                // we can't break it. not much we can do here. just don't touch and ignore this change
                                continue;
                            }

                            changeQueue.InsertRange(changeIndex + 1, subChanges);
                            continue;
                        }
                    }
                }
            }
        }

        private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change)
        {
            if (!string.IsNullOrWhiteSpace(change.NewText))
            {
                return false;
            }

            if (change.Span.End <= visibleTextSpan.Start)
            {
                return true;
            }

            if (visibleTextSpan.End <= change.Span.Start)
            {
                return true;
            }

            return false;
        }

        private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText)
        {
            using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject())
            {
                var leftText = originalText.ToString(changeInOriginalText.Span);
                var rightText = changeInOriginalText.NewText;
                var offsetInOriginalText = changeInOriginalText.Span.Start;

                if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object))
                {
                    return changes.Object.ToList();
                }

                return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText);
            }
        }

        private bool TryGetSubTextChanges(
            SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes)
        {
            // these are expensive. but hopely, we don't hit this as much except the boundary cases.
            using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
            using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
            {
                var spansInLeftText = leftPool.Object;
                var spansInRightText = rightPool.Object;

                if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText))
                {
                    for (var i = 0; i < spansInLeftText.Count; i++)
                    {
                        var spanInLeftText = spansInLeftText[i];
                        var spanInRightText = spansInRightText[i];
                        if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty)
                        {
                            continue;
                        }

                        var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);

                        TextChange textChange;
                        if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange))
                        {
                            changes.Add(textChange);
                        }
                    }

                    return true;
                }

                return false;
            }
        }

        private IEnumerable<TextChange> GetSubTextChanges(
            SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText)
        {
            // these are expensive. but hopely, we don't hit this as much except the boundary cases.
            using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
            using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject())
            {
                var leftReplacementMap = leftPool.Object;
                var rightReplacementMap = rightPool.Object;

                string leftTextWithReplacement, rightTextWithReplacement;
                GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement);

                var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement);

                foreach (var difference in diffResult)
                {
                    var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap);
                    var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap);

                    var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length);

                    TextChange textChange;
                    if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange))
                    {
                        yield return textChange;
                    }
                }
            }
        }

        private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText)
        {
            return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count;
        }

        private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups)
        {
            if (text.Length == 0)
            {
                groups.Add(new TextSpan(0, 0));
                return true;
            }

            var start = 0;
            for (var i = 0; i < text.Length; i++)
            {
                var ch = text[i];
                switch (ch)
                {
                    case ' ':
                        if (!TextAt(text, i - 1, ' '))
                        {
                            start = i;
                        }

                        break;

                    case '\r':
                    case '\n':
                        if (i == 0)
                        {
                            groups.Add(TextSpan.FromBounds(0, 0));
                        }
                        else if (TextAt(text, i - 1, ' '))
                        {
                            groups.Add(TextSpan.FromBounds(start, i));
                        }
                        else if (TextAt(text, i - 1, '\n'))
                        {
                            groups.Add(TextSpan.FromBounds(start, i));
                        }

                        start = i + 1;
                        break;

                    default:
                        return false;
                }
            }

            if (start <= text.Length)
            {
                groups.Add(TextSpan.FromBounds(start, text.Length));
            }

            return true;
        }

        private bool TextAt(string text, int index, char ch)
        {
            if (index < 0 || text.Length <= index)
            {
                return false;
            }

            return text[index] == ch;
        }

        private bool TryGetSubTextChange(
            SourceText originalText, TextSpan visibleSpanInOriginalText,
            string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange)
        {
            textChange = default(TextChange);

            var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start);
            var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End);

            // skip easy case
            // 1. things are out of visible span
            if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText))
            {
                return false;
            }

            // 2. there are no intersects
            var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length);
            if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End)
            {
                textChange = new TextChange(spanInOriginalText, snippetInRightText);
                return true;
            }

            // okay, more complex case. things are intersecting boundaries.
            var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText();
            var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText();

            // there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heristic is heavily based on
            // text differ's behavior.

            // 1. it is a single line
            if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber)
            {
                // don't do anything
                return false;
            }

            // 2. replacement contains visible spans
            if (spanInOriginalText.Contains(visibleSpanInOriginalText))
            {
                // header
                // don't do anything

                // body
                textChange = new TextChange(
                    TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start),
                    snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length));

                // footer
                // don't do anything

                return true;
            }

            // 3. replacement intersects with start
            if (spanInOriginalText.Start < visibleSpanInOriginalText.Start &&
                visibleSpanInOriginalText.Start <= spanInOriginalText.End &&
                spanInOriginalText.End < visibleSpanInOriginalText.End)
            {
                // header
                // don't do anything

                // body
                if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End)
                {
                    textChange = new TextChange(
                        TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End),
                        snippetInRightText.Substring(firstLineOfRightTextSnippet.Length));
                    return true;
                }

                return false;
            }

            // 4. replacement intersects with end
            if (visibleSpanInOriginalText.Start < spanInOriginalText.Start &&
                spanInOriginalText.Start <= visibleSpanInOriginalText.End &&
                visibleSpanInOriginalText.End <= spanInOriginalText.End)
            {
                // body
                if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start)
                {
                    textChange = new TextChange(
                        TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start),
                        snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length));
                    return true;
                }

                // footer
                // don't do anything

                return false;
            }

            // if it got hit, then it means there is a missing case
            throw ExceptionUtilities.Unreachable;
        }

        private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement)
        {
            var diffService = _differenceSelectorService.GetTextDifferencingService(
                _workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType());

            diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService;
            return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions);
        }

        private void GetTextWithReplacements(
            string leftText, string rightText,
            List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap,
            out string leftTextWithReplacement, out string rightTextWithReplacement)
        {
            // to make diff works better, we choose replacement strings that don't appear in both texts.
            var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString);
            var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString);

            leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap);
            rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap);
        }

        private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement)
        {
632
            if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0)
633 634 635 636 637
            {
                return initialReplacement;
            }

            // okay, there is already one in the given text.
638
            const string format = "{{|{0}|{1}|{0}|}}";
639 640 641
            for (var i = 0; true; i++)
            {
                var replacement = string.Format(format, i.ToString(), initialReplacement);
642
                if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0)
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
                {
                    return replacement;
                }
            }
        }

        private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap)
        {
            var delta = 0;
            var returnLength = returnReplacement.Length;
            var newLineLength = newLineReplacement.Length;

            var sb = StringBuilderPool.Allocate();
            for (var i = 0; i < text.Length; i++)
            {
                var ch = text[i];
                if (ch == '\r')
                {
                    sb.Append(returnReplacement);
                    delta += returnLength - 1;
                    replacementMap.Add(ValueTuple.Create(i + delta, delta));
                    continue;
                }
                else if (ch == '\n')
                {
                    sb.Append(newLineReplacement);
                    delta += newLineLength - 1;
                    replacementMap.Add(ValueTuple.Create(i + delta, delta));
                    continue;
                }

                sb.Append(ch);
            }

            return StringBuilderPool.ReturnAndFree(sb);
        }

        private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap)
        {
            var start = span.Start;
            var end = span.End;

            for (var i = 0; i < replacementMap.Count; i++)
            {
                var positionAndDelta = replacementMap[i];
                if (positionAndDelta.Item1 <= span.Start)
                {
                    start = span.Start - positionAndDelta.Item2;
                }

                if (positionAndDelta.Item1 <= span.End)
                {
                    end = span.End - positionAndDelta.Item2;
                }

                if (positionAndDelta.Item1 > span.End)
                {
                    break;
                }
            }

            return Span.FromBounds(start, end);
        }

        public IEnumerable<TextSpan> GetEditorVisibleSpans()
        {
            var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
            return _containedLanguage.DataBuffer.CurrentSnapshot
                       .GetSourceSpans()
                       .Where(ss => ss.Snapshot.TextBuffer == subjectBuffer)
                       .Select(s => s.Span.ToTextSpan())
                       .OrderBy(s => s.Start);
        }

        private static void ApplyChanges(
            IProjectionBuffer subjectBuffer,
            IEnumerable<TextChange> changes,
            IList<TextSpan> visibleSpansInOriginal,
            out IEnumerable<int> affectedVisibleSpansInNew)
        {
            using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
            {
                var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear();
                affectedVisibleSpansInNew = affectedSpans;

                var currentVisibleSpanIndex = 0;
                foreach (var change in changes)
                {
                    // Find the next visible span that either overlaps or intersects with 
                    while (currentVisibleSpanIndex < visibleSpansInOriginal.Count &&
                           visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start)
                    {
                        currentVisibleSpanIndex++;
                    }

                    // no more place to apply text changes
                    if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count)
                    {
                        break;
                    }

                    var newText = change.NewText;
                    var span = change.Span.ToSpan();

                    edit.Replace(span, newText);

                    affectedSpans.Add(currentVisibleSpanIndex);
                }

                edit.Apply();
            }
        }

        private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex)
        {
            if (!visibleSpanIndex.Any())
            {
                return;
            }

            var snapshot = subjectBuffer.CurrentSnapshot;
            var document = _workspace.CurrentSolution.GetDocument(this.Id);
            var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
            Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText()));

            var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>();
            var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer);
            var options = _workspace.Options
                                        .WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled())
                                        .WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize())
                                        .WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize());

            using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject())
            {
                var spans = pooledObject.Object;

                spans.AddRange(this.GetEditorVisibleSpans());
                using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null))
                {
                    foreach (var spanIndex in visibleSpanIndex)
                    {
                        var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex);

                        var visibleSpan = spans[spanIndex];
                        AdjustIndentationForSpan(document, edit, visibleSpan, rule, options);
                    }

                    edit.Apply();
                }
            }
        }

        private void AdjustIndentationForSpan(
            Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options)
        {
            var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject())
            using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
            {
                var venusFormattingRules = rulePool.Object;
                var visibleSpans = spanPool.Object;

                venusFormattingRules.Add(baseIndentationRule);
                venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);

                var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));

                var workspace = document.Project.Solution.Workspace;
                var changes = Formatter.GetFormattedTextChanges(
                    root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
                    workspace, options, formattingRules, CancellationToken.None);

                visibleSpans.Add(visibleSpan);
                var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));

                foreach (var change in newChanges)
                {
                    edit.Replace(change.Span.ToSpan(), change.NewText);
                }
            }
        }

        public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex)
        {
            if (_hostType == HostType.Razor)
            {
                var currentSpanIndex = spanIndex;

                TextSpan visibleSpan;
                TextSpan visibleTextSpan;
                GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan);

                var end = visibleSpan.End;
                var current = root.FindToken(visibleTextSpan.Start).Parent;
                while (current != null)
                {
                    if (current.Span.Start == visibleTextSpan.Start)
                    {
                        var blockType = GetRazorCodeBlockType(visibleSpan.Start);
                        if (blockType == RazorCodeBlockType.Explicit)
                        {
                            var baseIndentation = GetBaseIndentation(root, text, visibleSpan);
                            return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule);
                        }
                    }

                    if (current.Span.Start < visibleSpan.Start)
                    {
                        var blockType = GetRazorCodeBlockType(visibleSpan.Start);
                        if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper)
                        {
                            var baseIndentation = GetBaseIndentation(root, text, visibleSpan);
                            return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule);
                        }

                        if (currentSpanIndex == 0)
                        {
                            break;
                        }

                        GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan);
                        continue;
                    }

                    current = current.Parent;
                }
            }

            var span = spans[spanIndex];
            var indentation = GetBaseIndentation(root, text, span);
            return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule);
        }

        private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan)
        {
            visibleSpan = spans[spanIndex];

            visibleTextSpan = GetVisibleTextSpan(text, visibleSpan);
            if (visibleTextSpan.IsEmpty)
            {
                // span has no text in them
                visibleTextSpan = visibleSpan;
            }
        }

        private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span)
        {
            // Is this right?  We should probably get this from the IVsContainedLanguageHost instead.
            var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>();
            var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer);

            var additionalIndentation = GetAdditionalIndentation(root, text, span);

            string baseIndentationString;
            int parent, indentSize, useTabs = 0, tabSize = 0;

            // Skip over the first line, since it's in "Venus space" anyway.
            var startingLine = text.Lines.GetLineFromPosition(span.Start);
            for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1])
            {
                Marshal.ThrowExceptionForHR(
                    this.ContainedLanguage.ContainedLanguageHost.GetLineIndent(
                        line.LineNumber,
                        out baseIndentationString,
                        out parent,
                        out indentSize,
                        out useTabs,
                        out tabSize));
                if (!string.IsNullOrEmpty(baseIndentationString))
                {
                    return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation;
                }
            }

            return additionalIndentation;
        }

        private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false)
        {
            var start = visibleSpan.Start;
            for (; start < visibleSpan.End; start++)
            {
                if (!char.IsWhiteSpace(text[start]))
                {
                    break;
                }
            }

            var end = visibleSpan.End - 1;
            if (start <= end)
            {
                for (; start <= end; end--)
                {
                    if (!char.IsWhiteSpace(text[end]))
                    {
                        break;
                    }
                }
            }

            if (uptoFirstAndLastLine)
            {
                var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start);
                var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End);

                if (firstLine.LineNumber < lastLine.LineNumber)
                {
                    start = (start < firstLine.End) ? start : firstLine.End;
                    end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1;
                }
            }

            return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan);
        }

        private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span)
        {
            if (_hostType == HostType.HTML)
            {
                return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language);
            }

            if (_hostType == HostType.Razor)
            {
                var type = GetRazorCodeBlockType(span.Start);

                // razor block
                if (type == RazorCodeBlockType.Block)
                {
                    // more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist
                    // in both subject and surface buffer and there is no easy way to figure out who owns } just typed.
                    // in this case, we let razor owns it. later razor will remove } from subject buffer if it is something
                    // razor owns.
                    if (this.Project.Language == LanguageNames.CSharp)
                    {
                        var textSpan = GetVisibleTextSpan(text, span);
                        var end = textSpan.End - 1;
                        if (end >= 0 && text[end] == '}')
                        {
                            var token = root.FindToken(end);
                            var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>();
                            if (token.Span.Start == end && syntaxFact != null)
                            {
                                SyntaxToken openBrace;
                                if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span))
                                {
                                    return 0;
                                }
                            }
                        }
                    }

                    // same as C#, but different text is in the buffer
                    if (this.Project.Language == LanguageNames.VisualBasic)
                    {
                        var textSpan = GetVisibleTextSpan(text, span);
                        var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot;
                        var end = textSpan.End - 1;
                        if (end >= 0)
                        {
                            var ch = subjectSnapshot[end];
                            if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) ||
                                CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false))
                            {
                                var token = root.FindToken(end, findInsideTrivia: true);
                                var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>();
                                if (token.Span.End == textSpan.End && syntaxFact != null)
                                {
                                    if (syntaxFact.IsSkippedTokensTrivia(token.Parent))
                                    {
                                        return 0;
                                    }
                                }
                            }
                        }
                    }

                    return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language);
                }
            }

            return 0;
        }

        private RazorCodeBlockType GetRazorCodeBlockType(int position)
        {
            var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer();
            var subjectSnapshot = subjectBuffer.CurrentSnapshot;
            var surfaceSnapshot = _containedLanguage.DataBuffer.CurrentSnapshot;

            var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor);
            if (!surfacePoint.HasValue)
            {
                // how this can happen?
                return RazorCodeBlockType.Implicit;
            }

            var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]);

            // razor block
            if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch))
            {
                return RazorCodeBlockType.Block;
            }

            if (ch == RazorExplicit)
            {
                return RazorCodeBlockType.Explicit;
            }

            if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor))
            {
                return RazorCodeBlockType.Helper;
            }

            return RazorCodeBlockType.Implicit;
        }

        private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch)
        {
            if (this.Project.Language == LanguageNames.CSharp)
            {
                return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) ||
                       CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock);
            }

            if (this.Project.Language == LanguageNames.VisualBasic)
            {
                return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) ||
                       CheckCode(surfaceSnapshot, position, ch, FunctionsRazor);
            }

            return false;
        }

        private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true)
        {
            if (ch != tag[tag.Length - 1] || position < tag.Length)
            {
                return false;
            }

            var start = position - tag.Length;
            var razorTag = snapshot.GetText(start, tag.Length);
            return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit);
        }

        private bool CheckCode(ITextSnapshot snapshot, int position, string tag)
        {
            int i = position - 1;
            if (i < 0)
            {
                return false;
            }

            for (; i >= 0; i--)
            {
                if (!char.IsWhiteSpace(snapshot[i]))
                {
                    break;
                }
            }

            var ch = snapshot[i];
            position = i + 1;

            return CheckCode(snapshot, position, ch, tag);
        }

        private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2)
        {
            if (!CheckCode(snapshot, position, ch, tag2, checkAt: false))
            {
                return false;
            }

            return CheckCode(snapshot, position - tag2.Length, tag1);
        }

        public ITextUndoHistory GetTextUndoHistory()
        {
            // In Venus scenarios, the undo history is associated with the data buffer
            return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer);
        }

        public uint GetItemId()
        {
            AssertIsForeground();

            if (_itemMoniker == null)
            {
                return (uint)VSConstants.VSITEMID.Nil;
            }

            uint itemId;
            Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId);
            return itemId;
        }

        private enum RazorCodeBlockType
        {
            Block,
            Explicit,
            Implicit,
            Helper
        }

        private enum HostType
        {
            HTML,
            Razor
        }
    }
}