Control that wraps a TextView and adds support for user input and the caret.
상속: System.Windows.Controls.Control, IScrollInfo, IWeakEventListener, ITextEditorComponent, IServiceProvider
예제 #1
0
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     var instance = ServiceLocator.Current.GetInstance<MainViewModel>();
     var text = instance.ActiveEditor.TextBox.FindWord();
     var offset = completionSegment.Offset - text.Length;
     textArea.Document.Replace(offset, text.Length, Text);
 }
    public CompletionData[] GenerateCompletionData(string fileName, TextArea textArea)
    {
      string name = WordUtilities.FindPreviousWord(textArea);

      if (name == null)
        return EmptySuggestion(textArea.Caret);

      if (name == "specification" || name == "requires" || name == "same_machine_as" || name == "@")
      {
        return ModulesSuggestions();
      }

      if (name == "users_per_machine")
      {
        return NumbersSuggestions(50,100,150,200);
      }
      else if (name == "min_memory")
      {
          return NumbersSuggestions(1024,2048,4096,8*1024);
      }
      else if (name == "min_cpu_count")
      {
          return NumbersSuggestions(1, 2, 4, 8, 16);
      }

      return EmptySuggestion(textArea.Caret);
    }
예제 #3
0
		/// <summary>
		/// Creates a new SearchInputHandler and registers the search-related commands.
		/// </summary>
		public SearchInputHandler(TextArea textArea)
			: base(textArea)
		{
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, ExecuteFind));
			this.CommandBindings.Add(new CommandBinding(SearchCommands.FindNext, ExecuteFindNext));
			this.CommandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, ExecuteFindPrevious));
		}
		public void Dispose()
		{
			if (textArea != null) {
				FoldingManager.Uninstall(foldingManager);
				textArea = null;
			}
		}
예제 #5
0
 public IncrementalSearch(TextArea textArea, LogicalDirection direction)
 {
     if (textArea == null)
                         throw new ArgumentNullException("textArea");
                 this.textArea = textArea;
                 this.direction = direction;
 }
예제 #6
0
        /// <summary>
        /// Inserts the snippet into the text area.
        /// </summary>
        public void Insert(TextArea textArea)
        {
            if (textArea == null)
                throw new ArgumentNullException("textArea");

            ISegment selection = textArea.Selection.SurroundingSegment;
            int insertionPosition = textArea.Caret.Offset;

            if (selection != null) // if something is selected
                // use selection start instead of caret position,
                // because caret could be at end of selection or anywhere inside.
                // Removal of the selected text causes the caret position to be invalid.
                insertionPosition = selection.Offset + TextUtilities.GetWhitespaceAfter(textArea.Document, selection.Offset).Length;

            InsertionContext context = new InsertionContext(textArea, insertionPosition);

            using (context.Document.RunUpdate()) {
                if (selection != null)
                    textArea.Document.Remove(insertionPosition, selection.EndOffset - insertionPosition);
                Insert(context);

                // [DIGITALRUNE] Format inserted lines.
                int beginLine = textArea.Document.GetLineByOffset(context.StartPosition).LineNumber;
                int endLine = textArea.Document.GetLineByOffset(context.InsertionPosition).LineNumber;
                textArea.IndentationStrategy?.IndentLines(textArea, beginLine, endLine);

                context.RaiseInsertionCompleted(EventArgs.Empty);
            }
        }
		public void SetUpFixture()
		{
			string python = "class Test:\r\n" +
							"\tdef foo(self):\r\n" +
							"\t\tpass";
			
			DefaultProjectContent projectContent = new DefaultProjectContent();
			PythonParser parser = new PythonParser();
			compilationUnit = parser.Parse(projectContent, @"C:\test.py", python);			
			if (compilationUnit.Classes.Count > 0) {
				c = compilationUnit.Classes[0];
				if (c.Methods.Count > 0) {
					method = c.Methods[0];
				}
				
				TextArea textArea = new TextArea();
				document = new TextDocument();
				textArea.Document = document;
				textArea.Document.Text = python;
				
				ParserFoldingStrategy foldingStrategy = new ParserFoldingStrategy(textArea);
				
				ParseInformation parseInfo = new ParseInformation(compilationUnit);
				foldingStrategy.UpdateFoldings(parseInfo);
				List<FoldingSection> folds = new List<FoldingSection>(foldingStrategy.FoldingManager.AllFoldings);
				
				if (folds.Count > 0) {
					classFold = folds[0];
				}
				if (folds.Count > 1) {
					methodFold = folds[1];
				}
			}
		}
		public SharpDevelopCompletionWindow(ITextEditor editor, TextArea textArea, ICompletionItemList itemList) : base(textArea)
		{
			if (editor == null)
				throw new ArgumentNullException("editor");
			if (itemList == null)
				throw new ArgumentNullException("itemList");
			
			if (!itemList.ContainsAllAvailableItems) {
				// If more items are available (Ctrl+Space wasn't pressed), show this hint
				this.EmptyText = StringParser.Parse("${res:ICSharpCode.AvalonEdit.AddIn.SharpDevelopCompletionWindow.EmptyText}");
			}
			
			InitializeComponent();
			this.Editor = editor;
			this.itemList = itemList;
			ICompletionItem suggestedItem = itemList.SuggestedItem;
			foreach (ICompletionItem item in itemList.Items) {
				ICompletionData adapter = new CodeCompletionDataAdapter(this, item);
				this.CompletionList.CompletionData.Add(adapter);
				if (item == suggestedItem)
					this.CompletionList.SelectedItem = adapter;
			}
			this.StartOffset -= itemList.PreselectionLength;
			this.EndOffset += itemList.PostselectionLength;
		}
