Example #1
0
        public BraceSmartIndenter(
            JoinableTaskContext joinableTaskContext,
            VisualStudioDocumentTracker documentTracker,
            TextBufferCodeDocumentProvider codeDocumentProvider,
            IEditorOperationsFactoryService editorOperationsFactory)
        {
            if (joinableTaskContext is null)
            {
                throw new ArgumentNullException(nameof(joinableTaskContext));
            }

            if (documentTracker is null)
            {
                throw new ArgumentNullException(nameof(documentTracker));
            }

            if (codeDocumentProvider is null)
            {
                throw new ArgumentNullException(nameof(codeDocumentProvider));
            }

            if (editorOperationsFactory is null)
            {
                throw new ArgumentNullException(nameof(editorOperationsFactory));
            }

            _joinableTaskContext     = joinableTaskContext;
            _documentTracker         = documentTracker;
            _codeDocumentProvider    = codeDocumentProvider;
            _editorOperationsFactory = editorOperationsFactory;
            _textBuffer              = _documentTracker.TextBuffer;
            _textBuffer.Changed     += TextBuffer_OnChanged;
            _textBuffer.PostChanged += TextBuffer_OnPostChanged;
        }
Example #2
0
        public void RestoreCaretTo_PlacesCursorAtProvidedPosition()
        {
            // Arrange
            var initialSnapshot = new StringTextSnapshot("@{ \n\n}");
            var bufferPosition  = new VirtualSnapshotPoint(initialSnapshot, 4);
            var caret           = new Mock <ITextCaret>(MockBehavior.Strict);

            caret.Setup(c => c.MoveTo(It.IsAny <SnapshotPoint>()))
            .Callback <SnapshotPoint>(point =>
            {
                Assert.Equal(3, point.Position);
                Assert.Same(initialSnapshot, point.Snapshot);
            }).Returns(new CaretPosition(bufferPosition, new Mock <IMappingPoint>(MockBehavior.Strict).Object, PositionAffinity.Predecessor));
            ITextBuffer textBuffer      = null;
            var         textView        = CreateFocusedTextView(() => textBuffer, caret.Object);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, textView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            BraceSmartIndenter.RestoreCaretTo(3, textView);

            // Assert
            caret.VerifyAll();
        }
        // Internal for testing
        internal static void InsertIndent(int insertLocation, string indent, ITextBuffer textBuffer)
        {
            var edit = textBuffer.CreateEdit();

            edit.Insert(insertLocation, indent);
            edit.Apply();
        }
Example #4
0
        private void Close()
        {
            if (_parseData == null)
            {
                return;
            }
            ParseData parseData = _parseData;

            lock (parseData)
            {
                _fullPath = null;
                _htmlDocument.OnDocumentClosing  -= OnClose;
                _htmlDocument.MassiveChangeEnded -= OnMassiveChangeEnded;
                _htmlDocument = null;
                ServiceManager.RemoveService <RazorCodeGenerator>(_viewBuffer);
                ServiceManager.RemoveService <IRazorCodeGenerator>(_viewBuffer);
                ServiceManager.RemoveService <IContainedCodeGenerator>(_viewBuffer);
                _parseData = null;
                _runtimeError.Close();
                _viewBuffer.Changed     -= TextBuffer_OnChanged;
                _viewBuffer.PostChanged -= TextBuffer_OnPostChanged;
                SetProvisionallyAcceptedState(false);
                _viewBuffer = null;
                if (_razorEditorParser != null)
                {
                    _razorEditorParser.DocumentParseComplete -= DocumentParseComplete;
                    _razorEditorParser.Close();
                    _razorEditorParser = null;
                }
            }
        }
Example #5
0
        private string CalculateIndent(ITextBuffer buffer, int from)
        {
            // Get the line text of the block start
            var currentSnapshotPoint = new SnapshotPoint(buffer.CurrentSnapshot, from);
            var line     = buffer.CurrentSnapshot.GetLineFromPosition(currentSnapshotPoint);
            var lineText = line.GetText();

            // Gather up the indent from the start block
            _indentBuilder.Append(line.GetLineBreakText());
            foreach (var ch in lineText)
            {
                if (!char.IsWhiteSpace(ch))
                {
                    break;
                }

                _indentBuilder.Append(ch);
            }

            var indent = _indentBuilder.ToString();

            _indentBuilder.Clear();

            return(indent);
        }
