Beispiel #1
0
 private void Create(ITextView textView, IEditorOptions editorOptions = null)
 {
     _textView = textView;
     _textBuffer = textView.TextBuffer;
     _snapshot = _textBuffer.CurrentSnapshot;
     _textBuffer.Changed += delegate { _snapshot = _textBuffer.CurrentSnapshot; };
     _globalSettings = new Vim.GlobalSettings();
     _localSettings = new LocalSettings(_globalSettings, FSharpOption.CreateForReference(editorOptions), FSharpOption.CreateForReference(textView));
     _markMap = new MarkMap(new TrackingLineColumnService());
     _vimData = new VimData();
     _search = VimUtil.CreateSearchService(_globalSettings);
     _jumpList = VimUtil.CreateJumpList();
     _statusUtil = new Mock<IStatusUtil>(MockBehavior.Strict);
     _navigator = VimUtil.CreateTextStructureNavigator(_textView, WordKind.NormalWord);
     _motionUtil = new MotionUtil(
         _textView,
         _markMap,
         _localSettings,
         _search,
         _navigator,
         _jumpList,
         _statusUtil.Object,
         VimUtil.GetWordUtil(textView),
         _vimData);
 }
        /// <summary>
        /// Writes a set of images based on the settings specified in a ImagePropertiesInfo object.
        /// </summary>
        /// <param name="imageInfo">the image properties</param>
        /// <param name="allowEnlargement">if true, generated images will be scaled larger than the source image (if the imageInfo sizes are larger) </param>
        public void WriteImages(ImagePropertiesInfo imageInfo, bool allowEnlargement, ImageDecoratorInvocationSource invocationSource, CreateFileCallback inlineFileCreator, CreateFileCallback linkedFileCreator, IEditorOptions clientOptions)
        {
            string inlinePrefix = imageInfo.LinkTarget == LinkTargetType.IMAGE ? "_thumb" : "";

            ImageFilter inlineFilter = ImageFilterDecoratorAdapter.CreateImageDecoratorsFilter(imageInfo, ImageEmbedType.Embedded, invocationSource, clientOptions);
            ImageFilter targetFilter = ImageFilterDecoratorAdapter.CreateImageDecoratorsFilter(imageInfo, ImageEmbedType.Linked, invocationSource, clientOptions);

            using (Bitmap inlineBitmap = new Bitmap(imageInfo.ImageSourceUri.LocalPath))
            {
                string imgPath = writeImage(inlineBitmap, imageInfo.ImageSourceUri.LocalPath, inlinePrefix, inlineFilter, inlineFileCreator);
                string inlineImgPath = new Uri(UrlHelper.CreateUrlFromPath(imgPath)).ToString();
                imageInfo.InlineImageUrl = inlineImgPath;
            }

            //Generate the link image
            //Warning! this imageInfo.LinkTarget check must be done after the inline image because the resize
            //         decorator will set the default link target for the image the first time it
            //         is applied.
            //imageInfo.LinkTarget = origLinkTarget;
            if (imageInfo.LinkTarget == LinkTargetType.IMAGE && !ImageDecoratorDirective.ShouldSuppressLinked)
            {
                using (Bitmap targetBitmap = new Bitmap(imageInfo.ImageSourceUri.LocalPath))
                {
                    string anchorPath = writeImage(targetBitmap, imageInfo.ImageSourceUri.LocalPath, "", targetFilter, linkedFileCreator);
                    string targetUrl = new Uri(UrlHelper.CreateUrlFromPath(anchorPath)).ToString();
                    imageInfo.LinkTargetUrl = targetUrl;
                }
            }
        }
Beispiel #3
0
		//private GLControl glControl;

		#region Constructors and Destructors

		public Base3DEditor(
			IComponentContext context, IEditorOptions<Base3DEditorOptions> options, Base3DEditorContent content)
		{
			this.options = options;
			this.content = content;
			this.graphicsContext = context.Resolve<ToeGraphicsContext>();
			this.camera = new EditorCamera(context.Resolve<IEditorOptions<EditorCameraOptions>>());
			this.camera.PropertyChanged += this.OnCameraPropertyChanged;
			this.InitializeComponent();
			this.Dock = DockStyle.Fill;
			//this.glControl = new GLControl(GraphicsMode.Default, 1, 0, GraphicsContextFlags.Default);
			//this.glControl.Dock = DockStyle.Fill;
			this.glControl.Load += this.GLControlLoad;
			this.glControl.Paint += this.GLControlPaint;
			this.glControl.Resize += this.GLControlResize;
			this.Controls.Add(this.glControl);
			this.glControl.MouseMove += this.OnSceneMouseMove;
			this.glControl.MouseEnter += this.OnSceneMouseEnter;
			this.glControl.MouseLeave += this.OnSceneMouseLeave;
			this.glControl.MouseWheel += this.OnSceneMouseWheel;
			this.glControl.KeyDown += this.OnControlKeyDown;
			this.glControl.KeyUp += this.OnControlKeyUp;
			this.glControl.GotFocus += this.OnSceneGotFocus;
			this.glControl.LostFocus += this.OnSceneLostFocus;
			this.Camera.LookAt(new Vector3(512, 64, 1024), new Vector3(0, 0, 0));
			this.CameraController = new TargetCameraController { Camera = this.Camera };
			this.yUpToolStripMenuItem.Click += this.SelectYUp;
			this.zUpToolStripMenuItem.Click += this.SelectZUp;
			this.UpdateCoordinateSystemIcon();
			this.UpdateLighingIcon();
			this.UpdateWireframeIcon();
			this.UpdateNormalIcon();
		}
 /// <summary>Returns the span for the selected line. Extends it if it is a part of a multi line statement or declaration.</summary>
 private Task<IEnumerable<SnapshotSpan>> GetExpandedLineAsync(IEditorOptions editorOptions, CommandArgs args, CancellationToken cancellationToken)
 {
     IEnumerable<SnapshotSpan> selectedSpans = GetSelectedLine(args.TextView);
     var candidateSubmission = GetSubmissionFromSelectedSpans(editorOptions, selectedSpans);
     return CanParseSubmission(candidateSubmission)
         ? Task.FromResult(selectedSpans)
         : ExpandSelectionAsync(selectedSpans, args, cancellationToken);
 }
 private ImageFilterDecoratorAdapter(ImagePropertiesInfo imageInfo, ImageEmbedType embedType, ImageDecoratorInvocationSource invocationSource, IEditorOptions editorOptions)
 {
     _decoratorsList = imageInfo.ImageDecorators;
     _imageInfo = imageInfo;
     _embedType = embedType;
     _invocationSource = invocationSource;
     _editorOptions = editorOptions;
 }
 public bool LoadOption(IEditorOptions options, string optionName)
 {
     if (_settingsStore != null)
     {
         return _settingsStore.LoadOption(options, optionName);
     }
     return false;
 }
        string ISendToInteractiveSubmissionProvider.GetSelectedText(IEditorOptions editorOptions, CommandArgs args, CancellationToken cancellationToken)
        {
            IEnumerable<SnapshotSpan> selectedSpans = args.TextView.Selection.IsEmpty
                ? GetExpandedLineAsync(editorOptions, args, cancellationToken).WaitAndGetResult(cancellationToken)
                : args.TextView.Selection.GetSnapshotSpansOnBuffer(args.SubjectBuffer).Where(ss => ss.Length > 0);

            return GetSubmissionFromSelectedSpans(editorOptions, selectedSpans);
        }
 public void Setup()
 {
     _synchronizer = new EditorToSettingSynchronizer(EditorUtil.FactoryService.Vim);
     _buffer = EditorUtil.FactoryService.Vim.CreateBuffer(EditorUtil.CreateTextView(""));
     _localSettings = _buffer.LocalSettings;
     _globalSettings = _localSettings.GlobalSettings;
     _editorOptions = _localSettings.EditorOptions.Value;
 }
        public TemplateTypingCommandHandler(
            ITextView textView,
            ITextBuffer textBuffer,
            IEditorOptions editorOptions,
            IEditorOperations editorOperations)
