internal CodeEditor(
			ICommandManager commandManager
			, IEditorView editorView
			, IEditorViewHost editorViewHost
			, IEditorCommands editorCommands
			, IUndoManager undoManager
			, IFindLogic findLogic
			, CodeOptionsModel codeOptionsModel
			)
		{
			this.commandManager = commandManager;
			this.editorView = editorView;
			this.editorViewHost = editorViewHost;
			this.findLogic = findLogic;
			this.editorCommands = editorCommands;
			this.undoManager = undoManager;
			FrameworkElement element = this.Element;
			element.PreviewLostKeyboardFocus += new KeyboardFocusChangedEventHandler(this.Editor_LostFocus);
			element.LostFocus += new RoutedEventHandler(this.Editor_LostFocus);
			if (this.commandManager != null)
			{
				this.commandManager.CommandExecuting += new CommandExecutionEventHandler(this.Editor_LostFocus);
			}
			this.editorView.Background = Brushes.White;
			TextFormattingRunProperties.DefaultProperties.SetTypeface(new Typeface(FontName));
			TextFormattingRunProperties.DefaultProperties.SetFontRenderingEmSize(FontSize);
			this.editorViewHost.LineNumberGutterForegroundColor = Colors.Black;
			this.editorViewHost.LineNumberGutterTypeface = new Typeface(FontName);
			this.editorViewHost.LineNumberGutterFontSize = FontSize;
			this.editorView.Invalidate();
			this.codeOptionsModel = codeOptionsModel;
			this.codeOptionsModel.PropertyChanged += new PropertyChangedEventHandler(this.CodeOptionsModel_PropertyChanged);
			this.UpdateOptions();
		}
        protected override bool RequestSession(IEditorView view, object context)
        {
            var linkTagContext = context as LinkTagContext;
            if (linkTagContext == null)
                return false;

            var linkTag = linkTagContext.TagRange.Tag;
            var session = new QuickInfoSession()
            {
                Context = context,
            };

            if (linkTag.NavigationType == LinkTagNavigationType.ExternalUrl)
            {
                var htmlSnippet = string.Format("{0}<br/>Shift + Click to follow link", linkTag.Url);
                session.Content = new HtmlContentProvider(htmlSnippet).GetContent();
            }
            else
            {
                session.Content = new QuickDocumentView() {DocumentId = linkTag.Url};
            }

            session.Open(view, linkTagContext.TagRange.SnapshotRange);

            return true;
        }
		protected virtual CompletionContext GetCompletionContext(IEditorView view)
		{
			var reader = view.GetReader();

			var token = reader.ReadTokenReverse();
			var completionContext = new CompletionContext();

			if (token == null)
				return completionContext;

			var tokenText = reader.PeekText(token.Length);
			if (token.Key == "Identifier" || (token.Key == "Punctuation" && tokenText == "."))
			{
				var memberExpression = DetermineFullMemberExpression(tokenText, reader);

				if (memberExpression.Contains("."))
					completionContext.IsObjectMember = true;

				if (memberExpression.StartsWith("this."))
				{
					completionContext.IsDocumentProperty = true;
					var completedPath = memberExpression.Substring("this.".Length);
					var lastDot = completedPath.LastIndexOf('.');
					completedPath = lastDot >= 0 ? completedPath.Substring(0, lastDot) : "";
					completionContext.CompletedPropertyPath = completedPath;
				}
			}

			return completionContext;
		}
 public EditorViewModel(IUnityContainer container, IEditorView view)
     : base(view)
 {
     _container = container;
     GlobalCommands.superTestMethod.RegisterCommand(
         new DelegateCommand(OpenFileAndReplace, CanOpenFileAndReplace));
 }
        public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
        {
            var session = new CompletionSession()
            {

            };

            var completionContext = GetCompletionContext(view);

            if (completionContext.IsDocumentProperty)
            {
                var properties = GetProperties(completionContext.CompletedPropertyPath);
                foreach (var property in properties)
                {
                    session.Items.Add(new CompletionItem()
                    {
                        ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
                        Text = property,
                        AutoCompletePreText = property,
                        DescriptionProvider =
                            new HtmlContentProvider(string.Format("Document Property <em>{0}</em>", property))
                    }); 
                }
            }
            else if (!completionContext.IsObjectMember)
            {
                session.Items.Add(new CompletionItem()
                {
                    ImageSourceProvider = new CommonImageSourceProvider(CommonImage.MethodPublic),
                    Text = "LoadDocument",
                    AutoCompletePreText = "LoadDocument",
                    DescriptionProvider =
                        new HtmlContentProvider("(<em>documentId</em>)<br/>Loads the document with the given id")
                });

                foreach (var patchValue in patchValues)
                {
                    session.Items.Add(new CompletionItem()
                    {
                        ImageSourceProvider = new CommonImageSourceProvider(CommonImage.ConstantPublic),
                        Text = patchValue.Key,
                        AutoCompletePreText = patchValue.Key,
                        DescriptionProvider =
                            new HtmlContentProvider(
                                          string.Format("Script Parameter <em>{0}</em>. Current value: <em>{1}</em>",
                                                        patchValue.Key, patchValue.Value))
                    });
                }
            }

            if (session.Items.Count > 0)
            {
                session.Open(view);
                return true;
            }
            else
            {
                return false;
            }
        }
		public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
		{
			var session = new CompletionSession
			              {
			              	CanCommitWithoutPopup = canCommitWithoutPopup,
			              	CanFilterUnmatchedItems = true,
			              	MatchOptions = CompletionMatchOptions.UseAcronyms,
			              };

		    var context = GetCompletionContext(view);

            if (context.Field != null)
            {
                if (!isInFieldsOnlyMode)
                {
                    PopulateTerm(context.Field, session, view, context.Prefix);
                }
            }
			else
			{
				PopulateFields(session);
			}

			if (session.Items.Count == 0) return false;

			session.Selection = new CompletionSelection(session.Items.First(), CompletionSelectionState.Partial);
			session.Open(view);

			return true;
		}
        public EraserRenderer(IEraserRendererState state, IEditorView editorView)
        {
            state.ThrowIfNull("state");
            editorView.ThrowIfNull("editorView");

            _state = state;
            _editorView = editorView;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="SourceEditorViewHelper"/> class.
		/// </summary>
		/// <exception cref="ArgumentNullException">
		/// <para><paramref name="editorView"/> is <see langword="null"/>.</para>
		/// </exception>
		public SourceEditorViewHelper(IEditorView editorView)
			: base(editorView)
		{
			if (editorView == null)
			{
				throw new ArgumentNullException("editorView");
			}

			_editorView = editorView;
		}
        public override object GetContext(IEditorView view, int offset)
        {
            using (var tagAggregator = view.CreateTagAggregator<LinkTag>())
            {
                var tagRange = tagAggregator.GetTags(new[] {new TextSnapshotRange(view.CurrentSnapshot, offset)})
                    .FirstOrDefault(tag => tag.Tag != null && tag.SnapshotRange.Contains(offset));

                return tagRange != null ? new LinkTagContext {TagRange = tagRange} : null;
            }
        }
Exemple #10
0
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            Factor = model as Factor;
            FactorView = view as IEditorView;
            ExplorerPresenter = explorerPresenter;

            FactorView.Lines = Factor.Specifications.ToArray();

            FactorView.TextHasChangedByUser += OnTextHasChangedByUser;
            FactorView.ContextItemsNeeded += OnContextItemsNeeded;
            ExplorerPresenter.CommandHistory.ModelChanged += OnModelChanged;
        }
        /// <summary>
        /// Retrieves contained language host for a given text buffer.
        /// </summary>
        /// <param name="editorView">Primary text view</param>
        /// <param name="editorBuffer">Contained language text buffer</param>
        /// <returns>Contained language host, <seealso cref="IContainedLanguageHost"/></returns>
        public IContainedLanguageHost GetContainedLanguageHost(IEditorView editorView, IEditorBuffer editorBuffer)
        {
            var containedLanguageHost = editorBuffer.GetService <IContainedLanguageHost>();

            if (containedLanguageHost == null)
            {
                var document = editorView.EditorBuffer.GetEditorDocument <IMdEditorDocument>();
                Debug.Assert(document != null);
                containedLanguageHost = new MdContainedLanguageHost(document, editorBuffer);
            }
            return(containedLanguageHost);
        }
        /// <summary>
        /// Initializes a new instance of the <c>WordHighlightTagger</c> class.
        /// </summary>
        /// <param name="view">The view to which this manager is attached.</param>
        public WordHighlightTagger(IEditorView view) : base("Custom",
                                                            new Ordering[] { new Ordering(TaggerKeys.Token, OrderPlacement.Before) }, view.SyntaxEditor.Document)
        {
            // Initialize
            this.view = view;
            this.view.SelectionChanged += OnViewSelectionChanged;

            HighlightedStringChanged += UpdateHighlights;

            // Update current word
            this.UpdateHighlights();
        }