Example #6
0
            private IContentType SniffContentType(ITextBuffer diskBuffer)
            {
                // try and sniff the content type from a double extension, and if we can't
                // do that then default to HTML.
                IContentType  contentType = null;
                ITextDocument textDocument;

                if (diskBuffer.Properties.TryGetProperty <ITextDocument>(typeof(ITextDocument), out textDocument))
                {
                    if (Path.GetExtension(textDocument.FilePath).Equals(PhpConstants.PhpFileExtension, StringComparison.OrdinalIgnoreCase) ||
                        Path.GetExtension(textDocument.FilePath).Equals(PhpConstants.Php5FileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        var path = Path.GetFileNameWithoutExtension(textDocument.FilePath);
                        if (path.IndexOf('.') != -1)
                        {
                            string subExt = Path.GetExtension(path).Substring(1);

                            var fileExtRegistry = _compModel.GetService <IFileExtensionRegistryService>();

                            contentType = fileExtRegistry.GetContentTypeForExtension(subExt);
                        }
                    }
                }
                return(contentType);
            }
        public BraceSmartIndenter(
            ForegroundDispatcher dispatcher,
            VisualStudioDocumentTracker documentTracker,
            TextBufferCodeDocumentProvider codeDocumentProvider,
            IEditorOperationsFactoryService editorOperationsFactory)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException(nameof(dispatcher));
            }

            if (documentTracker == null)
            {
                throw new ArgumentNullException(nameof(documentTracker));
            }

            if (codeDocumentProvider == null)
            {
                throw new ArgumentNullException(nameof(codeDocumentProvider));
            }

            if (editorOperationsFactory == null)
            {
                throw new ArgumentNullException(nameof(editorOperationsFactory));
            }

            _dispatcher              = dispatcher;
            _documentTracker         = documentTracker;
            _codeDocumentProvider    = codeDocumentProvider;
            _editorOperationsFactory = editorOperationsFactory;
            _textBuffer              = _documentTracker.TextBuffer;
            _textBuffer.Changed     += TextBuffer_OnChanged;
            _textBuffer.PostChanged += TextBuffer_OnPostChanged;
        }
 public void VsTextViewCreated(IVsTextView textViewAdapter)
 {
     try
     {
         if (!(AdaptersFactory.GetWpfTextView(textViewAdapter) is IWpfTextView view))
         {
             return;
         }
         view.Closed += OnViewClosed;
         Microsoft.VisualStudio.Text.ITextBuffer buffer = view.TextBuffer;
         if (buffer == null)
         {
             return;
         }
         string ffn = buffer.GetFFN();
         if (ffn == null)
         {
             return;
         }
         if (!(Path.GetExtension(ffn) == ".xaml" ||
               Path.GetExtension(ffn) == ".axaml"))
         {
             return;
         }
         System.Collections.Generic.List <IContentType> content_types = ContentTypeRegistryService.ContentTypes.ToList();
         IContentType new_content_type       = content_types.Find(ct => ct.TypeName == "axaml");
         Type         type_of_content_type   = new_content_type.GetType();
         System.Reflection.Assembly assembly = type_of_content_type.Assembly;
         buffer.ChangeContentType(new_content_type, null);
     }
     catch (Exception)
     {
     }
 }
Example #9
0
        public AlloyQuickInfoSource(ITextBuffer textBuffer, AlloyQuickInfoSourceProvider provider)
        {
            Contract.Requires <ArgumentNullException>(textBuffer != null, "textBuffer");
            Contract.Requires <ArgumentNullException>(provider != null, "provider");

            _textBuffer = textBuffer;
            _provider   = provider;
        }
Example #10
0
        public AlloyQuickInfoSource([NotNull] ITextBuffer textBuffer, [NotNull] AlloyQuickInfoSourceProvider provider)
        {
            Requires.NotNull(textBuffer, nameof(textBuffer));
            Requires.NotNull(provider, nameof(provider));

            _textBuffer = textBuffer;
            _provider   = provider;
        }