#if DEV14_OR_LATER
            : base(textView, _ => textBuffer)
#else
            : base(textView, textBuffer)
 public static IElisionBuffer CreateElisionBufferWithoutIndentation(
     this IProjectionBufferFactoryService factoryService,
     IEditorOptions editorOptions,
     params SnapshotSpan[] exposedSpans)
 {
     return factoryService.CreateElisionBufferWithoutIndentation(
         editorOptions,
         (IEnumerable<SnapshotSpan>)exposedSpans);
 }
Beispiel #11
0
        public void Create(params string[] lines)
        {
            _textView = EditorUtil.CreateTextView(lines);
            _vimData = new VimData();
            _editorOptions = EditorUtil.FactoryService.EditorOptionsFactory.GetOptions(_textView);
            _textView.Caret.MoveTo(new SnapshotPoint(_textView.TextSnapshot, 0));
            _textBuffer = _textView.TextBuffer;
            _factory = new MockRepository(MockBehavior.Strict);
            _registerMap = VimUtil.CreateRegisterMap(MockObjectFactory.CreateClipboardDevice(_factory).Object);
            _host = _factory.Create<IVimHost>();
            _jumpList = _factory.Create<IJumpList>();
            _editorOperations = _factory.Create<IEditorOperations>();
            _editorOperations.Setup(x => x.AddAfterTextBufferChangePrimitive());
            _editorOperations.Setup(x => x.AddBeforeTextBufferChangePrimitive());
            _globalSettings = _factory.Create<IVimGlobalSettings>();
            _globalSettings.SetupGet(x => x.Magic).Returns(true);
            _globalSettings.SetupGet(x => x.SmartCase).Returns(false);
            _globalSettings.SetupGet(x => x.IgnoreCase).Returns(true);
            _globalSettings.SetupGet(x => x.IsVirtualEditOneMore).Returns(false);
            _globalSettings.SetupGet(x => x.UseEditorIndent).Returns(false);
            _globalSettings.SetupGet(x => x.UseEditorSettings).Returns(false);
            _globalSettings.SetupGet(x => x.VirtualEdit).Returns(String.Empty);
            _globalSettings.SetupGet(x => x.WrapScan).Returns(true);
            _settings = MockObjectFactory.CreateLocalSettings(_globalSettings.Object, _factory);
            _settings.SetupGet(x => x.AutoIndent).Returns(false);
            _settings.SetupGet(x => x.GlobalSettings).Returns(_globalSettings.Object);
            _settings.SetupGet(x => x.ExpandTab).Returns(true);
            _settings.SetupGet(x => x.TabStop).Returns(4);
            _outlining = _factory.Create<IOutliningManager>();
            _outlining
                .Setup(x => x.ExpandAll(It.IsAny<SnapshotSpan>(), It.IsAny<Predicate<ICollapsed>>()))
                .Returns<IEnumerable<ICollapsible>>(null);
            _globalSettings.SetupGet(x => x.ShiftWidth).Returns(2);
            _statusUtil = _factory.Create<IStatusUtil>();
            _searchService = VimUtil.CreateSearchService(_globalSettings.Object);
            _undoRedoOperations = VimUtil.CreateUndoRedoOperations(_statusUtil.Object);

            var data = new OperationsData(
                vimData: _vimData,
                vimHost: _host.Object,
                editorOperations: _editorOperations.Object,
                textView: _textView,
                outliningManager: FSharpOption.Create(_outlining.Object),
                jumpList: _jumpList.Object,
                localSettings: _settings.Object,
                undoRedoOperations: _undoRedoOperations,
                registerMap: _registerMap,
                editorOptions: _editorOptions,
                keyMap: null,
                statusUtil: _statusUtil.Object,
                foldManager: null,
                searchService: _searchService,
                wordUtil: VimUtil.GetWordUtil(_textView));

            _operationsRaw = new CommonOperations(data);
            _operations = _operationsRaw;
        }
        public EditorToSettingSynchronizerTest()
        {
            _synchronizer = new EditorToSettingSynchronizer(EditorOptionsFactoryService, Vim);

            _buffer = CreateVimBuffer("");
            _localSettings = _buffer.LocalSettings;
            _globalSettings = _localSettings.GlobalSettings;
            _editorOptions = _buffer.TextView.Options;
        }
        public void Setup()
        {
            _synchronizer = new EditorToSettingSynchronizer(EditorUtil.FactoryService.EditorOptionsFactory, EditorUtil.FactoryService.Vim);

            var textView = EditorUtil.CreateTextView("");
            _buffer = EditorUtil.FactoryService.Vim.CreateVimBuffer(textView);
            _localSettings = _buffer.LocalSettings;
            _globalSettings = _localSettings.GlobalSettings;
            _editorOptions = EditorUtil.FactoryService.EditorOptionsFactory.GetOptions(textView);
        }
 public TemplateTypingCommandHandler(
     ITextView textView,
     ITextBuffer textBuffer,
     IEditorOptions editorOptions,
     IEditorOperations editorOperations)
     : base(textView, _ => textBuffer)
 {
     _editorOperations = editorOperations;
     _editorOptions = editorOptions;
 }
		public TabOptionsListener(IWpfTextView textView)
		{
			TextView = textView;
			Options = textView.Options;

			Options.OptionChanged += OnTextViewOptionChanged;
			TextView.Closed += TextViewOnClosed;

			_OnConvertTabsToSpacesOptionChanged();
			OnIndentSizeOptionChanged();
		}
        internal static void SetEditorOptions(IEditorOptions options, Guid languageServiceGuid)
        {
            IVsTextManager textMgr = (IVsTextManager)InteractiveWindowPackage.GetGlobalService(typeof(SVsTextManager));
            var langPrefs = new LANGPREFERENCES[1];
            langPrefs[0].guidLang = languageServiceGuid;
            ErrorHandler.ThrowOnFailure(textMgr.GetUserPreferences(null, null, langPrefs, null));

            options.SetOptionValue(DefaultTextViewHostOptions.ChangeTrackingId, false);
            options.SetOptionValue(DefaultOptions.ConvertTabsToSpacesOptionId, langPrefs[0].fInsertTabs == 0);
            options.SetOptionValue(DefaultOptions.TabSizeOptionId, (int)langPrefs[0].uTabSize);
            options.SetOptionValue(DefaultOptions.IndentSizeOptionId, (int)langPrefs[0].uIndentSize);
        }
            public RemoteHostClientService(
                Workspace workspace,
                IDiagnosticAnalyzerService analyzerService,
                IEditorOptions globalEditorOptions) :
                base()
            {
                _gate = new object();

                _workspace = workspace;
                _analyzerService = analyzerService;
                _globalEditorOptions = globalEditorOptions;
            }
        public static IElisionBuffer CreateElisionBufferWithoutIndentation(
            this IProjectionBufferFactoryService factoryService,
            IEditorOptions editorOptions,
            IContentType contentType,
            IEnumerable<SnapshotSpan> exposedSpans)
        {
            var spans = new NormalizedSnapshotSpanCollection(exposedSpans);

            if (spans.Count > 0)
            {
                // BUG(6335): We have to make sure that the spans refer to the current snapshot of
                // the buffer.
                var buffer = spans.First().Snapshot.TextBuffer;
                var currentSnapshot = buffer.CurrentSnapshot;
                spans = new NormalizedSnapshotSpanCollection(
                    spans.Select(s => s.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeExclusive)));
            }

            contentType = contentType ?? factoryService.ProjectionContentType;
            var elisionBuffer = factoryService.CreateElisionBuffer(
                null, spans, ElisionBufferOptions.None, contentType);

            if (spans.Count > 0)
            {
                var snapshot = spans.First().Snapshot;
                var buffer = snapshot.TextBuffer;

                // We need to figure out the shorted indentation level of the exposed lines.  We'll
                // then remove that indentation from all lines.
                var indentationColumn = DetermineIndentationColumn(editorOptions, spans);

                var spansToElide = new List<Span>();

                foreach (var span in spans)
                {
                    var startLineNumber = snapshot.GetLineNumberFromPosition(span.Start);
                    var endLineNumber = snapshot.GetLineNumberFromPosition(span.End);

                    for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++)
                    {
                        var line = snapshot.GetLineFromLineNumber(lineNumber);
                        var lineOffsetOfColumn = line.GetLineOffsetFromColumn(indentationColumn, editorOptions);
                        spansToElide.Add(Span.FromBounds(line.Start, line.Start + lineOffsetOfColumn));
                    }
                }

                elisionBuffer.ElideSpans(new NormalizedSpanCollection(spansToElide));
            }

            return elisionBuffer;
        }
        public EditorToSettingSynchronizerTest()
        {
            _synchronizer = new EditorToSettingSynchronizer();

            var textView = CreateTextView();
            var globalSettings = new GlobalSettings();
            _localSettings = new LocalSettings(globalSettings);
            _windowSettings = new WindowSettings(globalSettings);
            _editorOptions = textView.Options;
            _vimBuffer = new Mock<IVimBuffer>(MockBehavior.Strict);
            _vimBuffer.SetupGet(x => x.LocalSettings).Returns(_localSettings);
            _vimBuffer.SetupGet(x => x.WindowSettings).Returns(_windowSettings);
            _vimBuffer.SetupGet(x => x.TextView).Returns(textView);
        }