Exemple #13
0
        public override object GetContext(IEditorView view, int offset)
        {
            using (var tagAggregator = view.CreateTagAggregator <LinkTag>())
            {
                var tagRange = tagAggregator.GetTags(new[] { new TextSnapshotRange(view.CurrentSnapshot, offset) })
                               .FirstOrDefault(tag => tag.Tag != null && tag.SnapshotRange.Contains(offset));

                return(tagRange != null ? new LinkTagContext {
                    TagRange = tagRange
                } : null);
            }
        }
        private static CompletionContext GetCompletionContext(IEditorView view)
        {
            var reader = view.GetReader();

            var hasSkippedWhitespace = false;

            while (true)
            {
                var token = reader.ReadTokenReverse();

                if (token == null)
                {
                    return(new CompletionContext());
                }

                if (token.Key == "Whitespace")
                {
                    hasSkippedWhitespace = true;
                    continue;
                }

                var tokenText = reader.PeekText(token.Length);

                if (token.Key == "Field")
                {
                    return new CompletionContext {
                               Field = GetFieldName(tokenText), Prefix = ""
                    }
                }
                ;

                if ((token.Key == "Operator" && preTermOperators.Contains(tokenText)) ||
                    token.Key == "OpenQuotes" ||
                    token.Key == "RangeQueryStart")
                {
                    var field = FindPrecedingField(reader);

                    return(new CompletionContext {
                        Field = field, Prefix = ""
                    });
                }

                if (!hasSkippedWhitespace && (token.Key == "Value" || token.Key == "StringText"))
                {
                    var field = FindPrecedingField(reader);
                    return(new CompletionContext {
                        Field = field, Prefix = tokenText
                    });
                }

                return(new CompletionContext());
            }
        }
Exemple #15
0
 /// <summary>
 /// Formats specific AST node
 /// </summary>
 public static void FormatNode(IEditorView editorView, IEditorBuffer textBuffer, IServiceContainer services, IAstNode node, int limit = -1)
 {
     if (node != null)
     {
         if (limit >= 0 && limit < node.Start)
         {
             throw new ArgumentException(nameof(limit));
         }
         var range = limit < 0 ? node as ITextRange : TextRange.FromBounds(node.Start, limit);
         UndoableFormatRange(editorView, textBuffer, range, services);
     }
 }