Example #11
0
        public JavaQuickInfoSource(ITextBuffer textBuffer, JavaQuickInfoSourceProvider provider)
        {
            Contract.Requires<ArgumentNullException>(textBuffer != null, "textBuffer");
            Contract.Requires<ArgumentNullException>(provider != null, "provider");

            _textBuffer = textBuffer;
            _provider = provider;
        }
        /// <summary>
        /// Called when the tagger for the specified <see cref="MVST.ITextBuffer"/> that has a matching content type should be created.
        /// </summary>
        /// <remarks>This function is called by the framework on Main Thread</remarks>
        /// <param name="text_view">The <see cref="MVSTE.ITextView"/> on which the tagger operates</param>
        /// <param name="text_buffer">The <see cref="MVST.ITextBuffer"/> on which the tagger operates</param>
        public MVSTT.ITagger <T> CreateTagger <T>(MVSTE.ITextView text_view, MVST.ITextBuffer text_buffer) where T : MVSTT.ITag
        {
            if (null == text_buffer)
            {
                return(null);
            }

            return(new EmbedFigureErrorTagger(text_view) as MVSTT.ITagger <T>);
        }
Example #13
0
 public void Dispose()
 {
     this.hostBuffer.NautilusBufferChanged -= new EventHandler <TextContentChangedEventArgs>(this.TextBuffer_Changed);
     this.hostBuffer        = (EditableTextBuffer)null;
     this.shouldTrackChange = (ShouldTrackChange)null;
     this.originalSnapshot  = (ITextSnapshot)null;
     this.textBuffer        = (Microsoft.VisualStudio.Text.ITextBuffer)null;
     this.changes           = (List <ITrackingSpan>)null;
 }
Example #14
0
 public TextChanges(EditableTextBuffer hostBuffer, Microsoft.VisualStudio.Text.ITextBuffer textBuffer, ShouldTrackChange shouldTrackChange)
 {
     this.hostBuffer = hostBuffer;
     this.hostBuffer.NautilusBufferChanged += new EventHandler <TextContentChangedEventArgs>(this.TextBuffer_Changed);
     this.textBuffer        = textBuffer;
     this.originalSnapshot  = this.textBuffer.CurrentSnapshot;
     this.changes           = new List <ITrackingSpan>();
     this.shouldTrackChange = shouldTrackChange;
 }
Example #15
0
        internal static IRazorCodeGenerator Create(Microsoft.VisualStudio.Text.ITextBuffer buffer, Version razorVersion, string physicalPath, string virtualPath)
        {
            RazorCodeGenerator razorCodeGenerator = ServiceManager.GetService <RazorCodeGenerator>(buffer);

            if (razorCodeGenerator == null)
            {
                razorCodeGenerator = new RazorCodeGenerator(buffer, razorVersion, physicalPath, virtualPath);
            }
            return(razorCodeGenerator);
        }
        private ProbeSignature CreateSignature(VsText.ITextBuffer textBuffer, FunctionSignature signature, VsText.ITrackingSpan span)
        {
            var sig = new ProbeSignature(textBuffer, signature, null);

            textBuffer.Changed += sig.SubjectBufferChanged;

            sig.Parameters = new ReadOnlyCollection <IParameter>((from a in signature.Arguments
                                                                  select new ProbeParameter(string.Empty, a.SignatureSpan.ToVsTextSpan(),
                                                                                            string.IsNullOrEmpty(a.Name) ? string.Empty : a.Name, sig)).Cast <IParameter>().ToArray());

            sig.ApplicableToSpan = span;
            sig.ComputeCurrentParameter(new VsText.SnapshotPoint(textBuffer.CurrentSnapshot, _triggerPos));
            return(sig);
        }