Beispiel #20
0
		public GenericSceneEditor(
			IEditorEnvironment editorEnvironment,
			IComponentContext context,
			ToeGraphicsContext graphicsContext,
			IEditorOptions<Base3DEditorOptions> options)
		{
			this.editorEnvironment = editorEnvironment;
			this.context = context;
			this.graphicsContext = graphicsContext;
			this.options = options;
			this.history = new CommandHistory();
			this.InitializeComponent();

			this.InitializeEditor();
		}
Beispiel #21
0
		public AnimEditor(
			IEditorEnvironment editorEnvironment,
			IResourceManager resourceManager,
			IComponentContext context,
			IEditorOptions<Base3DEditorOptions> options,
			Base3DEditorContent content)
			: base(context, options, content)
		{
			this.editorEnvironment = editorEnvironment;
			this.resourceManager = resourceManager;
			this.InitializeComponent();

			this.InitializeEditor();
			base.RenderScene += this.RenderAnimScene;
		}
 public static IProjectionBuffer CreateProjectionBufferWithoutIndentation(
     this IProjectionBufferFactoryService factoryService,
     IContentTypeRegistryService registryService,
     IEditorOptions editorOptions,
     ITextSnapshot snapshot,
     string separator,
     params LineSpan[] exposedLineSpans)
 {
     return factoryService.CreateProjectionBufferWithoutIndentation(
         registryService,
         editorOptions,
         snapshot,
         separator,
         suffixOpt: null,
         exposedLineSpans: exposedLineSpans);
 }