Exemple #16
0
        /// <summary>Attach the cultivar model to the cultivar view</summary>
        /// <param name="model">The mode</param>
        /// <param name="view">The view</param>
        /// <param name="explorerPresenter">The parent explorer presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.cultivar = model as Cultivar;
            this.view = view as IEditorView;
            this.explorerPresenter = explorerPresenter;

            this.view.Lines = this.cultivar.Commands;

            this.view.LeaveEditor += this.OnCommandsChanged;
            this.view.ContextItemsNeeded += this.OnContextItemsNeeded;
            this.explorerPresenter.CommandHistory.ModelChanged += this.OnModelChanged;
        }
        private void PopulateTerm(string field, CompletionSession session, IEditorView view, string termPrefix)
        {
            if (termPrefix.StartsWith("\""))
            {
                termPrefix = termPrefix.Substring(1);
            }

            if (termPrefix.EndsWith("\""))
            {
                termPrefix = termPrefix.Substring(0, termPrefix.Length - 1);
            }

            if (fieldTermsDictionary.ContainsKey(field) == false)
            {
                return;
            }

            var           termsDictionary = fieldTermsDictionary[field];
            List <string> terms;

            if (termsDictionary.ContainsKey(termPrefix))
            {
                terms = termsDictionary[termPrefix];
            }
            else
            {
                terms = new List <string>();
                termsDictionary[termPrefix] = terms;

                QueryIndexAutoComplete.GetTermsForFieldAsync(indexName, field, terms, termPrefix)
                .ContinueOnSuccessInTheUIThread(() =>
                {
                    PopulateTerm(field, session, view, termPrefix);
                    var completionItem = session.Items.FirstOrDefault();
                    if (completionItem != null)
                    {
                        session.Selection = new CompletionSelection(completionItem, CompletionSelectionState.Partial);
                        session.Open(view);
                    }
                });
            }

            foreach (var term in terms)
            {
                var maybeQuotedTerm = term.IndexOfAny(new[] { ' ', '\t' }) == -1 ? term : "\"" + term + "\"";
                session.Items.Add(new CompletionItem
                {
                    Text = term,
                    ImageSourceProvider = new CommonImageSourceProvider(CommonImage.ConstantPublic),
                    AutoCompletePreText = maybeQuotedTerm,
                });
            }
        }
        /// <summary>
        /// Returns an object describing the quick info context for the specified text offset, if any.
        /// </summary>
        /// <param name="view">The <see cref="IEditorView"/> in which the offset is located.</param>
        /// <param name="offset">The text offset to examine.</param>
        /// <returns>
        /// An object describing the quick info context for the specified text offset, if any.
        /// A <see langword="null"/> value indicates that no context is available.
        /// </returns>
        /// <remarks>
        /// This method is called in response to keyboard events.
        /// </remarks>
        public override object GetContext(IEditorView view, int offset)
        {
            // Get the context factory service
            SimpleContextFactory contextFactory = view.SyntaxEditor.Document.Language.GetService <SimpleContextFactory>();

            if (contextFactory != null)
            {
                // Get a context
                return(contextFactory.CreateContext(new TextSnapshotOffset(view.CurrentSnapshot, offset), false));
            }
            return(null);
        }
Exemple #19
0
        /// <summary>Attach the cultivar model to the cultivar view</summary>
        /// <param name="model">The mode</param>
        /// <param name="view">The view</param>
        /// <param name="explorerPresenter">The parent explorer presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.cultivar          = model as Cultivar;
            this.view              = view as IEditorView;
            this.explorerPresenter = explorerPresenter;

            this.view.Lines = this.cultivar.Commands;

            this.view.LeaveEditor        += this.OnCommandsChanged;
            this.view.ContextItemsNeeded += this.OnContextItemsNeeded;
            this.explorerPresenter.CommandHistory.ModelChanged += this.OnModelChanged;
        }
Exemple #20
0
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            Factor            = model as Factor;
            FactorView        = view as IEditorView;
            ExplorerPresenter = explorerPresenter;

            FactorView.Lines = Factor.Specifications.ToArray();

            FactorView.TextHasChangedByUser += OnTextHasChangedByUser;
            FactorView.ContextItemsNeeded   += OnContextItemsNeeded;
            ExplorerPresenter.CommandHistory.ModelChanged += OnModelChanged;
        }
        /// <summary>
        /// Occurs when the manager is closed and detached from the view.
        /// </summary>
        /// <remarks>
        /// The default implementation of this method does nothing.
        /// Overrides should release any event handlers set up in the manager's constructor.
        /// </remarks>
        protected override void OnClosed()
        {
            // Detach from the view
            if (view != null)
            {
                view.SelectionChanged -= new EventHandler <EditorViewSelectionEventArgs>(OnViewSelectionChanged);
                view = null;
            }

            // Call the base method
            base.OnClosed();
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        // PUBLIC PROCEDURES
        /////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Occurs when the tagger is closed.
        /// </summary>
        protected override void OnClosed()
        {
            // Detach from the view
            if (view != null)
            {
                view.VisualElement.SizeChanged -= OnViewSizeChanged;
                view = null;
            }

            // Call the base method
            base.OnClosed();
        }
Exemple #23
0
 public override void Execute(IEditorView view)
 {
     if (m_view == null)
     {
         view.SyntaxEditor.ViewActionExecuting += this.SyntaxEditor_ViewActionExecuting;
         m_view = view;
     }
     else
     {
         m_view.SyntaxEditor.ViewActionExecuting -= this.SyntaxEditor_ViewActionExecuting;
         m_view = null;
     }
 }
Exemple #24
0
        /// <summary>
        /// Attach model to view.
        /// </summary>
        /// <param name="model">The model object</param>
        /// <param name="view">The view object</param>
        /// <param name="explorerPresenter">The explorer presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.operations            = model as Operations;
            this.view                  = view as IEditorView;
            this.explorerPresenter     = explorerPresenter;
            this.intellisense          = new IntellisensePresenter(view as ViewBase);
            intellisense.ItemSelected += OnIntellisenseItemSelected;

            this.PopulateEditorView();
            this.view.ContextItemsNeeded   += this.OnContextItemsNeeded;
            this.view.TextHasChangedByUser += this.OnTextHasChangedByUser;
            this.explorerPresenter.CommandHistory.ModelChanged += this.OnModelChanged;
        }
Exemple #25
0
        /// <summary>
        /// Attach the view
        /// </summary>
        /// <param name="model">The model</param>
        /// <param name="view">The view to attach</param>
        /// <param name="explorerPresenter">The presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.factor           = model as Factor;
            this.factorView       = view as IEditorView;
            this.presenter        = explorerPresenter;
            intellisense          = new IntellisensePresenter(factorView as ViewBase);
            this.factorView.Lines = this.factor.Specifications?.ToArray() ?? new string[0];

            this.factorView.TextHasChangedByUser       += this.OnTextHasChangedByUser;
            this.factorView.ContextItemsNeeded         += this.OnContextItemsNeeded;
            this.presenter.CommandHistory.ModelChanged += this.OnModelChanged;
            intellisense.ItemSelected += OnIntellisenseItemSelected;
        }