예제 #9
0
		public TextMarkerService(TextArea area)
		{
			this.area = area;
			markers = new TextSegmentCollection<TextMarker>(area.Document);
			this.area.TextView.BackgroundRenderers.Add(this);
			this.area.TextView.LineTransformers.Add(this);
		}
예제 #10
0
파일: CmdScreenMid.cs 프로젝트: voland/ViSD
 public void Execute(object arg)
 {
     ViSDGlobalCount.ResetAll();
                 ta = arg as TextArea;
                 int begin=-1;
                 int end=-1;
                 if ( ta!=null ){
                         double TopLine = ta.TextView.ScrollOffset.Y;
                         foreach( VisualLine vl in ta.TextView.VisualLines){
                                 if ( begin == -1 ){
                                         if ( vl.VisualTop>=TopLine) {
                                                 begin = vl.FirstDocumentLine.LineNumber;
                                         }
                                 } else{
                                         if (((vl.VisualTop +2*vl.Height)>=(TopLine+ta.TextView.ActualHeight))||
                                             ((vl.VisualTop +1*vl.Height)>=(ta.TextView.DocumentHeight))) {
                                                 end = vl.LastDocumentLine.LineNumber;
                                                 break;
                                         }
                                 }
                         }
                         if ( (begin >=0)&&( end >=0)){
                                 ta.Caret.Line = begin + (end - begin)/2;
                                 return;
                         }
                 }
 }
 public virtual void Complete(TextArea textArea, ISegment completionSegment,
     EventArgs insertionRequestEventArgs)
 {
   textArea.Document.Replace(completionSegment, Action == null ? this.Text : Action.Invoke());
   if (CaretOffset != 0)
     textArea.Caret.Offset += CaretOffset;
 }
		public void SetUpFixture()
		{
			string ruby = "class Test\r\n" +
							"\tdef initialize\r\n" +
							"\t\tputs 'test'\r\n" +
							"\tend\r\n" +
							"end";
			
			DefaultProjectContent projectContent = new DefaultProjectContent();
			RubyParser parser = new RubyParser();
			compilationUnit = parser.Parse(projectContent, @"C:\test.rb", ruby);			
			if (compilationUnit.Classes.Count > 0) {
				c = compilationUnit.Classes[0];
				if (c.Methods.Count > 0) {
					method = c.Methods[0];
				}
				
				TextArea textArea = new TextArea();
				document = new TextDocument();
				textArea.Document = document;
				textArea.Document.Text = ruby;
				
				// Get folds.
				ParserFoldingStrategy foldingStrategy = new ParserFoldingStrategy(textArea);
				
				ParseInformation parseInfo = new ParseInformation(compilationUnit);
				foldingStrategy.UpdateFoldings(parseInfo);
				List<FoldingSection> folds = new List<FoldingSection>(foldingStrategy.FoldingManager.AllFoldings);
			
				if (folds.Count > 1) {
					classFold = folds[0];
					methodFold = folds[1];
				}
			}
		}