Beispiel #23
0
		public MainEditorWindow(IComponentContext context, IEditorOptions<MainEditorWindowOptions> options)
		{
			this.context = context;
			this.options = options;
			this.InitializeComponent();
			this.fileTabs.SelectedIndexChanged += this.RebindToEditor;

			if (options.Options.RecentFiles == null)
			{
				options.Options.RecentFiles = new ObservableCollection<string>();
			}

			options.Options.RecentFiles.CollectionChanged += this.ResetRecentFilesMenu;
			this.ResetRecentFilesMenu(
				options.Options.RecentFiles, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
		}
Beispiel #24
0
		public TextureEditor(
			IEditorEnvironment editorEnvironment,
			IResourceManager resourceManager,
			IComponentContext context,
			ToeGraphicsContext graphicsContext,
			IEditorOptions<Base3DEditorOptions> options,
			Base3DEditorContent content)
			: base(context, options, content)
		{
			this.editorEnvironment = editorEnvironment;
			this.resourceManager = resourceManager;
			this.graphicsContext = graphicsContext;
			this.InitializeComponent();

			this.InitializeEditor();
			base.RenderScene += this.RenderTexScene;
		}
Beispiel #25
0
		public MaterialPreview(
			MaterialEditor editor,
			ToeGraphicsContext graphicsContext,
			IComponentContext context,
			IEditorOptions<Base3DEditorOptions> options,
			Base3DEditorContent content,
			IStreamConverterFactory streamConverterFactory)
			: base(context, options, content)
		{
			this.editor = editor;
			this.graphicsContext = graphicsContext;
			this.Camera.Ortho = false;
			this.Camera.ZNear = 16.0f;
			this.Camera.ZFar = 2048.0f;
			base.RenderScene += this.RenderMaterialScene;
			this.box = BoxBuilder.BuildSoftEdgedBox(250, streamConverterFactory);
		}
Beispiel #26
0
		public ModelEditor(
			IEditorEnvironment editorEnvironment,
			IResourceManager resourceManager,
			IComponentContext context,
			ToeGraphicsContext graphicsContext,
			IEditorOptions<Base3DEditorOptions> options,
			ICommandHistory history)
		{
			this.editorEnvironment = editorEnvironment;
			this.resourceManager = resourceManager;
			this.context = context;
			this.graphicsContext = graphicsContext;
			this.options = options;
			this.history = history;
			this.dataContext.DataContextChanged += ResetModel;
			this.InitializeComponent();

			this.InitializeEditor();
		}
Beispiel #27
0
		public AddNewItemForm(
			IEditorOptions<AddNewItemFormOptions> editorOptions, IEnumerable<IResourceEditorFactory> resourceFileFormats)
		{
			this.editorOptions = editorOptions;
			this.InitializeComponent();
			var directoryHistory = this.Options.DirectoryHistory;
			if (directoryHistory.Count == 0)
			{
				this.txtFolder.Text = Directory.GetCurrentDirectory();
			}
			else
			{
				this.txtFolder.Text = directoryHistory[directoryHistory.Count - 1];
				var autoCompleteSource = new AutoCompleteStringCollection();
				autoCompleteSource.AddRange(directoryHistory.ToArray());
				this.txtFolder.AutoCompleteCustomSource = autoCompleteSource;
				this.txtFolder.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
				this.txtFolder.AutoCompleteSource = AutoCompleteSource.CustomSource;
			}

			if (resourceFileFormats != null)
			{
				foreach (var fileFormat in resourceFileFormats)
				{
					ListViewGroup group = null;
					foreach (var format in fileFormat.SupportedFormats)
					{
						if (format.CanCreate)
						{
							if (group == null)
							{
								group = new ListViewGroup(fileFormat.Name);
								this.listView1.Groups.Add(group);
							}
							this.listView1.Items.Add(new ListViewItem(format.Name, group) { Tag = format });
						}
					}
				}
			}
		}
Beispiel #28
0
        public CommandFilter(
            IVsTextView textView,
            IWpfTextView wpfTextView,
            IHtmlBuilderService htmlBuilderService,
            IRtfBuilderService rtfBuilderService,
            IEditorOperations editorOperations,
            ITextUndoHistory undoHistory,
            IEditorOptions editorOptions,
            IViewPrimitives viewPrimitives,
            ITelemetrySession telemetrySession)
        {
            _htmlBuilderService = htmlBuilderService;
            _rtfBuilderService = rtfBuilderService;
            _undoHistory = undoHistory;
            _textView = wpfTextView;
            _editorOperations = editorOperations;
            _editorOptions = editorOptions;
            _viewPrimitives = viewPrimitives;
            _telemetrySession = telemetrySession;

            textView.AddCommandFilter(this, out _nextCommandTargetInChain);
        }
Beispiel #29
0
 public static bool GetAutoInsertAttributeValue(this IEditorOptions options)
 => options.GetOptionValue(XmlOptions.AutoInsertAttributeValue);
Beispiel #30
0
        public EditFilter(System.IServiceProvider serviceProvider, ITextView textView, IEditorOperations editorOps, IEditorOptions editorOptions, IIntellisenseSessionStack intellisenseStack, IComponentModel compModel)
        {
            _serviceProvider   = serviceProvider;
            _textView          = textView;
            _editorOps         = editorOps;
            _intellisenseStack = intellisenseStack;
            _compModel         = compModel;
            var agg = _compModel.GetService <IClassifierAggregatorService>();

            _classifier    = agg.GetClassifier(textView.TextBuffer);
            _incSearch     = _compModel.GetService <IIncrementalSearchFactoryService>().GetIncrementalSearch(_textView);
            _broker        = _compModel.GetService <ICompletionBroker>();
            _editorOptions = editorOptions;
        }
Beispiel #31
0
 public SmartIndent(WorkspaceDocument <ITextBuffer> document, IEditorOptions options)
 {
     this.document = document ?? throw new ArgumentNullException(nameof(document));
     this.options  = options ?? throw new ArgumentNullException(nameof(options));
 }
Beispiel #32
0
        protected override async Task <Control> OnGetViewControlAsync(CancellationToken token, DocumentViewContent view)
        {
            // FIXME: move this to the end of the .ctor after fixing margin options responsiveness
            UpdateLineNumberMarginOption();

            var fileModel = (TextBufferFileModel)Model;

            TextDocument = fileModel.TextDocument;
            TextBuffer   = TextDocument.TextBuffer;

            UpdateTextBufferRegistration();

            var roles = GetAllPredefinedRoles();

            ITextBuffer projectionBuffer = null;

            foreach (var projectionBufferProvider in Imports.ProjectionBufferProviders)
            {
                if (projectionBufferProvider.Value.TryGetProjectionBuffer(TextBuffer, out projectionBuffer))
                {
                    break;
                }
            }

            var dataModel = new ProjectionTextDataModel(TextBuffer, projectionBuffer);

            //we have multiple copies of VacuousTextDataModel for back-compat reasons
#pragma warning disable CS0436 // Type conflicts with imported type
            var viewModel = UIExtensionSelector.InvokeBestMatchingFactory(
                Imports.TextViewModelProviders,
                dataModel.ContentType,
                roles,
                provider => provider.CreateTextViewModel(dataModel, roles),
                Imports.ContentTypeRegistryService,
                Imports.GuardedOperations,
                this) ?? new VacuousTextViewModel(dataModel);
#pragma warning restore CS0436 // Type conflicts with imported type

            TextView = CreateTextView(viewModel, roles);
            control  = CreateControl();

            commandService    = Imports.EditorCommandHandlerServiceFactory.GetService(TextView);
            EditorOperations  = (EditorOperationsInterface)Imports.EditorOperationsProvider.GetEditorOperations(TextView);
            EditorOptions     = Imports.EditorOptionsFactoryService.GetOptions(TextView);
            TextBufferOptions = Imports.EditorOptionsFactoryService.GetOptions(TextView.TextBuffer);
            UpdateTextEditorOptions(this, EventArgs.Empty);
            contentProviders = new List <IEditorContentProvider> (Imports.EditorContentProviderService.GetContentProvidersForView(TextView));

            TextView.Properties [typeof(DocumentController)] = this;

            infoBarPresenter = Imports.InfoBarPresenterFactory?.TryGetInfoBarPresenter(TextView);

            InstallAdditionalEditorOperationsCommands();

            UpdateBufferOptions();
            SubscribeToEvents();

            // Set up this static event handling just once
            if (globalOptions == null)
            {
                globalOptions = Imports.EditorOptionsFactoryService.GlobalOptions;

                // From Mono.TextEditor.TextEditorOptions
                const double ZOOM_FACTOR  = 1.1f;
                const int    ZOOM_MIN_POW = -4;
                const int    ZOOM_MAX_POW = 8;
                var          ZOOM_MIN     = Math.Pow(ZOOM_FACTOR, ZOOM_MIN_POW);
                var          ZOOM_MAX     = Math.Pow(ZOOM_FACTOR, ZOOM_MAX_POW);

#if !WINDOWS
                globalOptions.SetMinZoomLevel(ZOOM_MIN * 100);
                globalOptions.SetMaxZoomLevel(ZOOM_MAX * 100);
#endif

                OnConfigurationZoomLevelChanged(null, EventArgs.Empty);

                globalOptions.OptionChanged += OnGlobalOptionsChanged;
                // Check for option changing in old editor
                TextEditorFactory.ZoomLevel.Changed += OnConfigurationZoomLevelChanged;
            }

            // Content providers can provide additional content
            NotifyContentChanged();

            await Load(false);

            return(control);
        }
Beispiel #33
0
        private static int CalculateIndentation(
            string baseline,
            ITextSnapshotLine line,
            IEditorOptions options,
            PythonTextBufferInfo buffer
            )
        {
            var snapshot = line.Snapshot;

            if (snapshot.TextBuffer != buffer.Buffer)
            {
                throw new ArgumentException("buffer mismatch");
            }

            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize     = options.GetIndentSize();
            var tokens      = buffer.GetTokens(line).ToList();

            while (tokens.Count > 0 && IsWhitespace(tokens[tokens.Count - 1].Category))
            {
                tokens.RemoveAt(tokens.Count - 1);
            }

            if (tokens.Count == 0 || IsUnterminatedStringToken(tokens[tokens.Count - 1], snapshot))
            {
                return(indentation);
            }

            if (HasExplicitLineJoin(tokens, snapshot))
            {
                // explicit line continuation, we indent 1 level for the continued line unless
                // we're already indented because of multiple line continuation characters.
                indentation = GetIndentation(line.GetText(), options.GetTabSize());
                var joinedLine = line.LineNumber - 1;
                if (joinedLine >= 0)
                {
                    var prevLineTokens = buffer.GetTokens(snapshot.GetLineFromLineNumber(joinedLine)).ToList();
                    if (prevLineTokens.Count == 0 || !HasExplicitLineJoin(prevLineTokens, snapshot))
                    {
                        indentation += tabSize;
                    }
                }
                else
                {
                    indentation += tabSize;
                }

                return(indentation);
            }

            var tokenStack = new Stack <TrackingTokenInfo?>();

            tokenStack.Push(null);  // end with an implicit newline
            int endAtLine = -1, currentLine = tokens.Last().LineNumber;

            foreach (var t in buffer.GetTokensInReverseFromPoint(tokens.Last().ToSnapshotSpan(snapshot).Start))
            {
                if (t.LineNumber == currentLine)
                {
                    tokenStack.Push(t);
                }
                else
                {
                    tokenStack.Push(null);
                }

                if (t.LineNumber == endAtLine)
                {
                    break;
                }
                else if (t.Category == TokenCategory.Keyword && PythonKeywords.IsOnlyStatementKeyword(t.GetText(snapshot), buffer.LanguageVersion))
                {
                    endAtLine = t.LineNumber - 1;
                }

                if (t.LineNumber != currentLine)
                {
                    currentLine = t.LineNumber;
                    if (t.Category != TokenCategory.WhiteSpace && t.Category != TokenCategory.Comment && t.Category != TokenCategory.LineComment)
                    {
                        tokenStack.Push(t);
                    }
                }
            }

            var indentStack = new Stack <LineInfo>();
            var current     = LineInfo.Empty;

            while (tokenStack.Count > 0)
            {
                var t = tokenStack.Pop();
                if (t == null)
                {
                    current.NeedsUpdate = true;
                    continue;
                }

                var tline = new Lazy <string>(() => snapshot.GetLineFromLineNumber(t.Value.LineNumber).GetText());

                if (IsOpenGrouping(t.Value, snapshot))
                {
                    indentStack.Push(current);
                    var next = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                    if (next != null && next.Value.LineNumber == t.Value.LineNumber)
                    {
                        // Put indent at same depth as grouping
                        current = new LineInfo {
                            Indentation = t.Value.ToSourceSpan().End.Column - 1
                        };
                    }
                    else
                    {
                        // Put indent at one indent deeper than this line
                        current = new LineInfo {
                            Indentation = GetIndentation(tline.Value, tabSize) + tabSize
                        };
                    }
                }
                else if (IsCloseGrouping(t.Value, snapshot))
                {
                    if (indentStack.Count > 0)
                    {
                        current = indentStack.Pop();
                    }
                    else
                    {
                        current.NeedsUpdate = true;
                    }
                }
                else if (IsExplicitLineJoin(t.Value, snapshot))
                {
                    while (t != null && tokenStack.Count > 0)
                    {
                        t = tokenStack.Pop();
                    }
                    if (!t.HasValue)
                    {
                        continue;
                    }
                }
                else if (current.NeedsUpdate == true)
                {
                    current = new LineInfo {
                        Indentation = GetIndentation(tline.Value, tabSize)
                    };
                }

                if (ShouldDedentAfterKeyword(t.Value, snapshot))      // dedent after some statements
                {
                    current.ShouldDedentAfter = true;
                }

                if (IsColon(t.Value, snapshot) &&       // indent after a colon
                    indentStack.Count == 0)             // except in a grouping
                {
                    current.ShouldIndentAfter = true;
                    // If the colon isn't at the end of the line, cancel it out.
                    // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                    current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                }
            }

            indentation = current.Indentation +
                          (current.ShouldIndentAfter ? tabSize : 0) -
                          (current.ShouldDedentAfter ? tabSize : 0);

            return(indentation);
        }
 public IWpfTextView CreateTextView(ITextViewModel viewModel, ITextViewRoleSet roles, IEditorOptions parentOptions) =>
 CreateTextView(viewModel, roles, parentOptions, null);
 public IWpfTextView CreateTextView(ITextBuffer textBuffer, ITextViewRoleSet roles, IEditorOptions parentOptions) =>
 CreateTextView(textBuffer, roles, parentOptions, null);
Beispiel #36
0
        /// <summary>
        /// Text View constructor.
        /// </summary>
        /// <param name="textViewModel">The text view model that provides the text to visualize.</param>
        /// <param name="roles">Roles for this view.</param>
        /// <param name="parentOptions">Parent options for this view.</param>
        /// <param name="factoryService">Our handy text editor factory service.</param>
        internal TextView(TextEditor textEditor, ITextViewModel textViewModel, ITextViewRoleSet roles, IEditorOptions parentOptions, TextEditorFactoryService factoryService, bool initialize = true)
        {
            _textEditor = textEditor;

            _roles = roles;

            _factoryService = factoryService;

            this.TextDataModel = textViewModel.DataModel;
            this.TextViewModel = textViewModel;

            _textBuffer = textViewModel.EditBuffer;
            //			_visualBuffer = textViewModel.VisualBuffer;

            //			_textSnapshot = _textBuffer.CurrentSnapshot;
            //			_visualSnapshot = _visualBuffer.CurrentSnapshot;

            _editorOptions        = _factoryService.EditorOptionsFactoryService.GetOptions(this);
            _editorOptions.Parent = parentOptions;

            if (initialize)
            {
                this.Initialize();
            }
        }
Beispiel #37
0
 public static int GetLineOffsetFromColumn(this ITextSnapshotLine line, int column, IEditorOptions editorOptions)
 {
     return(line.GetText().GetLineOffsetFromColumn(column, editorOptions.GetTabSize()));
 }
Beispiel #38
0
 public static int GetColumnFromLineOffset(this ITextSnapshotLine line, int lineOffset, IEditorOptions editorOptions)
 {
     return(line.GetText().GetColumnFromLineOffset(lineOffset, editorOptions.GetTabSize()));
 }
Beispiel #39
0
 public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this ITextSnapshotLine line, IEditorOptions editorOptions)
 {
     return(line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(editorOptions.GetTabSize()));
 }
        IDsWpfTextView CreateTextViewImpl(ITextViewModel textViewModel, ITextViewRoleSet roles, IEditorOptions parentOptions, TextViewCreatorOptions options)
        {
            var wpfTextView = new WpfTextView(textViewModel, roles, parentOptions, editorOptionsFactoryService, commandService, smartIndentationService, formattedTextSourceFactoryService, viewClassifierAggregatorService, textAndAdornmentSequencerFactoryService, classificationFormatMapService, editorFormatMapService, adornmentLayerDefinitionService, lineTransformProviderService, spaceReservationStackProvider, wpfTextViewConnectionListenerServiceProvider, bufferGraphFactoryService, wpfTextViewCreationListeners);

            if (options?.MenuGuid != null)
            {
                var guidObjectsProvider = new GuidObjectsProvider(wpfTextView, options?.CreateGuidObjects);
                menuService.InitializeContextMenu(wpfTextView.VisualElement, options.MenuGuid.Value, guidObjectsProvider, new ContextMenuInitializer(wpfTextView));
            }

            if (options?.EnableUndoHistory != false)
            {
                textViewUndoManagerProvider.Value.GetTextViewUndoManager(wpfTextView);
            }

            TextViewCreated?.Invoke(this, new TextViewCreatedEventArgs(wpfTextView));

            return(wpfTextView);
        }
Beispiel #41
0
 public DropShadowBorderDecoratorSettings(ImageDecoratorContext context)
 {
     Element       = context.ImgElement;
     editorOptions = context.EditorOptions;
 }
 public static int GetLineOffsetFromColumn(this ITextSnapshotLine line, int column, IEditorOptions editorOptions)
 {
     return line.GetText().GetLineOffsetFromColumn(column, editorOptions.GetTabSize());
 }
        IDnSpyWpfTextView CreateTextViewImpl(ITextViewModel textViewModel, ITextViewRoleSet roles, IEditorOptions parentOptions, TextViewCreatorOptions options, Func <IGuidObjectsProvider> createGuidObjectsProvider = null)
        {
            var guidObjectsProvider = new GuidObjectsProvider(options?.CreateGuidObjects, createGuidObjectsProvider?.Invoke());
            var wpfTextView         = new WpfTextView(textViewModel, roles, parentOptions, editorOptionsFactoryService, commandManager, smartIndentationService, formattedTextSourceFactoryService, viewClassifierAggregatorService, textAndAdornmentSequencerFactoryService, classificationFormatMapService, editorFormatMapService, adornmentLayerDefinitionService, lineTransformProviderService, wpfTextViewCreationListeners);

            guidObjectsProvider.WpfTextView = wpfTextView;

            if (options?.MenuGuid != null)
            {
                menuManager.InitializeContextMenu(wpfTextView.VisualElement, options.MenuGuid.Value, guidObjectsProvider, new ContextMenuInitializer(wpfTextView));
            }

            TextViewCreated?.Invoke(this, new TextViewCreatedEventArgs(wpfTextView));

            return(wpfTextView);
        }
Beispiel #44
0
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView)
        {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize     = options.GetIndentSize();
            var tokens      = classifier.GetClassificationSpans(line.Extent);

            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1]))
            {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                       (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                        tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace)))
                {
                    tokenIndex--;
                }

                if (tokenIndex < 0)
                {
                    return(indentation);
                }

                if (Genero4glReverseParser.IsExplicitLineJoin(tokens[tokenIndex]))
                {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0)
                    {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !Genero4glReverseParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1]))
                        {
                            indentation += tabSize;
                        }
                    }
                    else
                    {
                        indentation += tabSize;
                    }

                    return(indentation);
                }

                string sline    = tokens[tokenIndex].Span.GetText();
                var    lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                    );
                if (spans.Count == 0)
                {
                    return(indentation);
                }

                var revParser = new Genero4glReverseParser(
                    spans[0].Snapshot,
                    spans[0].Snapshot.TextBuffer,
                    spans[0].Snapshot.CreateTrackingSpan(
                        spans[0].Span,
                        SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new List <ClassificationSpan>();
                tokenStack.Insert(0, null);
                bool endAtNextNull = false;

                foreach (var token in revParser)
                {
                    tokenStack.Insert(0, token);
                    if (token == null && endAtNextNull)
                    {
                        break;
                    }
                    else if (token != null &&
                             token.ClassificationType == Genero4glClassifierProvider.Keyword)
                    {
                        var tok = Tokens.GetToken(token.Span.GetText());
                        if (tok != null && Genero4glAst.ValidStatementKeywords.Contains(tok.Kind))
                        {
                            switch (tok.Kind)
                            {
                            // Handle any tokens that are valid statement keywords in the autocomplete context but not in the "statement start" context
                            case TokenKind.EndKeyword:
                                continue;

                            default:
                                endAtNextNull = true;
                                break;
                            }
                        }
                    }
                }

                var indentStack = new System.Collections.Generic.Stack <LineInfo>();
                var current     = LineInfo.Empty;
                List <CancelIndent> cancelIndent           = null;
                int                cancelIndentStartingAt  = -1;
                TokenKind          firstStatement          = TokenKind.EndOfFile;
                TokenKind          latestIndentChangeToken = TokenKind.EndOfFile;
                ClassificationSpan firstToken = null;

                for (int i = 0; i < tokenStack.Count; i++)
                {
                    var token = tokenStack[i];
                    if (token != null && firstToken == null)
                    {
                        firstToken = token;
                    }

                    if (token == null)
                    {
                        current.NeedsUpdate = true;
                    }
                    else if (token.IsOpenGrouping())
                    {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        current = new LineInfo
                        {
                            Indentation = start.Position - line2.Start.Position + 1
                        };
                    }
                    else if (token.IsCloseGrouping())
                    {
                        if (indentStack.Count > 0)
                        {
                            current = indentStack.Pop();
                        }
                        else
                        {
                            current.NeedsUpdate = true;
                        }
                    }
                    else if (Genero4glReverseParser.IsExplicitLineJoin(token))
                    {
                        while (token != null && i + 1 < tokenStack.Count)
                        {
                            i++;
                            token = tokenStack[i];
                        }
                    }
                    else if (current.NeedsUpdate == true)
                    {
                        var tok = Tokens.GetToken(token.Span.GetText());
                        if (tok == null || !Genero4glAst.ValidStatementKeywords.Contains(tok.Kind))
                        {
                            current.NeedsUpdate = false;
                        }
                        else
                        {
                            switch (tok.Kind)
                            {
                            // Handle any tokens that are valid statement keywords in the autocomplete context but not in the "statement start" context
                            case TokenKind.EndKeyword:
                                if (firstStatement != TokenKind.EndOfFile)
                                {
                                    current.NeedsUpdate = false;
                                }
                                else
                                {
                                    latestIndentChangeToken = tok.Kind;
                                }
                                break;

                            default:
                            {
                                if (firstStatement == TokenKind.EndOfFile)
                                {
                                    firstStatement = tok.Kind;
                                }
                                var line2 = token.Span.Start.GetContainingLine();
                                current = new LineInfo
                                {
                                    Indentation = GetIndentation(line2.GetText(), tabSize)
                                };
                                break;
                            }
                            }
                        }
                    }

                    if (token != null && current.ShouldIndentAfter && cancelIndent != null)
                    {
                        // Check to see if we have following tokens that would cancel the current indent.

                        var  tok           = Tokens.GetToken(token.Span.GetText());
                        var  tokenCategory = token.ClassificationType;
                        bool allPast       = true;
                        bool cancel        = false;
                        foreach (var ci in cancelIndent)
                        {
                            if (ci.TokensAhead < (i - cancelIndentStartingAt))
                            {
                                continue;
                            }
                            else
                            {
                                allPast = false;
                                if (ci.TokensAhead == (i - cancelIndentStartingAt))
                                {
                                    if (ci.UseCategory && ci.CancelCategory != null)
                                    {
                                        cancel = tokenCategory == ci.CancelCategory;
                                    }
                                    else if (tok != null)
                                    {
                                        cancel = tok.Kind == ci.CancelToken;
                                    }
                                    if (cancel)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        if (cancel)
                        {
                            current.ShouldIndentAfter = false;
                        }
                        if (cancel || allPast)
                        {
                            cancelIndent            = null;
                            cancelIndentStartingAt  = -1;
                            latestIndentChangeToken = TokenKind.EndOfFile;
                        }
                    }

                    if (token != null && ShouldDedentAfterKeyword(token))
                    {     // dedent after some statements
                        current.ShouldDedentAfter = true;
                    }

                    TokenKind tempChangeToken;
                    if (token != null &&
                        indentStack.Count == 0 &&
                        firstToken == token &&
                        ShouldIndentAfterKeyword(token, out tempChangeToken, out cancelIndent))
                    {                               // except in a grouping
                        if (latestIndentChangeToken != TokenKind.EndKeyword)
                        {
                            current.ShouldIndentAfter = true;
                        }
                        latestIndentChangeToken = tempChangeToken;
                        if (cancelIndent != null)
                        {
                            cancelIndentStartingAt = i;
                        }
                    }
                }

                if (tokenStack.Count > 2 &&
                    tokenStack[tokenStack.Count - 2] != null)
                {
                    if (latestIndentChangeToken != TokenKind.EndOfFile &&
                        _customIndentingRules.ContainsKey(latestIndentChangeToken))
                    {
                        var potentialIndent = _customIndentingRules[latestIndentChangeToken](tokenStack, tabSize);
                        if (potentialIndent != 0)
                        {
                            return(potentialIndent);
                        }
                    }

                    // see if we have specific alignment rules
                    if (firstStatement != TokenKind.EndOfFile &&
                        _customIndentingRules.ContainsKey(firstStatement))
                    {
                        var potentialIndent = _customIndentingRules[firstStatement](tokenStack, tabSize);
                        if (potentialIndent != 0)
                        {
                            return(potentialIndent);
                        }
                    }
                }

                indentation = current.Indentation +
                              (current.ShouldIndentAfter ? tabSize : 0) -
                              (current.ShouldDedentAfter ? tabSize : 0);
            }

            return(indentation);
        }
 public IDsWpfTextView CreateTextView(ITextBuffer textBuffer, ITextViewRoleSet roles, IEditorOptions parentOptions, TextViewCreatorOptions options)
 {
     if (textBuffer == null)
     {
         throw new ArgumentNullException(nameof(textBuffer));
     }
     if (roles == null)
     {
         throw new ArgumentNullException(nameof(roles));
     }
     if (parentOptions == null)
     {
         throw new ArgumentNullException(nameof(parentOptions));
     }
     return(CreateTextView(new TextDataModel(textBuffer), roles, parentOptions, options));
 }
        /// <summary>
        /// Writes a set of images based on the settings specified in a ImagePropertiesInfo object.
        /// </summary>
        /// <param name="imageInfo">the image properties</param>
        /// <param name="allowEnlargement">if true, generated images will be scaled larger than the source image (if the imageInfo sizes are larger) </param>
        public void WriteImages(ImagePropertiesInfo imageInfo, bool allowEnlargement, ImageDecoratorInvocationSource invocationSource, CreateFileCallback inlineFileCreator, CreateFileCallback linkedFileCreator, IEditorOptions clientOptions)
        {
            string inlinePrefix = imageInfo.LinkTarget == LinkTargetType.IMAGE ? "_thumb" : "";

            ImageFilter inlineFilter = ImageFilterDecoratorAdapter.CreateImageDecoratorsFilter(imageInfo, ImageEmbedType.Embedded, invocationSource, clientOptions);
            ImageFilter targetFilter = ImageFilterDecoratorAdapter.CreateImageDecoratorsFilter(imageInfo, ImageEmbedType.Linked, invocationSource, clientOptions);

            using (Bitmap inlineBitmap = new Bitmap(imageInfo.ImageSourceUri.LocalPath))
            {
                string imgPath       = writeImage(inlineBitmap, imageInfo.ImageSourceUri.LocalPath, inlinePrefix, inlineFilter, inlineFileCreator);
                string inlineImgPath = new Uri(UrlHelper.CreateUrlFromPath(imgPath)).ToString();
                imageInfo.InlineImageUrl = inlineImgPath;
            }

            //Generate the link image
            //Warning! this imageInfo.LinkTarget check must be done after the inline image because the resize
            //         decorator will set the default link target for the image the first time it
            //         is applied.
            //imageInfo.LinkTarget = origLinkTarget;
            if (imageInfo.LinkTarget == LinkTargetType.IMAGE && !ImageDecoratorDirective.ShouldSuppressLinked)
            {
                using (Bitmap targetBitmap = new Bitmap(imageInfo.ImageSourceUri.LocalPath))
                {
                    string anchorPath = writeImage(targetBitmap, imageInfo.ImageSourceUri.LocalPath, "", targetFilter, linkedFileCreator);
                    string targetUrl  = new Uri(UrlHelper.CreateUrlFromPath(anchorPath)).ToString();
                    imageInfo.LinkTargetUrl = targetUrl;
                }
            }
        }
 public IDsWpfTextView CreateTextView(ITextViewModel viewModel, ITextViewRoleSet roles, IEditorOptions parentOptions, TextViewCreatorOptions options)
 {
     if (viewModel == null)
     {
         throw new ArgumentNullException(nameof(viewModel));
     }
     if (roles == null)
     {
         throw new ArgumentNullException(nameof(roles));
     }
     if (parentOptions == null)
     {
         throw new ArgumentNullException(nameof(parentOptions));
     }
     return(CreateTextViewImpl(viewModel, roles, parentOptions, options));
 }
Beispiel #48
0
 WordWrapCommand(IEditorOptionsFactoryService editorOptionsFactoryService)
 {
     this.editorOptions = editorOptionsFactoryService.GlobalOptions;
 }
Beispiel #49
0
 public SettingsStore(IVsSettingsManager manager, IEditorOptions options)
 {
     _options = options;
     manager.GetWritableSettingsStore((uint)__VsSettingsScope.SettingsScope_UserSettings, out _store);
 }
Beispiel #50
0
 HighlightCurrentLineCommand(IEditorOptionsFactoryService editorOptionsFactoryService)
 {
     this.editorOptions = editorOptionsFactoryService.GlobalOptions;
 }
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView)
        {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize     = options.GetIndentSize();
            var tokens      = classifier.GetClassificationSpans(line.Extent);

            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1]))
            {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                       (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                        tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace)))
                {
                    tokenIndex--;
                }

                if (tokenIndex < 0)
                {
                    return(indentation);
                }

                if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex]))
                {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0)
                    {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1]))
                        {
                            indentation += tabSize;
                        }
                    }
                    else
                    {
                        indentation += tabSize;
                    }

                    return(indentation);
                }

                string sline    = tokens[tokenIndex].Span.GetText();
                var    lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                    );
                if (spans.Count == 0)
                {
                    return(indentation);
                }

                var revParser = new ReverseExpressionParser(
                    spans[0].Snapshot,
                    spans[0].Snapshot.TextBuffer,
                    spans[0].Snapshot.CreateTrackingSpan(
                        spans[0].Span,
                        SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new System.Collections.Generic.Stack <ClassificationSpan>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                foreach (var token in revParser)
                {
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull)
                    {
                        break;
                    }
                    else if (token != null &&
                             token.ClassificationType == revParser.Classifier.Provider.Keyword &&
                             PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText()))
                    {
                        endAtNextNull = true;
                    }
                }

                var indentStack = new System.Collections.Generic.Stack <LineInfo>();
                var current     = LineInfo.Empty;

                while (tokenStack.Count > 0)
                {
                    var token = tokenStack.Pop();
                    if (token == null)
                    {
                        current.NeedsUpdate = true;
                    }
                    else if (token.IsOpenGrouping())
                    {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        var next  = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                        if (next != null && next.Span.End <= line2.End)
                        {
                            current = new LineInfo {
                                Indentation = start.Position - line2.Start.Position + 1
                            };
                        }
                        else
                        {
                            current = new LineInfo {
                                Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize
                            };
                        }
                    }
                    else if (token.IsCloseGrouping())
                    {
                        if (indentStack.Count > 0)
                        {
                            current = indentStack.Pop();
                        }
                        else
                        {
                            current.NeedsUpdate = true;
                        }
                    }
                    else if (ReverseExpressionParser.IsExplicitLineJoin(token))
                    {
                        while (token != null && tokenStack.Count > 0)
                        {
                            token = tokenStack.Pop();
                        }
                    }
                    else if (current.NeedsUpdate == true)
                    {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetIndentation(line2.GetText(), tabSize)
                        };
                    }

                    if (token != null && ShouldDedentAfterKeyword(token))       // dedent after some statements
                    {
                        current.ShouldDedentAfter = true;
                    }

                    if (token != null && token.Span.GetText() == ":" &&         // indent after a colon
                        indentStack.Count == 0)                                 // except in a grouping
                    {
                        current.ShouldIndentAfter = true;
                        // If the colon isn't at the end of the line, cancel it out.
                        // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                        current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                    }
                }

                indentation = current.Indentation +
                              (current.ShouldIndentAfter ? tabSize : 0) -
                              (current.ShouldDedentAfter ? tabSize : 0);
            }

            return(indentation);
        }