Exemple #26
0
        public override bool CanExecute(IEditorView view)
        {
            object calcResult = this.Calc.LastResult;

            if (calcResult is int || calcResult is long)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Occurs when the selection is changed in the specified <see cref="IEditorView"/>.
        /// </summary>
        /// <param name="view">The <see cref="IEditorView"/> that received the event.</param>
        /// <param name="e">The <c>EditorViewSelectionEventArgs</c> that contains the event data.</param>
        protected virtual void OnViewSelectionChanged(IEditorView view, EditorViewSelectionEventArgs e)
        {
            if (view == null)
            {
                throw new ArgumentNullException("view");
            }

            // Look for an existing session
            var session = view.SyntaxEditor.IntelliPrompt.Sessions[IntelliPromptSessionTypes.ParameterInfo] as IParameterInfoSession;

            if ((session != null) && (session.IsOpen))
            {
                // Quit if for a different view
                if (view != session.View)
                {
                    return;
                }

                // Get the context
                var requestNewSession = false;
                var context           = new SimpleContextFactory().CreateContext(view.Selection.EndSnapshotOffset, true);
                if ((context != null) && (context.ArgumentListSnapshotOffset.HasValue))
                {
                    // If the current session is still valid...
                    if (context.ArgumentListSnapshotOffset.Value.Offset == session.SnapshotRange.StartOffset)
                    {
                        // If the current parameter was updated...
                        if (UpdateCurrentParameter(session, context))
                        {
                            // Refresh content
                            session.Refresh();
                        }
                        return;
                    }
                    else
                    {
                        // Flag to request a new session
                        requestNewSession = true;
                    }
                }

                // Close the session
                session.Close(true);

                // If a new session should be requested...
                if (requestNewSession)
                {
                    this.RequestSession(view);
                }
            }
        }
Exemple #28
0
        public CompoundUndoAction(IEditorView editorView, IServiceContainer services, bool addRollbackOnCancel = true)
        {
            var shell = services.GetService <ICoreShell>();

            if (TestEnvironment.Current == null)
            {
                var operationsService = services.GetService <IEditorOperationsFactoryService>();
                var undoProvider      = services.GetService <ITextBufferUndoManagerProvider>();

                _editorOperations    = operationsService.GetEditorOperations(editorView.As <ITextView>());
                _undoManager         = undoProvider.GetTextBufferUndoManager(_editorOperations.TextView.TextBuffer);
                _addRollbackOnCancel = addRollbackOnCancel;
            }
        }
        public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
        {
            var session = new CompletionSession();

            var completionContext = GetCompletionContext(view);

            if (completionContext.IsDocumentProperty)
            {
                var properties = GetProperties();
                foreach (var property in properties)
                {
                    session.Items.Add(new CompletionItem
                    {
                        ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
                        Text = property,
                        AutoCompletePreText = property,
                        DescriptionProvider =
                            new HtmlContentProvider(string.Format("Document Property <em>{0}</em>", property))
                    });
                }
            }
            else if (!completionContext.IsObjectMember)
            {
                session.Items.Add(new CompletionItem
                {
                    ImageSourceProvider = new CommonImageSourceProvider(CommonImage.MethodPublic),
                    Text = "sqlReplicate",
                    AutoCompletePreText = "sqlReplicate",
                    DescriptionProvider =
                        new HtmlContentProvider("Will update/insert the specified object (with the object properties matching the table columns) to the specified table, using the specified pkName<br/>sqlReplicate(table, pkName, columnsObj)")
                });

                session.Items.Add(new CompletionItem
                {
                    ImageSourceProvider = new CommonImageSourceProvider(CommonImage.FieldPublic),
                    Text = "documentId",
                    AutoCompletePreText = "documentId",
                    DescriptionProvider =
                        new HtmlContentProvider("The document id for the current document")
                });
            }

            if (session.Items.Count > 0)
            {
                session.Open(view);
                return(true);
            }

            return(false);
        }
Exemple #30
0
        public bool FormatRange(IEditorView editorView, IEditorBuffer editorBuffer, ITextRange formatRange)
        {
            var snapshot = editorBuffer.CurrentSnapshot;
            var start    = formatRange.Start;
            var end      = formatRange.End;

            if (!CanFormatRange(editorView, editorBuffer, formatRange))
            {
                return(false);
            }

            // When user clicks editor margin to select a line, selection actually
            // ends in the beginning of the next line. In order to prevent formatting
            // of the next line that user did not select, we need to shrink span to
            // format and exclude the trailing line break.
            var line = snapshot.GetLineFromPosition(formatRange.End);

            if (line.Start == formatRange.End && formatRange.Length > 0)
            {
                if (line.LineNumber > 0)
                {
                    line  = snapshot.GetLineFromLineNumber(line.LineNumber - 1);
                    end   = line.End;
                    start = Math.Min(start, end);
                }
            }

            // Expand span to include the entire line
            var startLine = snapshot.GetLineFromPosition(start);
            var endLine   = snapshot.GetLineFromPosition(end);

            // In case of formatting of multiline expressions formatter needs
            // to know the entire expression since otherwise it may not correctly
            // preserve user indentation. Consider 'x >% y' which is a plain statement
            // and needs to be indented at regular scope level vs
            //
            //      a %>% b %>%
            //          x %>% y
            //
            // where user indentation of 'x %>% y' must be preserved. We don't have
            // complete information here since expression may not be syntactically
            // correct and hence AST may not have correct information and besides,
            // the AST is damaged at this point. As a workaround, we will check
            // if the previous line ends with an operator current line starts with
            // an operator.
            int startPosition = FindStartOfExpression(editorBuffer, startLine.Start);

            formatRange = TextRange.FromBounds(startPosition, endLine.End);
            return(FormatRangeExact(editorView, editorBuffer, formatRange));
        }
Exemple #31
0
        public static void UndoableFormatRange(IEditorView editorView, IEditorBuffer textBuffer, ITextRange formatRange, IServiceContainer services)
        {
            var es = services.GetService <IEditorSupport>();

            using (var undoAction = es.CreateUndoAction(editorView)) {
                undoAction.Open(Resources.AutoFormat);
                var formatter = new RangeFormatter(services);
                var result    = formatter.FormatRange(editorView, textBuffer, formatRange);
                if (result)
                {
                    undoAction.Commit();
                }
            }
        }
Exemple #32
0
 /// <summary>
 /// Constructor
 /// </summary>
 public ManagerView(ViewBase owner) : base(owner)
 {
     notebook       = new Notebook();
     mainWidget     = notebook;
     propertyEditor = new PropertyView(this);
     scriptEditor   = new EditorView(this)
     {
         ShowLineNumbers = true,
         Language        = "c-sharp",
     };
     notebook.AppendPage(propertyEditor.MainWidget, new Label("Parameters"));
     notebook.AppendPage(((ViewBase)scriptEditor).MainWidget, new Label("Script"));
     mainWidget.Destroyed += _mainWidget_Destroyed;
 }
Exemple #33
0
        /// <summary>Attach the cultivar model to the cultivar view</summary>
        /// <param name="model">The mode</param>
        /// <param name="view">The view</param>
        /// <param name="explorerPresenter">The parent explorer presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.cultivar          = model as Cultivar;
            this.view              = view as IEditorView;
            this.explorerPresenter = explorerPresenter;

            this.view.Lines            = this.cultivar.Commands;
            intellisense               = new IntellisensePresenter(this.view as ViewBase);
            intellisense.ItemSelected += (sender, e) => this.view.InsertCompletionOption(e.ItemSelected, e.TriggerWord);

            this.view.LeaveEditor        += this.OnCommandsChanged;
            this.view.ContextItemsNeeded += this.OnContextItemsNeeded;
            this.explorerPresenter.CommandHistory.ModelChanged += this.OnModelChanged;
        }
	    private void PopulateTerm(string field, CompletionSession session, IEditorView view, string termPrefix)
		{
			if(termPrefix.StartsWith("\""))
			{
				termPrefix = termPrefix.Substring(1);
			}
			if( termPrefix.EndsWith("\""))
			{
				termPrefix = termPrefix.Substring(0,termPrefix.Length - 1);
			}

			if (fieldTermsDictionary.ContainsKey(field) == false)
				return;

			var termsDictionary = fieldTermsDictionary[field];
			List<string> terms;
			if (termsDictionary.ContainsKey(termPrefix))
			{
				terms = termsDictionary[termPrefix];
			}
			else
			{
				terms = new List<string>();
				termsDictionary[termPrefix] = terms;

			    QueryIndexAutoComplete.GetTermsForFieldAsync(indexName, field, terms, termPrefix)
			        .ContinueOnSuccessInTheUIThread(
			            () =>
			                {
			                    PopulateTerm(field, session, view, termPrefix);
			                    var completionItem = session.Items.FirstOrDefault();
			                    if (completionItem != null)
			                    {
			                        session.Selection = new CompletionSelection(completionItem,CompletionSelectionState.Partial);
                                    session.Open(view);
			                    }
			                });
			}

			foreach (var term in terms)
			{
				var maybeQuotedTerm = term.IndexOfAny(new[] {' ', '\t'}) == -1 ? term : "\"" + term + "\"";
				session.Items.Add(new CompletionItem
				{
					Text = term,
					ImageSourceProvider = new CommonImageSourceProvider(CommonImage.ConstantPublic),
					AutoCompletePreText = maybeQuotedTerm,
				});
			}
		}