예제 #13
0
		/// <inheritdoc/>
		public override void ReplaceSelectionWithText(TextArea textArea, string newText)
		{
			if (textArea == null)
				throw new ArgumentNullException("textArea");
			if (newText == null)
				throw new ArgumentNullException("newText");
			using (textArea.Document.RunUpdate()) {
				if (IsEmpty) {
					if (newText.Length > 0) {
						if (textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset)) {
							textArea.Document.Insert(textArea.Caret.Offset, newText);
						}
					}
				} else {
					ISegment[] segmentsToDelete = textArea.GetDeletableSegments(this);
					for (int i = segmentsToDelete.Length - 1; i >= 0; i--) {
						if (i == segmentsToDelete.Length - 1) {
							textArea.Caret.Offset = segmentsToDelete[i].EndOffset;
							textArea.Document.Replace(segmentsToDelete[i], newText);
						} else {
							textArea.Document.Remove(segmentsToDelete[i]);
						}
					}
					if (segmentsToDelete.Length != 0) {
						textArea.Selection = Selection.Empty;
					}
				}
			}
		}
예제 #14
0
 /// <summary>
 /// Creates a new SearchInputHandler and registers the search-related commands.
 /// </summary>
 public SearchInputHandler(TextArea textArea)
     : base(textArea)
 {
     RegisterCommands(this.CommandBindings);
     panel = new SearchPanel();
     panel.Attach(TextArea);
 }
예제 #15
0
		/// <summary>
		/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
		/// </summary>
		public static TextAreaInputHandler Create(TextArea textArea)
		{
			TextAreaInputHandler handler = new TextAreaInputHandler(textArea);
			handler.CommandBindings.AddRange(CommandBindings);
			handler.InputBindings.AddRange(InputBindings);
			return handler;
		}
        /// <summary>
        /// Creates a new code completion window.
        /// </summary>
        public PythonConsoleCompletionWindow(TextArea textArea, PythonTextEditor textEditor)
            : base(textArea)
        {
            // keep height automatic
            this.completionDataProvider = textEditor.CompletionProvider;
            this.textEditor = textEditor;
            this.CloseAutomatically = true;
            this.SizeToContent = SizeToContent.Height;
            this.MaxHeight = 300;
            this.Width = 175;
            this.Content = completionList;
            // prevent user from resizing window to 0x0
            this.MinHeight = 15;
            this.MinWidth = 30;

            toolTip.PlacementTarget = this;
            toolTip.Placement = PlacementMode.Right;
            toolTip.Closed += toolTip_Closed;

            completionList.InsertionRequested += completionList_InsertionRequested;
            completionList.SelectionChanged += completionList_SelectionChanged;
            AttachEvents();

            updateDescription = new DispatcherTimer();
            updateDescription.Tick += new EventHandler(completionList_UpdateDescription);
            updateDescriptionInterval = TimeSpan.FromSeconds(0.3);

            EventInfo eventInfo = typeof(TextView).GetEvent("ScrollOffsetChanged");
            Delegate methodDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, (this as CompletionWindowBase), "TextViewScrollOffsetChanged");
            eventInfo.RemoveEventHandler(this.TextArea.TextView, methodDelegate);
        }