Beispiel #52
0
        public static DefaultTextViewOptions.IncludeWhitespaces VisibleWhitespaceEnabledTypes(this IEditorOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(options.GetOptionValue <DefaultTextViewOptions.IncludeWhitespaces> (DefaultTextViewOptions.UseVisibleWhitespaceIncludeId));
        }
 public DefaultSelectionPrimitive(TextView textView, IEditorOptions editorOptions)
 {
     _textView      = textView;
     _editorOptions = editorOptions;
 }
        private static IProjectionBuffer CreateProjectionBuffer(
            IProjectionBufferFactoryService factoryService,
            IContentTypeRegistryService registryService,
            IEditorOptions editorOptions,
            ITextSnapshot snapshot,
            string separator,
            object suffixOpt,
            bool trim,
            params LineSpan[] exposedLineSpans)
        {
            var spans = new List <object>();

            if (exposedLineSpans.Length > 0)
            {
                if (exposedLineSpans[0].Start > 0 && !string.IsNullOrEmpty(separator))
                {
                    spans.Add(separator);
                    spans.Add(editorOptions.GetNewLineCharacter());
                }

                var snapshotSpanRanges = CreateSnapshotSpanRanges(snapshot, exposedLineSpans);
                var indentColumn       = trim
                    ? DetermineIndentationColumn(editorOptions, snapshotSpanRanges.Flatten())
                    : 0;

                foreach (var snapshotSpanRange in snapshotSpanRanges)
                {
                    foreach (var snapshotSpan in snapshotSpanRange)
                    {
                        var line           = snapshotSpan.Snapshot.GetLineFromPosition(snapshotSpan.Start);
                        var indentPosition = line.GetLineOffsetFromColumn(indentColumn, editorOptions) + line.Start;
                        var mappedSpan     = new SnapshotSpan(snapshotSpan.Snapshot,
                                                              Span.FromBounds(indentPosition, snapshotSpan.End));

                        var trackingSpan = mappedSpan.CreateTrackingSpan(SpanTrackingMode.EdgeExclusive);

                        spans.Add(trackingSpan);

                        // Add a newline between every line.
                        if (snapshotSpan != snapshotSpanRange.Last())
                        {
                            spans.Add(editorOptions.GetNewLineCharacter());
                        }
                    }

                    // Add a separator between every set of lines.
                    if (snapshotSpanRange != snapshotSpanRanges.Last())
                    {
                        spans.Add(editorOptions.GetNewLineCharacter());
                        spans.Add(separator);
                        spans.Add(editorOptions.GetNewLineCharacter());
                    }
                }

                if (snapshot.GetLineNumberFromPosition(snapshotSpanRanges.Last().Last().End) < snapshot.LineCount - 1)
                {
                    spans.Add(editorOptions.GetNewLineCharacter());
                    spans.Add(separator);
                }
            }

            if (suffixOpt != null)
            {
                if (spans.Count >= 0)
                {
                    if (!separator.Equals(spans.Last()))
                    {
                        spans.Add(editorOptions.GetNewLineCharacter());
                        spans.Add(separator);
                    }

                    spans.Add(editorOptions.GetNewLineCharacter());
                }

                spans.Add(suffixOpt);
            }

            return(factoryService.CreateProjectionBuffer(
                       projectionEditResolver: null,
                       sourceSpans: spans,
                       options: ProjectionBufferOptions.None,
                       contentType: registryService.GetContentType(RoslynPreviewContentType)));
        }
        public static IProjectionBuffer CreateProjectionBufferWithoutIndentation(
            this IProjectionBufferFactoryService factoryService,
            IEditorOptions editorOptions,
            IContentType contentType,
            IEnumerable <SnapshotSpan> exposedSpans)
        {
            var spans = new NormalizedSnapshotSpanCollection(exposedSpans);

            if (spans.Count > 0)
            {
                // BUG(6335): We have to make sure that the spans refer to the current snapshot of
                // the buffer.
                var buffer          = spans.First().Snapshot.TextBuffer;
                var currentSnapshot = buffer.CurrentSnapshot;
                spans = new NormalizedSnapshotSpanCollection(
                    spans.Select(s => s.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeExclusive)));
            }

            contentType ??= factoryService.ProjectionContentType;
            var projectionBuffer = factoryService.CreateProjectionBuffer(
                projectionEditResolver: null,
                sourceSpans: Array.Empty <object>(),
                options: ProjectionBufferOptions.None,
                contentType: contentType);

            if (spans.Count > 0)
            {
                var finalSpans = new List <object>();

                // We need to figure out the shorted indentation level of the exposed lines.  We'll
                // then remove that indentation from all lines.
                var indentationColumn = DetermineIndentationColumn(editorOptions, spans);

                foreach (var span in spans)
                {
                    var snapshot        = span.Snapshot;
                    var startLineNumber = snapshot.GetLineNumberFromPosition(span.Start);
                    var endLineNumber   = snapshot.GetLineNumberFromPosition(span.End);

                    for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++)
                    {
                        // Compute the span clamped to this line
                        var line           = snapshot.GetLineFromLineNumber(lineNumber);
                        var finalSpanStart = Math.Max(line.Start, span.Start);
                        var finalSpanEnd   = Math.Min(line.EndIncludingLineBreak, span.End);

                        // We'll only offset if our span doesn't already start at the start of the line. See the similar exclusion in
                        // DetermineIndentationColumn that this matches.
                        if (line.Start == finalSpanStart)
                        {
                            finalSpanStart += line.GetLineOffsetFromColumn(indentationColumn, editorOptions);

                            // Paranoia: what if the indentation reversed our ordering?
                            if (finalSpanStart > finalSpanEnd)
                            {
                                finalSpanStart = finalSpanEnd;
                            }
                        }

                        // We don't expect edits to happen while this projection buffer is active. We'll choose EdgeExclusive so
                        // if they do we don't end up in any cases where there is overlapping source spans.
                        finalSpans.Add(snapshot.CreateTrackingSpan(Span.FromBounds(finalSpanStart, finalSpanEnd), SpanTrackingMode.EdgeExclusive));
                    }
                }
                projectionBuffer.InsertSpans(0, finalSpans);
            }

            return(projectionBuffer);
        }