Example #17
0
        public void InsertIndent_InsertsProvidedIndentIntoBuffer()
        {
            // Arrange
            var         initialSnapshot      = new StringTextSnapshot("@{ \n}");
            var         expectedIndentResult = "@{ anything\n}";
            ITextBuffer textBuffer           = null;
            var         textView             = CreateFocusedTextView(() => textBuffer);
            var         documentTracker      = CreateDocumentTracker(() => textBuffer, textView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            BraceSmartIndenter.InsertIndent(3, "anything", textBuffer);

            // Assert
            Assert.Equal(expectedIndentResult, ((StringTextSnapshot)textBuffer.CurrentSnapshot).Content);
        }
Example #18
0
        public void TryCreateIndentationContext_ReturnsFalseIfNoFocusedTextView()
        {
            // Arrange
            var         snapshot        = new StringTextSnapshot(Environment.NewLine + "Hello World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(snapshot.Content));
            ITextBuffer textBuffer      = null;
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView: null);

            textBuffer = CreateTextBuffer(snapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(0, Environment.NewLine.Length, Environment.NewLine, syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Example #19
0
        public void TryCreateIndentationContext_ReturnsFalseIfNewLineIsNotFollowedByCloseBrace()
        {
            // Arrange
            var         initialSnapshot = new StringTextSnapshot("@{ " + Environment.NewLine + "World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(initialSnapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(3, Environment.NewLine.Length, Environment.NewLine, syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Example #20
0
        public void TryCreateIndentationContext_ReturnsFalseIfNewLineIsNotPrecededByOpenBrace_MidFile()
        {
            // Arrange
            var         initialSnapshot = new StringTextSnapshot("Hello\u0085World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(initialSnapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(5, 1, "\u0085", syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Example #21
0
        public void TryCreateIndentationContext_ReturnsFalseIfTextChangeIsNotNewline()
        {
            // Arrange
            var         snapshot        = new StringTextSnapshot("This Hello World");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(snapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(snapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(0, 5, "This ", syntaxTree, documentTracker, out var context);

            // Assert
            Assert.Null(context);
            Assert.False(result);
        }
Example #22
0
        internal CodeEditor CreateCodeEditor(Microsoft.VisualStudio.Text.ITextBuffer textBuffer)
        {
            EditingService.DefaultEnvironment defaultEnvironment = new EditingService.DefaultEnvironment();
            IWpfTextViewHost textViewHost = this.textEditorFactoryProvider.CreateTextViewHost(textBuffer, (IEnvironment)defaultEnvironment, false);

            defaultEnvironment.SetTextViewHost(textViewHost);
            IWpfTextView                textView              = textViewHost.TextView;
            IEditorOperations           editorOperations      = this.editorCommandsProvider.GetEditorOperations((ITextView)textView);
            ITextBufferUndoManager      bufferUndoManager     = this.undoManagerProvider.GetTextBufferUndoManager(textBuffer);
            IFindLogic                  service1              = this.loader.GetService <IFindLogic>();
            IClassificationTypeRegistry service2              = this.loader.GetService <IClassificationTypeRegistry>();
            IClassificationFormatMap    service3              = this.loader.GetService <IClassificationFormatMap>();
            ISquiggleProvider           squiggleProvider      = this.squiggleProviderFactory.GetSquiggleProvider((ITextView)textView);
            ICompletionBroker           brokerForTextView     = this.completionBrokerMap.GetBrokerForTextView((ITextView)textView);
            IMessageDisplayService      messageDisplayService = (IMessageDisplayService)this.serviceProvider.GetService(typeof(IMessageDisplayService));
            ICodeAidProvider            codeAidProvider       = this.GetCodeAidProvider();

            return(new CodeEditor(textView, textViewHost, editorOperations, bufferUndoManager, service1, service2, service3, squiggleProvider, brokerForTextView, this.codeOptionsModel, messageDisplayService, codeAidProvider, (IEnvironment)defaultEnvironment));
        }
Example #23
0
        public void TryCreateIndentationContext_ReturnsTrueIfNewLineIsSurroundedByBraces()
        {
            // Arrange
            var         initialSnapshot = new StringTextSnapshot("@{ \n}");
            var         syntaxTree      = RazorSyntaxTree.Parse(TestRazorSourceDocument.Create(initialSnapshot.Content));
            ITextBuffer textBuffer      = null;
            var         focusedTextView = CreateFocusedTextView(() => textBuffer);
            var         documentTracker = CreateDocumentTracker(() => textBuffer, focusedTextView);

            textBuffer = CreateTextBuffer(initialSnapshot, documentTracker);

            // Act
            var result = BraceSmartIndenter.TryCreateIndentationContext(3, 1, "\n", syntaxTree, documentTracker, out var context);

            // Assert
            Assert.NotNull(context);
            Assert.Same(focusedTextView, context.FocusedTextView);
            Assert.Equal(3, context.ChangePosition);
            Assert.True(result);
        }
Example #24
0
            public int OnLoadCompleted(int fReload)
            {
                _cp.Unadvise(_cookie);

                var         adapterService = _compModel.GetService <IVsEditorAdaptersFactoryService>();
                ITextBuffer diskBuffer     = adapterService.GetDocumentBuffer(_textLines);

                var factService = _compModel.GetService <IProjectionBufferFactoryService>();

                var contentRegistry = _compModel.GetService <IContentTypeRegistryService>();

                var bufferTagAggregatorFactory = _compModel.GetService <IBufferTagAggregatorFactoryService>();

                IContentType contentType = SniffContentType(diskBuffer) ??
                                           contentRegistry.GetContentType("HTML");

                var projBuffer = new PhpProjectionBuffer(contentRegistry, factService, bufferTagAggregatorFactory, diskBuffer, _compModel.GetService <IBufferGraphFactoryService>(), contentType);

                diskBuffer.Properties.AddProperty(typeof(PhpProjectionBuffer), projBuffer);

                Guid langSvcGuid = typeof(PhpLanguageInfo).GUID;

                _textLines.SetLanguageServiceID(ref langSvcGuid);

                adapterService.SetDataBuffer(_textLines, projBuffer.ProjectionBuffer);

                IVsTextView view;

                ErrorHandler.ThrowOnFailure(_window.GetPrimaryView(out view));

                if (contentType != null && contentType.IsOfType("HTML"))
                {
                    var editAdapter            = _compModel.GetService <IVsEditorAdaptersFactoryService>();
                    var newView                = editAdapter.GetWpfTextView(view);
                    var intellisenseController = HtmlIntellisenseControllerProvider.GetOrCreateController(_compModel, newView);
                    intellisenseController.AttachKeyboardFilter();
                }

                return(VSConstants.S_OK);
            }
        public VisualStudioRazorParser(ForegroundDispatcher dispatcher, ITextBuffer buffer, RazorTemplateEngine templateEngine, string filePath, ICompletionBroker completionBroker)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException(nameof(dispatcher));
            }

            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (templateEngine == null)
            {
                throw new ArgumentNullException(nameof(templateEngine));
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(filePath));
            }

            if (completionBroker == null)
            {
                throw new ArgumentNullException(nameof(completionBroker));
            }

            _dispatcher           = dispatcher;
            TemplateEngine        = templateEngine;
            FilePath              = filePath;
            _textBuffer           = buffer;
            _completionBroker     = completionBroker;
            _textBuffer.Changed  += TextBuffer_OnChanged;
            _parser               = new BackgroundParser(templateEngine, filePath);
            _idleTimer            = new Timer(IdleDelay);
            _idleTimer.Elapsed   += Onidle;
            _parser.ResultsReady += OnResultsReady;

            _parser.Start();
        }
Example #26
0
 private RazorCodeGenerator(Microsoft.VisualStudio.Text.ITextBuffer buffer, Version razorVersion, string physicalPath, string virtualPath)
 {
     WebEditor.CompositionService.SatisfyImportsOnce(this);
     _parseData                        = new ParseData();
     _viewBuffer                       = buffer;
     _viewBuffer.Changed              += TextBuffer_OnChanged;
     _viewBuffer.PostChanged          += TextBuffer_OnPostChanged;
     _htmlDocument                     = ServiceManager.GetService <HtmlEditorDocument>(_viewBuffer);
     _htmlDocument.OnDocumentClosing  += OnClose;
     _htmlDocument.MassiveChangeEnded += OnMassiveChangeEnded;
     _fullPath = ((!string.IsNullOrEmpty(physicalPath)) ? physicalPath : "Default.cshtml");
     if (virtualPath == null)
     {
         virtualPath = "Default.cshtml";
     }
     _runtimeError      = new RazorRuntimeError(_viewBuffer);
     _razorEditorParser = new ShimRazorEditorParserImpl(virtualPath, _fullPath);
     _razorEditorParser.DocumentParseComplete += DocumentParseComplete;
     ReparseFile();
     WebEditor.OnIdle += OnFirstIdle;
     ServiceManager.AddService(this, _viewBuffer);
     ServiceManager.AddService <IRazorCodeGenerator>(this, _viewBuffer);
     ServiceManager.AddService <IContainedCodeGenerator>(this, _viewBuffer);
 }
Example #27
0
        public static FileStore GetOrCreateForTextBuffer(VsText.ITextBuffer buf)
        {
            if (buf == null)
            {
                throw new ArgumentNullException("buf");
            }

            if (buf.ContentType.TypeName != Constants.DkContentType)
            {
                return(null);
            }

            FileStore cache;

            if (buf.Properties.TryGetProperty(typeof(FileStore), out cache))
            {
                return(cache);
            }

            cache = new FileStore();
            buf.Properties[typeof(FileStore)] = cache;

            return(cache);
        }
Example #28
0
 public void SetDataBuffer(IVsTextBuffer bufferAdapter, Microsoft.VisualStudio.Text.ITextBuffer dataBuffer)
 {
     throw new NotImplementedException();
 }
Example #29
0
 public IVsTextBuffer CreateVsTextBufferAdapterForSecondaryBuffer(Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider, Microsoft.VisualStudio.Text.ITextBuffer secondaryBuffer)
 {
     throw new NotImplementedException();
 }
Example #30
0
 public ITagger <T> CreateTagger <T>(Microsoft.VisualStudio.Text.ITextBuffer buffer) where T : ITag
 {
     return(buffer.Properties.GetOrCreateSingletonProperty <ITagger <T> >(() => new JavaOutline(this, buffer) as ITagger <T>));
 }
Example #31
0
 public TextBufferWriter(Microsoft.VisualStudio.Text.ITextBuffer textBuffer)
     : base((IFormatProvider)CultureInfo.CurrentUICulture)
 {
     this.textBuffer = textBuffer;
 }
            private IContentType SniffContentType(ITextBuffer diskBuffer)
            {
                // try and sniff the content type from a double extension, and if we can't
                // do that then default to HTML.
                IContentType contentType = null;
                ITextDocument textDocument;
                if (diskBuffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out textDocument))
                {
                    if (Path.GetExtension(textDocument.FilePath).Equals(PhpConstants.PhpFileExtension, StringComparison.OrdinalIgnoreCase)
                        || Path.GetExtension(textDocument.FilePath).Equals(PhpConstants.Php5FileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        var path = Path.GetFileNameWithoutExtension(textDocument.FilePath);
                        if (path.IndexOf('.') != -1)
                        {
                            string subExt = Path.GetExtension(path).Substring(1);

                            var fileExtRegistry = _compModel.GetService<IFileExtensionRegistryService>();

                            contentType = fileExtRegistry.GetContentTypeForExtension(subExt);
                        }
                    }
                }
                return contentType;
            }
		private void Close()
		{
			if (_parseData == null)
			{
				return;
			}
            ParseData parseData = _parseData;
			lock (parseData)
			{
				_fullPath = null;
				_htmlDocument.OnDocumentClosing -= OnClose;
				_htmlDocument.MassiveChangeEnded -= OnMassiveChangeEnded;
				_htmlDocument = null;
				ServiceManager.RemoveService<RazorCodeGenerator>(_viewBuffer);
				ServiceManager.RemoveService<IRazorCodeGenerator>(_viewBuffer);
				ServiceManager.RemoveService<IContainedCodeGenerator>(_viewBuffer);
				_parseData = null;
				_runtimeError.Close();
				_viewBuffer.Changed -= TextBuffer_OnChanged;
				_viewBuffer.PostChanged -= TextBuffer_OnPostChanged;
				SetProvisionallyAcceptedState(false);
				_viewBuffer = null;
				if (_razorEditorParser != null)
				{
					_razorEditorParser.DocumentParseComplete -= DocumentParseComplete;
					_razorEditorParser.Close();
					_razorEditorParser = null;
				}
			}
		}
		private RazorCodeGenerator(Microsoft.VisualStudio.Text.ITextBuffer buffer, Version razorVersion, string physicalPath, string virtualPath)
		{
			WebEditor.CompositionService.SatisfyImportsOnce(this);
			_parseData = new ParseData();
			_viewBuffer = buffer;
			_viewBuffer.Changed += TextBuffer_OnChanged;
			_viewBuffer.PostChanged += TextBuffer_OnPostChanged;
			_htmlDocument = ServiceManager.GetService<HtmlEditorDocument>(_viewBuffer);
			_htmlDocument.OnDocumentClosing += OnClose;
            _htmlDocument.MassiveChangeEnded += OnMassiveChangeEnded;
			_fullPath = ((!string.IsNullOrEmpty(physicalPath)) ? physicalPath : "Default.cshtml");
			if (virtualPath == null)
			{
				virtualPath = "Default.cshtml";
			}
			_runtimeError = new RazorRuntimeError(_viewBuffer);
			_razorEditorParser = new ShimRazorEditorParserImpl(virtualPath, _fullPath);
			_razorEditorParser.DocumentParseComplete += DocumentParseComplete;
			ReparseFile();
			WebEditor.OnIdle += OnFirstIdle;
			ServiceManager.AddService(this, _viewBuffer);
			ServiceManager.AddService<IRazorCodeGenerator>(this, _viewBuffer);
			ServiceManager.AddService<IContainedCodeGenerator>(this, _viewBuffer);
		}