예제 #17
0
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     if (m_jsonEditorViewModel.IsBetweenQoats)
       {
     int offset = m_jsonEditorViewModel.Caret.Offset;
     List<char> startChars = new List<char> {m_autoCompleteValue.SchemaObject.AutoCompletePathSeperator, '"'};
     if (m_autoCompleteValue.SchemaObject.Prefix.Length > 0)
       startChars.Add(m_autoCompleteValue.SchemaObject.Prefix.Last());
     int indexQuotStart = m_jsonEditorViewModel.TextDocument.Text.LastIndexOfAny(startChars.ToArray(), offset - 1, offset - 1) + 1;
     int indexQuatEnd = m_jsonEditorViewModel.TextDocument.Text.IndexOf('"', offset);
     int indexLineBreak = m_jsonEditorViewModel.TextDocument.Text.IndexOf('\n', offset);
     if (indexQuatEnd >= indexQuotStart && indexQuatEnd < indexLineBreak)
       completionSegment = new SelectionSegment(indexQuotStart, indexQuatEnd);
       }
       int endOffset = completionSegment.Offset + Text.Length;
       textArea.Document.Replace(completionSegment, (Text + m_autoCompleteValue.SchemaObject.Suffix).Replace("\\", "\\\\"));
       m_jsonEditorViewModel.Caret.Offset = endOffset;
       string value = m_autoCompleteValue.SchemaObject.RemovePrefixAndSuffix(m_jsonEditorViewModel.GetCurrentValue());
       if (Text.StartsWith(".." + m_autoCompleteValue.SchemaObject.AutoCompletePathSeperator) && value.Any(char.IsLetterOrDigit))
       {
     value = value.Substring(0, value.Length - 4);
     int startIndex = value.LastIndexOf(m_autoCompleteValue.SchemaObject.AutoCompletePathSeperator);
     if (startIndex == -1)
       startIndex = m_autoCompleteValue.SchemaObject.Prefix.Length;
     else
     {
       startIndex++;
     }
     m_jsonEditorViewModel.TextDocument.Replace(
       m_jsonEditorViewModel.Caret.Offset - 4 - (value.Length - startIndex), (value.Length - startIndex) + 4, "");
       }
       m_jsonEditorViewModel.UpdateAutoCompletList = true;
 }
예제 #18
0
        public CodeCompletionWindow(ITextEditor editor, TextArea textArea, ICompletionItemList itemList)
            : base(textArea)
        {
            if (editor == null)
                throw new ArgumentNullException("editor");
            if (itemList == null)
                throw new ArgumentNullException("itemList");

            if (!itemList.ContainsAllAvailableItems) {
                // If more items are available (Ctrl+Space wasn't pressed), show this hint
                this.EmptyText = "Press Ctrl+Space to show items from all namespaces";
            }

            //InitializeComponent();
            this.Editor = editor;
            this.itemList = itemList;
            ICompletionItem suggestedItem = itemList.SuggestedItem;
            foreach (ICompletionItem item in itemList.Items) {
                ICompletionData adapter = new CodeCompletionDataAdapter(this, item);
                this.CompletionList.CompletionData.Add(adapter);
                if (item == suggestedItem)
                    this.CompletionList.SelectedItem = adapter;
            }
            this.StartOffset -= itemList.PreselectionLength;
        }
예제 #19
0
파일: CmdPrevIdent.cs 프로젝트: voland/ViSD
        public void Execute(object arg)
        {
            ta = arg as TextArea;
                        int begin, end, caret;
                        if ( ta!=null){
                                if (CanExecute()){
                                        ViSDGlobalCount.UpdLastUsed( cmdf, ta );

                                        caret = ta.Caret.Offset;
                                        while( IsLetter( caret-1 )) caret--;
                                        begin = caret;
                                        while( IsLetter(caret+1)) caret++;
                                        end = caret;
                                        int lenght =  end - begin + 1;
                                        ViSDGlobalWordSearch.SearchedWord=ta.Document.GetText( begin, lenght);
                                        if ( begin>0)
                                                ta.Caret.Offset = begin-1;
                                        else
                                                ta.Caret.Offset = ta.Document.TextLength-1;
                                        cmdf.Execute(ta);
                                }else{
                                        ViSDGlobalCount.ResetAll();
                                }
                        }
        }
예제 #20
0
		public SelectionLayer(TextArea textArea) : base(textArea.TextView, KnownLayer.Selection)
		{
			this.IsHitTestVisible = false;
			
			this.textArea = textArea;
			TextViewWeakEventManager.VisualLinesChanged.AddListener(textView, this);
			TextViewWeakEventManager.ScrollOffsetChanged.AddListener(textView, this);
		}
예제 #21
0
		static double GetXPos(TextArea textArea, TextViewPosition pos)
		{
			DocumentLine documentLine = textArea.Document.GetLineByNumber(pos.Line);
			VisualLine visualLine = textArea.TextView.GetOrConstructVisualLine(documentLine);
			int vc = visualLine.ValidateVisualColumn(pos, true);
			TextLine textLine = visualLine.GetTextLine(vc);
			return visualLine.GetTextLineVisualXPosition(textLine, vc);
		}