Beispiel #56
0
 private static string GetSubmissionFromSelectedSpans(IEditorOptions editorOptions, IEnumerable <SnapshotSpan> selectedSpans)
 => string.Join(editorOptions.GetNewLineCharacter(), selectedSpans.Select(ss => ss.GetText()));
Beispiel #57
0
 public static bool GetAutoInsertClosingTag(this IEditorOptions options)
 => options.GetOptionValue(XmlOptions.AutoInsertClosingTag);
Beispiel #58
0
        public IWpfTextView CreateTextView(MonoDevelop.Ide.Editor.TextEditor textEditor, ITextViewRoleSet roles = null, IEditorOptions parentOptions = null)
        {
            if (textEditor == null)
            {
                throw new ArgumentNullException("textBuffer");
            }

            ITextBuffer    textBuffer = textEditor.GetPlatformTextBuffer();
            ITextDataModel dataModel  = new VacuousTextDataModel(textBuffer);

            ITextViewModel viewModel = UIExtensionSelector.InvokeBestMatchingFactory
                                           (TextViewModelProviders,
                                           dataModel.ContentType,
                                           roles,
                                           (provider) => (provider.CreateTextViewModel(dataModel, roles)),
                                           ContentTypeRegistryService,
                                           this.GuardedOperations,
                                           this) ?? new VacuousTextViewModel(dataModel);

            TextView view = new TextView(textEditor, viewModel, roles ?? this.DefaultRoles, parentOptions ?? this.EditorOptionsFactoryService.GlobalOptions, this);

            view.Properties.AddProperty(typeof(MonoDevelop.Ide.Editor.TextEditor), textEditor);

            this.TextViewCreated?.Invoke(this, new TextViewCreatedEventArgs(view));

            return(view);
        }
 private void ReadSettings(IEditorOptions options)
 {
     var settings_manager = ServiceProvider.GetService(typeof(SVsSettingsManager)) as IVsSettingsManager;
     var store = new SettingsStore(settings_manager, options);
     store.Load();
     SettingsLoaded = true;
 }
 public IDnSpyWpfTextView CreateTextView(ITextDataModel dataModel, ITextViewRoleSet roles, IEditorOptions parentOptions, TextViewCreatorOptions options)
 {
     if (dataModel == null)
     {
         throw new ArgumentNullException(nameof(dataModel));
     }
     if (roles == null)
     {
         throw new ArgumentNullException(nameof(roles));
     }
     if (parentOptions == null)
     {
         throw new ArgumentNullException(nameof(parentOptions));
     }
     return(CreateTextView(new TextViewModel(dataModel), roles, parentOptions, options));
 }