Exemple #35
0
        /// <summary>
        /// Determines if secondary language can format given line.
        /// </summary>
        /// <param name="editorView">Text view</param>
        /// <param name="containedLanguageBuffer">Contained language buffer</param>
        /// <param name="lineNumber">Line number in the contained language buffer</param>
        public bool CanFormatLine(IEditorView editorView, IEditorBuffer containedLanguageBuffer, int lineNumber)
        {
            var textView   = editorView.As <ITextView>();
            var textBuffer = containedLanguageBuffer.As <ITextBuffer>();
            var line       = textBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber);
            var viewPoint  = textView.MapUpToView(line.Start);

            if (viewPoint.HasValue)
            {
                var lineText = textView.TextBuffer.CurrentSnapshot.GetLineFromPosition(viewPoint.Value).GetText();
                return(lineText.IndexOfOrdinal("```") < 0 && !lineText.TrimStart().StartsWithIgnoreCase("```{r"));
            }
            return(false);
        }
        public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
        {
            var currentInterestingToken = GetCurrentInterestingToken(view);

            var session = new CompletionSession
            {
                CanCommitWithoutPopup   = canCommitWithoutPopup,
                CanFilterUnmatchedItems = true,
                MatchOptions            = CompletionMatchOptions.UseAcronyms,
            };

            if (currentInterestingToken != null && currentInterestingToken.EndsWith(":"))
            {
                var field = currentInterestingToken.Substring(0, currentInterestingToken.Length - 1);
                if (termsDictionary.ContainsKey(field) == false)
                {
                    return(false);
                }
                var terms = termsDictionary[field];
                foreach (var term in terms)
                {
                    session.Items.Add(new CompletionItem
                    {
                        Text = term,
                        ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
                        AutoCompletePreText = term + " ",
                    });
                }
            }
            else
            {
                foreach (var field in fields)
                {
                    session.Items.Add(new CompletionItem
                    {
                        Text = field,
                        ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
                        AutoCompletePreText = field + ": ",
                    });
                }
            }

            if (session.Items.Count == 0)
            {
                return(false);
            }

            session.Open(view);
            return(true);
        }
		public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
		{
			var session = new CompletionSession();

			var completionContext = GetCompletionContext(view);

			if (completionContext.IsDocumentProperty)
			{
				var properties = GetProperties();
				foreach (var property in properties)
				{
					session.Items.Add(new CompletionItem
					{
						ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
						Text = property,
						AutoCompletePreText = property,
						DescriptionProvider =
							new HtmlContentProvider(string.Format("Document Property <em>{0}</em>", property))
					});
				}
			}
			else if (!completionContext.IsObjectMember)
			{
				session.Items.Add(new CompletionItem
				{
					ImageSourceProvider = new CommonImageSourceProvider(CommonImage.MethodPublic),
					Text = "sqlReplicate",
					AutoCompletePreText = "sqlReplicate",
					DescriptionProvider =
						 new HtmlContentProvider("Will update/insert the specified object (with the object properties matching the table columns) to the specified table, using the specified pkName<br/>sqlReplicate(table, pkName, columnsObj)")
				});

				session.Items.Add(new CompletionItem
				{
					ImageSourceProvider = new CommonImageSourceProvider(CommonImage.FieldPublic),
					Text = "documentId",
					AutoCompletePreText = "documentId",
					DescriptionProvider =
						 new HtmlContentProvider("The document id for the current document")
				});
			}

			if (session.Items.Count > 0)
			{
				session.Open(view);
				return true;
			}

			return false;
		}
        /// <summary>Attach the cultivar model to the cultivar view</summary>
        /// <param name="model">The mode</param>
        /// <param name="view">The view</param>
        /// <param name="explorerPresenter">The parent explorer presenter</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.cultivar          = model as Cultivar;
            this.view              = view as IEditorView;
            this.explorerPresenter = explorerPresenter;

            this.view.Lines            = this.cultivar.Command;
            intellisense               = new IntellisensePresenter(this.view as ViewBase);
            intellisense.ItemSelected += OnIntellisenseItemSelected;

            this.view.LeaveEditor        += this.OnCommandsChanged;
            this.view.ContextItemsNeeded += this.OnContextItemsNeeded;
            this.explorerPresenter.CommandHistory.ModelChanged += this.OnModelChanged;
        }
        public override nfloat GetRowHeight(NSOutlineView outlineView, NSObject item)
        {
            EditorViewModel     vm;
            PanelGroupViewModel group;
            string cellIdentifier;

            GetVMGroupCellItendifiterFromFacade(item, out vm, out group, out cellIdentifier);

            if (group != null)
            {
                return(24);
            }

            if (!this.registrations.TryGetValue(cellIdentifier, out EditorRegistration registration))
            {
                registration = new EditorRegistration();

                if (cellIdentifier == nameof(PanelHeaderEditorControl))
                {
                    registration.RowSize = 54;
                }
                else
                {
                    NSView      editorOrContainer = GetEditor(cellIdentifier, vm, outlineView);
                    IEditorView view = ((editorOrContainer as EditorContainer)?.EditorView) ?? editorOrContainer as IEditorView;

                    if (view == null)
                    {
                        registration.RowSize = 24;
                    }
                    else if (view.IsDynamicallySized)
                    {
                        registration.SizingInstance = view;
                    }
                    else
                    {
                        this.registrations[cellIdentifier] = registration = new EditorRegistration {
                            RowSize = view.GetHeight(vm)
                        };

                        this.firstCache[cellIdentifier] = view;
                    }
                }

                this.registrations[cellIdentifier] = registration;
            }

            return(registration.GetHeight(vm));
        }
		private static string GetCurrentInterestingToken(IEditorView view)
		{
			var textSnapshotReader = view.GetReader();
			while (true)
			{
				var lastToken = textSnapshotReader.ReadTokenReverse();
				if (lastToken == null) 
					return null;

				var currentInterestingToken = textSnapshotReader.ReadText(lastToken.Length);
				textSnapshotReader.ReadTokenReverse(); // reset the reading of the text
				if(string.IsNullOrWhiteSpace(currentInterestingToken) == false)
					return currentInterestingToken;
			}
		}
        protected override void OnViewKeyDown(IEditorView view, KeyEventArgs e)
        {
            // The base is eating the tab key - we want to forward it to the view.
            var isTab = e.Key == Key.Tab && e.KeyboardDevice.Modifiers == ModifierKeys.None;

            if (!isTab)
            {
                base.OnViewKeyDown(view, e);
            }
            else
            {
                Commit();
                e.Handled = false;
            }
        }