예제 #22
0
 public AvalonEditorAdapter(TextArea textArea)
 {
     this.textArea = textArea;
     textArea.Caret.PositionChanged += OnCaretPositionChanged;
     textArea.PreviewKeyDown += OnTextAreaPreviewKeyDown;
     textArea.KeyDown += OnKeyDown;
     textArea.KeyUp += OnKeyUp;
 }
예제 #23
0
 public static bool SetCompositionFont(HwndSource source, IntPtr hIMC, TextArea textArea)
 {
     if (textArea == null)
         throw new ArgumentNullException("textArea");
     //			LOGFONT font = new LOGFONT();
     //			ImmGetCompositionFont(hIMC, out font);
     return false;
 }
        // [DIGITALRUNE]
        /// <summary>
        /// Gets the text used for indentation.
        /// </summary>
        /// <param name="textArea">The active <see cref="TextArea"/>.</param>
        /// <returns>The text used for indentation.</returns>
        public static string GetIndentationString(TextArea textArea)
        {
            if (textArea == null)
                throw new ArgumentNullException("textArea");

            var options = textArea.Options;
            return (options != null) ? options.IndentationString : "\t";
        }
예제 #25
0
		/// <summary>
		/// Creates a new SimpleSelection instance.
		/// </summary>
		internal SimpleSelection(TextArea textArea, TextViewPosition start, TextViewPosition end)
			: base(textArea)
		{
			this.start = start;
			this.end = end;
			this.startOffset = textArea.Document.GetOffset(start.Location);
			this.endOffset = textArea.Document.GetOffset(end.Location);
		}
예제 #26
0
		internal static Selection Create(TextArea textArea, TextViewPosition start, TextViewPosition end)
		{
			if (textArea == null)
				throw new ArgumentNullException("textArea");
			if (textArea.Document.GetOffset(start.Location) == textArea.Document.GetOffset(end.Location) && start.VisualColumn == end.VisualColumn)
				return textArea.emptySelection;
			else
				return new SimpleSelection(textArea, start, end);
		}
예제 #27
0
		public ImeSupport(TextArea textArea)
		{
			if (textArea == null)
				throw new ArgumentNullException("textArea");
			this.textArea = textArea;
			InputMethod.SetIsInputMethodSuspended(this.textArea, true);
			textArea.OptionChanged += TextAreaOptionChanged;
			currentContext = IntPtr.Zero;
		}
예제 #28
0
		public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
		{
			textArea.Document.Replace(completionSegment, Text);

			// Get the current line and try to suggest attributes
			DocumentLine currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
			string lineText = textArea.Document.GetText(currentLine.Offset, currentLine.Length);
			_completer.CompleteAttributeName(lineText, textArea.Caret.Offset - currentLine.Offset);
		}
예제 #29
0
		/// <summary>
		/// Creates a new TextAreaDefaultInputHandler instance.
		/// </summary>
		public TextAreaDefaultInputHandler(TextArea textArea) : base(textArea)
		{
			this.NestedInputHandlers.Add(CaretNavigation = CaretNavigationCommandHandler.Create(textArea));
			this.NestedInputHandlers.Add(Editing = EditingCommandHandler.Create(textArea));
			this.NestedInputHandlers.Add(MouseSelection = new SelectionMouseHandler(textArea));
			
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, ExecuteUndo, CanExecuteUndo));
			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, ExecuteRedo, CanExecuteRedo));
		}
 public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     StringBuilder stringBuilder = new StringBuilder();
       int stepB = m_schemaObject.GenerateMin(stringBuilder, m_jsonEditorViewModel.File.Path);
       textArea.Document.Replace(completionSegment, stringBuilder.ToString());
       m_jsonEditorViewModel.Caret.Offset -= stepB;
       m_jsonEditorViewModel.AutoCompleteSchemaObject = m_schemaObject;
       m_jsonEditorViewModel.UpdateAutoCompletList = true;
 }