Exemple #42
0
 /// <summary>
 /// Extracts identifier or a keyword before caret. Typically used when inserting
 /// expansions (aka code snippets) at the caret location.
 /// </summary>
 public static string GetItemBeforeCaret(this IEditorView view, out ITextRange span, Func <RTokenType, bool> tokenTypeCheck = null)
 {
     if (!view.Caret.InVirtualSpace)
     {
         var position = view.Caret.Position;
         var line     = position.GetContainingLine();
         tokenTypeCheck = tokenTypeCheck ?? (x => x == RTokenType.Identifier);
         if (position.Position > line.Start)
         {
             return(GetItemAtPosition(line, position.Position - 1, tokenTypeCheck, out span));
         }
     }
     span = TextRange.EmptyRange;
     return(string.Empty);
 }
Exemple #43
0
        public static void FormatCurrentScope(IEditorView editorView, IEditorBuffer textBuffer, IServiceContainer services, bool indentCaret)
        {
            // Figure out caret position in the document text buffer
            var document = textBuffer.GetEditorDocument <IREditorDocument>();

            if (document == null)
            {
                return;
            }
            var caretPoint = editorView.GetCaretPosition(textBuffer);

            if (caretPoint == null)
            {
                return;
            }

            // Make sure AST is up to date
            document.EditorTree.EnsureTreeReady();
            var ast = document.EditorTree.AstRoot;
            // Find scope to format
            var scope = ast.GetNodeOfTypeFromPosition <IScope>(caretPoint.Position);

            var es = services.GetService <IEditorSupport>();

            using (var undoAction = es.CreateUndoAction(editorView)) {
                var settings = services.GetService <IREditorSettings>();
                undoAction.Open(Resources.AutoFormat);
                // Now format the scope
                var formatter = new RangeFormatter(services);
                var changed   = formatter.FormatRange(editorView, textBuffer, scope);
                if (indentCaret)
                {
                    // Formatting may change AST and the caret position so we need to reacquire both
                    caretPoint = editorView.GetCaretPosition(textBuffer);
                    if (caretPoint != null)
                    {
                        document.EditorTree.EnsureTreeReady();
                        ast   = document.EditorTree.AstRoot;
                        scope = ast.GetNodeOfTypeFromPosition <IScope>(caretPoint.Position);
                        IndentCaretInNewScope(editorView, scope, caretPoint, settings.FormatOptions);
                    }
                }
                if (changed)
                {
                    undoAction.Commit();
                }
            }
        }