예제 #31
0
        public void Complete(ICSharpCode.AvalonEdit.Editing.TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
        {
            var word = QueryComposerHelper.ExtractPreviousWord(textArea.Document.Text, completionSegment.EndOffset - 1);

            ISegment replaceSegment = completionSegment;

            if (stringval.Substring(0, word.Length) == word)
            {
                replaceSegment = new CustomSegment(completionSegment.EndOffset - word.Length, word.Length);
            }

            textArea.Document.Replace(replaceSegment, stringval);
        }
예제 #32
0
        private void codeEditor_TextEntered(object sender, TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                ICSharpCode.AvalonEdit.Editing.TextArea      area = (sender as ICSharpCode.AvalonEdit.Editing.TextArea);
                ICSharpCode.AvalonEdit.Document.TextDocument doc  = area.Document;
                int startoff = area.Caret.Offset - 1;
                int off      = area.Caret.Offset - 2;
                while (true)
                {
                    char o = doc.GetCharAt(off);
                    if (!char.IsLetter(o))
                    {
                        break;
                    }
                    if (off == 0)
                    {
                        break;
                    }
                    off--;
                }
                string prevToken = doc.GetText(off, startoff - off);

                // Open code completion after the user has pressed dot:
                completionWindow        = new CompletionWindow(CodeEditor.TextArea);
                completionWindow.Margin = new Thickness(0);
                IList <ICompletionData> data = completionWindow.CompletionList.CompletionData;
                try
                {
                    List <string> items = CompletionDatabase.completionDatabase[prevToken];
                    foreach (string item in items)
                    {
                        data.Add(new CompletionData(item));
                    }
                    completionWindow.Show();
                    completionWindow.Closed += delegate
                    {
                        completionWindow = null;
                    };
                }catch (Exception)
                {
                }
            }
        }
예제 #33
0
        public CompletionWindow(ICSharpCode.AvalonEdit.Editing.TextArea textAera, IEnumerable <ICompletionData> completionData)
            : base(textAera)
        {
            // オフセットを計算する
            //   既定の開始位置は前要素の境界位置
            //   既定の終了位置は次要素の境界位置
            var offset = textAera.Document.GetOffset(textAera.Caret.Line, textAera.Caret.Column);
            var start  = TextUtilities.GetNextCaretPosition(textAera.Document, offset, LogicalDirection.Backward, CaretPositioningMode.WordBorderOrSymbol);
            var end    = TextUtilities.GetNextCaretPosition(textAera.Document, start, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol);

            if (start < 0 || end < 0)
            {
                // 一方がテキストの端に到達している場合
                if (offset <= 0)
                {
                    // 開始位置がテキストの先端である場合
                    //   開始位置: 現在位置
                    //   終了位置: 次要素との境界位置
                    start = offset;
                    end   = TextUtilities.GetNextCaretPosition(textAera.Document, start, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol);

                    // 終了位置がテキストの終端に到達した、または次要素が空白で構成される場合
                    //   終了位置: 開始位置と同値
                    if (end < 0 || string.IsNullOrWhiteSpace(textAera.Document.GetText(start, end - start)))
                    {
                        end = offset;
                    }
                }
                else
                {
                    // 終了位置がテキストの終端である場合
                    //   開始位置: 現在位置
                    //   終了位置: 現在位置
                    start = offset;
                    end   = offset;
                }
            }
            else if (start + 1 == end && end == offset && TextUtilities.GetCharacterClass(textAera.Document.GetText(start, 1).First()) == CharacterClass.Other)
            {
                // 前要素が記号で構成される場合
                //   開始位置: 現在位置
                //   終了位置: 次要素との境界位置
                start = offset;
                end   = TextUtilities.GetNextCaretPosition(textAera.Document, start, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol);

                // 終了位置がテキストの終端に到達している、または次要素が空白で構成される場合
                //   終了位置: 現在位置
                if (end < 0 || string.IsNullOrWhiteSpace(textAera.Document.GetText(start, end - start)))
                {
                    end = offset;
                }
            }
            else if (string.IsNullOrWhiteSpace(textAera.Document.GetText(start, end - start)))
            {
                // 次要素が空白で構成される場合
                //   開始位置: 現在位置
                //   終了位置: 現在位置
                start = offset;
                end   = offset;
            }

            // オフセットを設定する
            this.StartOffset = start;
            this.EndOffset   = end;

            // キーワードリストを設定する
            completionData.ForEach(data => this.CompletionList.CompletionData.Add(data));
            this.CompletionList.SelectItem(start < end ? textAera.Document.GetText(start, end - start) : string.Empty);
            if (this.CompletionList.ListBox.ItemsSource.OfType <ICompletionData>().Any() == false)
            {
                this.CompletionList.SelectItem(string.Empty);
            }

            // プロパティを設定する
            this.CloseWhenCaretAtBeginning = true;

            // イベントを購読する
            this.TextArea.TextEntering          += this.TextArea_TextEntering;
            this.TextArea.TextEntered           += this.TextArea_TextEntered;
            this.TextArea.Caret.PositionChanged += this.Caret_PositionChanged;
        }
예제 #34
0
 public virtual void Complete(ICSharpCode.AvalonEdit.Editing.TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
 {
     textArea.Document.Replace(completionSegment, this.CompletionText);
 }
예제 #35
0
파일: CaretLayer.cs 프로젝트: dnGrep/dnGrep
 public CaretLayer(TextArea textArea) : base(textArea.TextView, KnownLayer.Caret)
 {
     this.textArea         = textArea;
     this.IsHitTestVisible = false;
     caretBlinkTimer.Tick += new EventHandler(caretBlinkTimer_Tick);
 }
        public override void Complete(ICSharpCode.AvalonEdit.Editing.TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs)
        {
            if (declarationBegin > completionSegment.Offset)
            {
                base.Complete(textArea, completionSegment, insertionRequestEventArgs);
                return;
            }
            TypeSystemAstBuilder b = new TypeSystemAstBuilder(new CSharpResolver(contextAtCaret));

            b.ShowTypeParameterConstraints = false;
            b.GenerateBody = true;

            var entityDeclaration = b.ConvertEntity(this.Entity);

            entityDeclaration.Modifiers &= ~(Modifiers.Virtual | Modifiers.Abstract);
            entityDeclaration.Modifiers |= Modifiers.Override;

            if (!this.Entity.IsAbstract)
            {
                // modify body to call the base method
                if (this.Entity.EntityType == EntityType.Method)
                {
                    var baseCall = new BaseReferenceExpression().Invoke(this.Entity.Name, ParametersToExpressions(this.Entity));
                    var body     = entityDeclaration.GetChildByRole(Roles.Body);
                    body.Statements.Clear();
                    if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void))
                    {
                        body.Statements.Add(new ExpressionStatement(baseCall));
                    }
                    else
                    {
                        body.Statements.Add(new ReturnStatement(baseCall));
                    }
                }
                else if (this.Entity.EntityType == EntityType.Indexer || this.Entity.EntityType == EntityType.Property)
                {
                    Expression baseCall;
                    if (this.Entity.EntityType == EntityType.Indexer)
                    {
                        baseCall = new BaseReferenceExpression().Indexer(ParametersToExpressions(this.Entity));
                    }
                    else
                    {
                        baseCall = new BaseReferenceExpression().Member(this.Entity.Name);
                    }
                    var getterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.GetterRole).Body;
                    if (!getterBody.IsNull)
                    {
                        getterBody.Statements.Clear();
                        getterBody.Add(new ReturnStatement(baseCall.Clone()));
                    }
                    var setterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.SetterRole).Body;
                    if (!setterBody.IsNull)
                    {
                        setterBody.Statements.Clear();
                        setterBody.Add(new AssignmentExpression(baseCall.Clone(), new IdentifierExpression("value")));
                    }
                }
            }

            var          document          = textArea.Document;
            StringWriter w                 = new StringWriter();
            var          formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();
            var          segmentDict       = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, textArea.Options);

            string newText = w.ToString().TrimEnd();

            document.Replace(declarationBegin, completionSegment.EndOffset - declarationBegin, newText);
            var throwStatement = entityDeclaration.Descendants.FirstOrDefault(n => n is ThrowStatement);

            if (throwStatement != null)
            {
                var segment = segmentDict[throwStatement];
                textArea.Selection = new RectangleSelection(textArea, new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset)), new TextViewPosition(textArea.Document.GetLocation(declarationBegin + segment.Offset + segment.Length)));
            }
            CSharpFormatter.Format(textArea.Document, declarationBegin, newText.Length, formattingOptions);
        }
예제 #37
0
 public EmptySelection(TextArea textArea) : base(textArea)
 {
 }