Exemple #44
0
        /// <summary>
        /// Requests that an <see cref="IParameterInfoSession"/> be opened for the specified <see cref="IEditorView"/>.
        /// </summary>
        /// <param name="view">The <see cref="IEditorView"/> that will host the session.</param>
        /// <returns>
        /// <c>true</c> if a session was opened; otherwise, <c>false</c>.
        /// </returns>
        public override bool RequestSession(IEditorView view)
        {
            if (view == null)
            {
                return(false);
            }

            // Get a context object, which will be filled in if we are in a valid offset for parameter info
            var context = this.CreateContext(view);

            if (context == null)
            {
                return(false);
            }

            // Create a session
            var session = new ParameterInfoSession();

            // Add items (hardcoded in this sample)... a real implementation like the one in the Getting Started series would
            //   dynamically build this sort of data, and track the current parameter for bolding as well
            var highlightingStyleRegistry = view.HighlightingStyleRegistry;

            session.Items.Add(new SignatureItem(new HtmlContentProvider("<span style=\"color: " + HtmlContentProvider.GetKeywordForegroundColor(highlightingStyleRegistry).ToWebColor() +
                                                                        ";\">function</span> Foo()<br/><span style=\"color: " + HtmlContentProvider.GetCommentForegroundColor(highlightingStyleRegistry).ToWebColor() + ";\">Returns 0.</span>", view.DefaultBackgroundColor)));
            session.Items.Add(new SignatureItem(new HtmlContentProvider("<span style=\"color: " + HtmlContentProvider.GetKeywordForegroundColor(highlightingStyleRegistry).ToWebColor() +
                                                                        ";\">function</span> Foo(x)<br/><span style=\"color: " + HtmlContentProvider.GetCommentForegroundColor(highlightingStyleRegistry).ToWebColor() + ";\">Returns the value passed in.</span>", view.DefaultBackgroundColor)));
            session.Items.Add(new SignatureItem(new HtmlContentProvider("<span style=\"color: " + HtmlContentProvider.GetKeywordForegroundColor(highlightingStyleRegistry).ToWebColor() +
                                                                        ";\">function</span> Foo(x, y)<br/><span style=\"color: " + HtmlContentProvider.GetCommentForegroundColor(highlightingStyleRegistry).ToWebColor() + ";\">Returns the multiplicative result of the two arguments.</span>", view.DefaultBackgroundColor)));

            // Try to pick the best overload to show by default... normally this would be much more robust code where
            //   your context would include the number of arguments that have been specified and you'd base the selection on that...
            //   For this sample, we're just going to use the argument index
            switch (context.ArgumentIndex)
            {
            case 1:
                session.Selection = session.Items[2];
                break;

            case 0:
                session.Selection = session.Items[1];
                break;
            }

            // Open the session
            session.Open(view, new TextRange(context.ArgumentListOffset));

            return(true);
        }
		public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
		{
			var currentInterestingToken = GetCurrentInterestingToken(view);

			var session = new CompletionSession
			              {
			              	CanCommitWithoutPopup = canCommitWithoutPopup,
			              	CanFilterUnmatchedItems = true,
			              	MatchOptions = CompletionMatchOptions.UseAcronyms,
			              };

			if (currentInterestingToken != null && currentInterestingToken.EndsWith(":"))
			{
				var field = currentInterestingToken.Substring(0, currentInterestingToken.Length - 1);
				if (termsDictionary.ContainsKey(field) == false)
					return false;
				var terms = termsDictionary[field];
				foreach (var term in terms)
				{
					session.Items.Add(new CompletionItem
					                  {
					                  	Text = term,
					                  	ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
					                  	AutoCompletePreText = term + " ",
					                  });
				}
			}
			else
			{
				foreach (var field in fields)
				{
					session.Items.Add(new CompletionItem
					                  {
					                  	Text = field,
					                  	ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
					                  	AutoCompletePreText = field + ": ",
					                  });
				}
			}

			if (session.Items.Count == 0) return false;

			session.Open(view);
			return true;
		}
        public TextAdventureEditorGame(
			GraphicsDevice graphicsDevice,
			IEditorView editorView,
			IBoardRendererState boardRendererState,
			IPencilRendererState pencilRendererState,
			IEraserRendererState eraserRendererState)
            : base(graphicsDevice, new ContentDirectoryContentManagerProvider())
        {
            editorView.ThrowIfNull("editorView");
            boardRendererState.ThrowIfNull("boardRendererState");
            pencilRendererState.ThrowIfNull("pencilRendererState");
            eraserRendererState.ThrowIfNull("eraserRendererState");

            _editorView = editorView;
            _boardRendererState = boardRendererState;
            _pencilRendererState = pencilRendererState;
            _eraserRendererState = eraserRendererState;
        }
        protected override bool RequestSession(IEditorView view, object context)
        {
            var linkTagContext = context as LinkTagContext;
            if (linkTagContext == null)
                return false;

            var linkTag = linkTagContext.TagRange.Tag;
            var htmlSnippet = linkTag.NavigationType == LinkTagNavigationType.ExternalUrl ? "Shift-Click to navigate to Url " + linkTag.Url
                : "Shift-Click to navigate to document " + linkTag.Url;

            var session = new QuickInfoSession()
            {
                Context = context,
                Content = new HtmlContentProvider(htmlSnippet).GetContent()
            };

            session.Open(view, linkTagContext.TagRange.SnapshotRange);

            return true;
        }
        protected virtual void OnViewMouseDown(IEditorView view, MouseButtonEventArgs e)
        {
            if ((e != null) && (!e.Handled))
            {
                var hitTestResult = view.SyntaxEditor.HitTest(e.GetPosition(view.VisualElement));
                if ((hitTestResult.Type == HitTestResultType.ViewMargin)
                    && (hitTestResult.ViewMargin.Key == EditorViewMarginKeys.Indicator)
                    && (hitTestResult.ViewLine != null))
                {

                    if (view.SyntaxEditor.Document.IndicatorManager.Breakpoints.RemoveAll(tr =>
                            hitTestResult.ViewLine.TextRange.IntersectsWith(tr.VersionRange.Translate(view.CurrentSnapshot).StartOffset)) == 0)
                    {

                        int currentOffset = hitTestResult.Offset + hitTestResult.ViewLine.TabStopLevel * 4;
                        DebuggingHelper.ToggleBreakpoint(new TextSnapshotOffset(hitTestResult.Snapshot, currentOffset), true);
                    }
                }
            }
        }
        public void NotifyMouseDown(IEditorView view, MouseButtonEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift)
                return;

            var hitTestResult = view.SyntaxEditor.HitTest(e.GetPosition(view.SyntaxEditor));
            if (hitTestResult.Type != HitTestResultType.ViewTextAreaOverCharacter)
                return;

            var tag = GetLinkTag(view, hitTestResult.Offset);
            if (tag == null)
                return;

            if (tag.NavigationType == LinkTagNavigationType.ExternalUrl)
                UrlUtil.NavigateToExternal(tag.Url);
            else
                UrlUtil.Navigate("/Edit?id=" + tag.Url);

            e.Handled = true;
        }
		public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
		{
			var session = new CompletionSession
			              {
			              	CanCommitWithoutPopup = canCommitWithoutPopup,
			              	CanFilterUnmatchedItems = true,
			              	MatchOptions = CompletionMatchOptions.UseAcronyms,
			              };

			var currentToken = GetInterestingToken(view, 0);
			var prevToken = GetInterestingToken(view, 1);
			string termPrefix = null;
			if (currentToken != null && currentToken.EndsWith(":"))
			{
				PopulateTerm(currentToken, session, view, string.Empty);
			}
			else if (prevToken != null && prevToken.EndsWith(":"))
			{
				termPrefix = currentToken;
				PopulateTerm(prevToken, session, view, termPrefix);
			}
			else
			{
				foreach (var field in fields)
				{
					session.Items.Add(new CompletionItem
					                  	{
					                  		Text = field,
					                  		ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
					                  		AutoCompletePreText = field + ": ",
					                  	});
				}
			}

			if (session.Items.Count == 0) return false;

			session.Selection = new CompletionSelection(session.Items.First(), CompletionSelectionState.Partial);
			session.Open(view);
			return true;
		}
        public void NotifyMouseHover(IEditorView view, RoutedEventArgsEx e)
        {
            var state = GetState(view);

            var result = view.SyntaxEditor.HitTest(state.LastMousePosition);
            var context = tagInfoProvider.GetContext(result) as LinkTagContext;

            if (state.Session == null && context != null)
            {
                tagInfoProvider.RequestSession(view, context, canTrackMouse: false);

                state.Session =
                    view.SyntaxEditor.IntelliPrompt.Sessions.OfType<IQuickInfoSession>()
                        .FirstOrDefault(s => s.Context == context);

                if (state.Session != null)
                {
                    state.Session.Closed += delegate { state.Session = null; };
                }

            }
        }
		public bool RequestSession(IEditorView view, bool canCommitWithoutPopup)
		{
			var session = new CompletionSession
			{
				CanCommitWithoutPopup = canCommitWithoutPopup,
				CanFilterUnmatchedItems = true,
				MatchOptions = CompletionMatchOptions.UseAcronyms,
			};

			var completionContext = GetCompletionContext(view);

			if (completionContext.IsDocumentProperty && ShowDocumentProperties)
			{
				var properties = GetProperties(completionContext.CompletedPropertyPath);
				foreach (var property in properties)
				{
					session.Items.Add(new CompletionItem
					{
						ImageSourceProvider = new CommonImageSourceProvider(CommonImage.PropertyPublic),
						Text = property,
						AutoCompletePreText = property,
						DescriptionProvider =
							new HtmlContentProvider(string.Format("Document Property <em>{0}</em>", property))
					});
				}
			}
			else if (!completionContext.IsObjectMember)
			{
				AddItemsToSession(session);
			}

			if (session.Items.Count > 0)
			{
				session.Open(view);
				return true;
			}

			return false;
		}
 public EditorPresenter(IEditorView view)
 {
     this.view = view;
 }
        public void NotifyMouseWheel(IEditorView view, MouseWheelEventArgs e)
        {

        }
        public void NotifyMouseUp(IEditorView view, MouseButtonEventArgs e)
        {

        }
 private HandlerViewState GetState(IEditorView view)
 {
     return view.Properties.GetOrCreateSingleton(() => new HandlerViewState());
 }
        public void NotifyMouseEnter(IEditorView view, MouseEventArgs e)
        {

        }
        public HatchRenderer(IEditorView editorView)
        {
            editorView.ThrowIfNull("editorView");

            _editorView = editorView;
        }
        public void NotifyMouseLeave(IEditorView view, MouseEventArgs e)
        {

        }
        public void NotifyMouseMove(IEditorView view, MouseEventArgs e)
        {
            var state = GetState(view);

            state.LastMousePosition = e.GetPosition(view.SyntaxEditor);

            if (state.Session != null)
            {
                try
                {
                    var inflatedBounds = state.Session.Bounds.Value.Inflate(40);
                    if (!inflatedBounds.Contains(state.LastMousePosition))
                    {
                        state.Session.Close(true);
                    }
                }
                catch (ArgumentException)
                {
                    
                }
            }
        }