Insert() public method

public Insert ( int offset, string value ) : int
offset int
value string
return int
		static void TestInsertionPoints (string text)
		{
			TextEditorData data = new TextEditorData ();
			List<InsertionPoint> loc = new List<InsertionPoint> ();
			for (int i = 0; i < text.Length; i++) {
				char ch = text[i];
				if (ch == '@') {
					i++;
					ch = text[i];
					loc.Add (new InsertionPoint (data.Document.OffsetToLocation (data.Document.Length), ch == '3' || ch == '2', ch == '3' || ch == '1'));
				} else {
					data.Insert (data.Document.Length, ch.ToString ());
				}
			}
			var parseResult = new NRefactoryParser ().Parse (null, "a.cs", data.Document.Text);
			
			var foundPoints = HelperMethods.GetInsertionPoints (data.Document, parseResult.CompilationUnit.Types[0]);
			Assert.AreEqual (loc.Count, foundPoints.Count, "point count doesn't match");
			for (int i = 0; i < loc.Count; i++) {
				Console.WriteLine (loc[i] + "/" + foundPoints[i]);
				Assert.AreEqual (loc[i].Location, foundPoints[i].Location, "point " + i + " doesn't match");
				Assert.AreEqual (loc[i].ShouldInsertNewLineAfter, foundPoints[i].ShouldInsertNewLineAfter, "point " + i + " ShouldInsertNewLineAfter doesn't match");
				Assert.AreEqual (loc[i].ShouldInsertNewLineBefore, foundPoints[i].ShouldInsertNewLineBefore, "point " + i + " ShouldInsertNewLineBefore doesn't match");
			}
		}
        public override void AddGlobalNamespaceImport(RefactorerContext ctx, string fileName, string nsName)
        {
            IEditableTextFile file        = ctx.GetFile(fileName);
            int            pos            = 0;
            ParsedDocument parsedDocument = parser.Parse(ctx.ParserContext, fileName, file.Text);
            StringBuilder  text           = new StringBuilder();

            if (parsedDocument.CompilationUnit != null)
            {
                IUsing lastUsing = null;
                foreach (IUsing u in parsedDocument.CompilationUnit.Usings)
                {
                    if (u.IsFromNamespace)
                    {
                        break;
                    }
                    lastUsing = u;
                }

                if (lastUsing != null)
                {
                    pos = file.GetPositionFromLineColumn(lastUsing.Region.End.Line, lastUsing.Region.End.Column);
                }
            }

            if (pos != 0)
            {
                text.AppendLine();
            }
            text.Append("using ");
            text.Append(nsName);
            text.Append(";");
            if (file is Mono.TextEditor.ITextEditorDataProvider)
            {
                Mono.TextEditor.TextEditorData data = ((Mono.TextEditor.ITextEditorDataProvider)file).GetTextEditorData();
                if (pos == 0)
                {
                    text.Append(data.EolMarker);
                }
                int caretOffset   = data.Caret.Offset;
                int insertedChars = data.Insert(pos, text.ToString());
                if (pos < caretOffset)
                {
                    data.Caret.Offset = caretOffset + insertedChars;
                }
            }
            else
            {
                if (pos == 0)
                {
                    text.AppendLine();
                }
                file.InsertText(pos, text.ToString());
            }
        }
		public override void HandleSpecialSelectionKey (TextEditorData textEditorData,uint unicodeKey)
		{
			string start, end;
			GetSelectionSurroundings (textEditorData, unicodeKey, out start, out end);
			var selection = textEditorData.MainSelection;

			if (textEditorData.MainSelection.SelectionMode == SelectionMode.Block) {
				int startCol = System.Math.Min (selection.Anchor.Column, selection.Lead.Column) - 1;
				int endCol = System.Math.Max (selection.Anchor.Column, selection.Lead.Column);
				for (int lineNumber = selection.MinLine; lineNumber <= selection.MaxLine; lineNumber++) {
					DocumentLine lineSegment = textEditorData.GetLine (lineNumber);

					if (lineSegment.Offset + startCol < lineSegment.EndOffset)
						textEditorData.Insert (lineSegment.Offset + startCol, start);
					if (lineSegment.Offset + endCol < lineSegment.EndOffset)
						textEditorData.Insert (lineSegment.Offset + endCol, end);
				}

				textEditorData.MainSelection = new Selection (
					new DocumentLocation (selection.Anchor.Line, endCol == selection.Anchor.Column ? endCol + start.Length : startCol + 1 + start.Length),
					new DocumentLocation (selection.Lead.Line, endCol == selection.Anchor.Column ? startCol + 1 + start.Length : endCol + start.Length),
					Mono.TextEditor.SelectionMode.Block);
				textEditorData.Document.CommitMultipleLineUpdate (textEditorData.MainSelection.MinLine, textEditorData.MainSelection.MaxLine);
			} else {
				int anchorOffset = selection.GetAnchorOffset (textEditorData);
				int leadOffset = selection.GetLeadOffset (textEditorData);
				if (leadOffset < anchorOffset) {
					int tmp = anchorOffset;
					anchorOffset = leadOffset;
					leadOffset = tmp;
				}
				textEditorData.Insert (anchorOffset, start);
				textEditorData.Insert (leadOffset >= anchorOffset ? leadOffset + start.Length : leadOffset, end);
			//	textEditorData.SetSelection (anchorOffset + start.Length, leadOffset + start.Length);
				if (CSharpTextEditorIndentation.OnTheFlyFormatting) {
					var l1 = textEditorData.GetLineByOffset (anchorOffset);
					var l2 = textEditorData.GetLineByOffset (leadOffset);
					OnTheFlyFormatter.Format (document, l1.Offset, l2.EndOffsetIncludingDelimiter);
				}
			}
		}
		public void InsertNewLine (TextEditorData editor, NewLineInsertion insertion, ref int offset)
		{
			string str = null;
			switch (insertion) {
			case NewLineInsertion.Eol:
				str = editor.EolMarker;
				break;
			case NewLineInsertion.BlankLine:
				str = editor.EolMarker + editor.EolMarker;
				break;
			default:
				return;
			}
			
			offset += editor.Insert (offset, str);
		}
		static int PastePlainText (TextEditorData data, int offset, string text, bool preserveSelection = false)
		{
			int inserted = 0;
			using (var undo = data.OpenUndoGroup ()) {
				var version = data.Document.Version;
				if (!preserveSelection)
					data.DeleteSelectedText (!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
				data.EnsureCaretIsNotVirtual ();
				if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block) {
					var selection = data.MainSelection;
					var visualInsertLocation = data.LogicalToVisualLocation (selection.Anchor);
					for (int lineNumber = selection.MinLine; lineNumber <= selection.MaxLine; lineNumber++) {
						var lineSegment = data.GetLine (lineNumber);
						int insertOffset = lineSegment.GetLogicalColumn (data, visualInsertLocation.Column) - 1;
						string textToInsert;
						if (lineSegment.Length < insertOffset) {
							int visualLastColumn = lineSegment.GetVisualColumn (data, lineSegment.Length + 1);
							int charsToInsert = visualInsertLocation.Column - visualLastColumn;
							int spaceCount = charsToInsert % data.Options.TabSize;
							textToInsert = new string ('\t', (charsToInsert - spaceCount) / data.Options.TabSize) + new string (' ', spaceCount) + text;
							insertOffset = lineSegment.Length;
						} else {
							textToInsert = text;
						}
						inserted = data.Insert (lineSegment.Offset + insertOffset, textToInsert);
					}
				} else {
					offset = version.MoveOffsetTo (data.Document.Version, offset);
					inserted = data.PasteText (offset, text);
				}
			}
			return inserted;
		}
		/// <summary>
		/// Transpose characters (Emacs C-t)
		/// </summary>
		public static void TransposeCharacters (TextEditorData data)
		{
			if (data.Caret.Offset == 0)
				return;
			DocumentLine line = data.Document.GetLine (data.Caret.Line);
			if (line == null)
				return;
			int transposeOffset = data.Caret.Offset - 1;
			char ch;
			if (data.Caret.Column == 0) {
				DocumentLine lineAbove = data.Document.GetLine (data.Caret.Line - 1);
				if (lineAbove.Length == 0 && line.Length == 0) 
					return;
				
				if (line.Length != 0) {
					ch = data.Document.GetCharAt (data.Caret.Offset);
					data.Remove (data.Caret.Offset, 1);
					data.Insert (lineAbove.Offset + lineAbove.Length, ch.ToString ());
					data.Document.CommitLineUpdate (data.Caret.Line - 1);
					return;
				}
				
				int lastCharOffset = lineAbove.Offset + lineAbove.Length - 1;
				ch = data.Document.GetCharAt (lastCharOffset);
				data.Remove (lastCharOffset, 1);
				data.InsertAtCaret (ch.ToString ());
				return;
			}
			
			int offset = data.Caret.Offset;
			if (data.Caret.Column >= line.Length + 1) {
				offset = line.Offset + line.Length - 1;
				transposeOffset = offset - 1;
				// case one char in line:
				if (transposeOffset < line.Offset) {
					DocumentLine lineAbove = data.Document.GetLine (data.Caret.Line - 1);
					transposeOffset = lineAbove.Offset + lineAbove.Length;
					ch = data.Document.GetCharAt (offset);
					data.Remove (offset, 1);
					data.Insert (transposeOffset, ch.ToString ());
					data.Caret.Offset = line.Offset;
					data.Document.CommitLineUpdate (data.Caret.Line - 1);
					return;
				}
			}
			
			ch = data.Document.GetCharAt (offset);
			data.Replace (offset, 1, data.Document.GetCharAt (transposeOffset).ToString ());
			data.Replace (transposeOffset, 1, ch.ToString ());
			if (data.Caret.Column < line.Length + 1)
				data.Caret.Offset = offset + 1;
		}
		public static void IndentSelection (TextEditorData data)
		{
			if (!data.IsSomethingSelected)
				return;
			int startLineNr, endLineNr;
			GetSelectedLines (data, out startLineNr, out endLineNr);
			var anchor = data.MainSelection.Anchor;
			var lead = data.MainSelection.Lead;
			var indentationString = data.Options.IndentationString;
			using (var undo = data.OpenUndoGroup (OperationType.Format)) {
				foreach (DocumentLine line in data.SelectedLines) {
					if (data.Options.IndentStyle == IndentStyle.Virtual && line.Length == 0)
						continue;
					data.Insert (line.Offset, indentationString);
				}
			}
			int chars = indentationString.Length;
			var leadCol = lead.Column > 1 || lead < anchor ? lead.Column + chars : 1;
			var anchorCol = anchor.Column > 1 || anchor < lead ? anchor.Column + chars : 1;
			data.SetSelection (anchor.Line, anchorCol, lead.Line, leadCol);
			data.Document.RequestUpdate (new MultipleLineUpdate (startLineNr, endLineNr));
			data.Document.CommitDocumentUpdate ();
		}
		public static void MoveBlockDown (TextEditorData data)
		{
			int lineStart = data.Caret.Line;
			int lineEnd = data.Caret.Line;
			bool setSelection = lineStart != lineEnd;
			if (data.IsSomethingSelected) {
				setSelection = true;
				lineStart = data.MainSelection.MinLine;
				lineEnd = data.MainSelection.MaxLine;
			}
			
			if (lineEnd + 1 >= data.Document.LineCount)
				return;
			
			Mono.TextEditor.LineSegment startLine = data.Document.GetLine (lineStart);
			Mono.TextEditor.LineSegment endLine = data.Document.GetLine (lineEnd);
			Mono.TextEditor.LineSegment nextLine = data.Document.GetLine (lineEnd + 1);
			int relCaretOffset = data.Caret.Offset - startLine.Offset;
			data.Document.BeginAtomicUndo ();
			string text = data.Document.GetTextBetween (startLine.Offset, endLine.EndOffset);
			
			int nextLineOffset = nextLine.EndOffset;
			int delta = endLine.EndOffset - startLine.Offset;
			int newStartOffset = nextLineOffset - delta;
			
			// handle the last line case
			if (nextLine.DelimiterLength == 0) {
				text = data.EolMarker + text.Substring (0, text.Length - endLine.DelimiterLength);
				newStartOffset += data.EolMarker.Length;
			}
			data.Insert (nextLineOffset, text);
			data.Remove (startLine.Offset, delta);
			
			// move markers
			List<TextMarker> markers = new List<TextMarker> (nextLine.Markers);
			nextLine.ClearMarker ();
			for (int i = lineEnd; i <= lineStart; i++) {
				foreach (TextMarker marker in data.Document.GetLine (i).Markers) {
					data.Document.GetLine (i + 1).AddMarker (marker);
				}
				data.Document.GetLine (i).ClearMarker ();
			}
			markers.ForEach (m => startLine.AddMarker (m));

			
			data.Caret.Offset = newStartOffset + relCaretOffset;
			if (setSelection)
				data.SetSelection (newStartOffset, newStartOffset + text.Length - endLine.DelimiterLength);
			data.Document.EndAtomicUndo ();
		}
		public static void InsertNewLine (TextEditorData data)
		{
			if (!data.CanEditSelection)
				return;
			
			using (var undo = data.OpenUndoGroup ()) {
				if (data.IsSomethingSelected) {
					var end = data.MainSelection.End;
					data.DeleteSelectedText ();
					if (end.Column == 1) {
						CaretMoveActions.InternalCaretMoveHome (data, true, false);
						return;
					}
				}
				switch (data.Options.IndentStyle) {
				case IndentStyle.None:
					data.InsertAtCaret (data.EolMarker);
					break;
				case IndentStyle.Auto:
					data.EnsureCaretIsNotVirtual ();
					var indent = data.Document.GetLineIndent (data.Caret.Line);
					data.InsertAtCaret (data.EolMarker);
					data.EnsureCaretIsNotVirtual ();
					if (data.GetLine (data.Caret.Line).Length == 0)
						data.InsertAtCaret (indent);
					break;
				case IndentStyle.Smart:
					if (!data.HasIndentationTracker)
						goto case IndentStyle.Auto;
					NewLineSmartIndent (data);
					break;
				case IndentStyle.Virtual:
					if (!data.HasIndentationTracker)
						goto case IndentStyle.Auto;
					var oldLine = data.Caret.Line;
					var curLine = data.GetLine (oldLine);
					var indentCol = data.GetVirtualIndentationColumn (data.Caret.Location);
					if (curLine.Length >= data.Caret.Column) {
						NewLineSmartIndent (data);
						data.FixVirtualIndentation ();
						data.FixVirtualIndentation (oldLine);
						break;
					}
					data.Insert (data.Caret.Offset, data.EolMarker);
					data.FixVirtualIndentation (oldLine);
					data.Caret.Column = indentCol;
					break;
				default:
					throw new ArgumentOutOfRangeException ();
				}
			}
		}
		public static void DuplicateLine (TextEditorData data)
		{
			DocumentLine line = data.Document.GetLine (data.Caret.Line);
			if (line == null)
				return;
			data.Insert (line.Offset, data.GetTextAt (line.SegmentIncludingDelimiter));
		}
Example #11
0
        protected void InsertCharacter(uint unicodeKey)
        {
            if (!textEditorData.CanEdit(Data.Caret.Line))
            {
                return;
            }

            HideMouseCursor();
            Document.BeginAtomicUndo();
            textEditorData.DeleteSelectedText(textEditorData.IsSomethingSelected ? textEditorData.MainSelection.SelectionMode != SelectionMode.Block : true);

            char ch = (char)unicodeKey;

            if (!char.IsControl(ch) && textEditorData.CanEdit(Caret.Line))
            {
                LineSegment line = Document.GetLine(Caret.Line);
                if (Caret.IsInInsertMode || Caret.Column >= line.EditableLength + 1)
                {
                    string text = Caret.Column > line.EditableLength + 1 ? textEditorData.GetVirtualSpaces(Caret.Line, Caret.Column) + ch.ToString() : ch.ToString();
                    if (textEditorData.IsSomethingSelected && textEditorData.MainSelection.SelectionMode == SelectionMode.Block)
                    {
                        int length = 0;
                        var visualInsertLocation = editor.LogicalToVisualLocation(Caret.Location);
                        for (int lineNumber = textEditorData.MainSelection.MinLine; lineNumber <= textEditorData.MainSelection.MaxLine; lineNumber++)
                        {
                            LineSegment lineSegment  = textEditorData.GetLine(lineNumber);
                            int         insertOffset = lineSegment.GetLogicalColumn(textEditorData, visualInsertLocation.Column) - 1;
                            string      textToInsert;
                            if (lineSegment.EditableLength < insertOffset)
                            {
                                int visualLastColumn = lineSegment.GetVisualColumn(textEditorData, lineSegment.EditableLength + 1);
                                int charsToInsert    = visualInsertLocation.Column - visualLastColumn;
                                int spaceCount       = charsToInsert % editor.Options.TabSize;
                                textToInsert = new string ('\t', (charsToInsert - spaceCount) / editor.Options.TabSize) + new string (' ', spaceCount) + text;
                                insertOffset = lineSegment.EditableLength;
                            }
                            else
                            {
                                textToInsert = text;
                            }
                            length = textEditorData.Insert(lineSegment.Offset + insertOffset, textToInsert);
                        }
                        Caret.PreserveSelection = true;
                        Caret.Column           += length - 1;

                        textEditorData.MainSelection.Lead   = new DocumentLocation(textEditorData.MainSelection.Lead.Line, Caret.Column + 1);
                        textEditorData.MainSelection.Anchor = new DocumentLocation(textEditorData.MainSelection.Anchor.Line, Caret.Column + 1);
                        Document.CommitMultipleLineUpdate(textEditorData.MainSelection.MinLine, textEditorData.MainSelection.MaxLine);
                    }
                    else
                    {
                        int length = textEditorData.Insert(Caret.Offset, text);
                        Caret.Column += length - 1;
                    }
                }
                else
                {
                    int length = textEditorData.Replace(Caret.Offset, 1, ch.ToString());
                    if (length > 1)
                    {
                        Caret.Offset += length - 1;
                    }
                }
                // That causes unnecessary redraws:
                //				bool autoScroll = Caret.AutoScrollToCaret;
                Caret.Column++;
                if (Caret.PreserveSelection)
                {
                    Caret.PreserveSelection = false;
                }
                //				Caret.AutoScrollToCaret = autoScroll;
                //				if (autoScroll)
                //					Editor.ScrollToCaret ();
                //				Document.RequestUpdate (new LineUpdate (Caret.Line));
                //				Document.CommitDocumentUpdate ();
            }
            Document.EndAtomicUndo();
            Document.OptimizeTypedUndo();
        }
Example #12
0
		public static void IndentSelection (TextEditorData data)
		{
			if (!data.IsSomethingSelected)
				return;
			int startLineNr, endLineNr;
			GetSelectedLines (data, out startLineNr, out endLineNr);
			var anchor = data.MainSelection.Anchor;
			var lead = data.MainSelection.Lead;
			using (var undo = data.OpenUndoGroup ()) {
				foreach (DocumentLine line in data.SelectedLines) {
					data.Insert (line.Offset, data.Options.IndentationString);
				}
			}
			var leadCol = lead.Column > 1 || lead < anchor ? lead.Column + 1 : 1;
			var anchorCol = anchor.Column > 1 || anchor < lead ? anchor.Column + 1 : 1;
			data.SetSelection (anchor.Line, anchorCol, lead.Line, leadCol);
			data.Document.RequestUpdate (new MultipleLineUpdate (startLineNr, endLineNr));
			data.Document.CommitDocumentUpdate ();
		}
Example #13
0
		public static void InsertNewLine (TextEditorData data)
		{
			if (!data.CanEditSelection)
				return;
			
			data.Document.BeginAtomicUndo ();
			if (data.IsSomethingSelected)
				data.DeleteSelectedText ();
			
			data.EnsureCaretIsNotVirtual ();
			StringBuilder sb = new StringBuilder (data.EolMarker);
			if (data.Options.AutoIndent)
				sb.Append (data.Document.GetLineIndent (data.Caret.Line));
			int offset = data.Caret.Offset;
			data.Insert (offset, sb.ToString ());
			data.Caret.Offset = offset + sb.Length;
			data.Document.EndAtomicUndo ();
		}
Example #14
0
		public static void InsertTab (TextEditorData data)
		{
			if (!data.CanEditSelection)
				return;
			
			if (data.IsMultiLineSelection) {
				IndentSelection (data);
				return;
			}
			data.Document.BeginAtomicUndo ();
			if (data.IsSomethingSelected) {
				data.DeleteSelectedText ();
			}
			string indentationString = "\t";
			bool convertTabToSpaces = data.Options.TabsToSpaces;
			
			if (!convertTabToSpaces && !data.Options.AllowTabsAfterNonTabs) {
				for (int i = 1; i < data.Caret.Column; i++) {
					if (data.Document.GetCharAt (data.Caret.Offset - i) != '\t') {
						convertTabToSpaces = true;
						break;
					}
				}
			}
			
			if (convertTabToSpaces) {
				DocumentLocation visualLocation = data.Document.LogicalToVisualLocation (data, data.Caret.Location);
				int tabWidth = TextViewMargin.GetNextTabstop (data, visualLocation.Column) - visualLocation.Column;
				indentationString = new string (' ', tabWidth);
			}
			int length = data.Insert (data.Caret.Offset, indentationString);
			data.Caret.Column += length;
			data.Document.EndAtomicUndo ();
		}
Example #15
0
		public static void IndentSelection (TextEditorData data)
		{
			int startLineNr, endLineNr;
			GetSelectedLines (data, out startLineNr, out endLineNr);
			
			data.Document.BeginAtomicUndo ();
			foreach (LineSegment line in data.SelectedLines) {
				data.Insert (line.Offset, data.Options.IndentationString);
			}
			if (data.IsSomethingSelected) 
				SelectLineBlock (data, endLineNr, startLineNr);
			
			if (data.Caret.Column != 0) {
				data.Caret.PreserveSelection = true;
				data.Caret.Column++;
				data.Caret.PreserveSelection = false;
			}
			
			data.Document.EndAtomicUndo ();
			data.Document.RequestUpdate (new MultipleLineUpdate (startLineNr, endLineNr));
			data.Document.CommitDocumentUpdate ();
		}
Example #16
0
		public static void InsertTab (TextEditorData data)
		{
			if (!data.CanEditSelection)
				return;
			if (data.IsMultiLineSelection && data.MainSelection.SelectionMode != SelectionMode.Block) {
				IndentSelection (data);
				return;
			}
			using (var undo = data.OpenUndoGroup ()) {
				string indentationString = "\t";
				bool convertTabToSpaces = data.Options.TabsToSpaces;
				
				if (!convertTabToSpaces && !data.Options.AllowTabsAfterNonTabs) {
					for (int i = 1; i < data.Caret.Column; i++) {
						if (data.Document.GetCharAt (data.Caret.Offset - i) != '\t') {
							convertTabToSpaces = true;
							break;
						}
					}
				}
					
				if (convertTabToSpaces) {
					DocumentLocation visualLocation = data.LogicalToVisualLocation (data.Caret.Location);
					int tabWidth = TextViewMargin.GetNextTabstop (data, visualLocation.Column) - visualLocation.Column;
					indentationString = new string (' ', tabWidth);
				}
				if (data.IsMultiLineSelection && data.MainSelection.SelectionMode == SelectionMode.Block) {
					data.InsertAtCaret (indentationString);
				} else {
					if (data.IsSomethingSelected)
						data.DeleteSelectedText ();
					data.Insert (data.Caret.Offset, indentationString);
				}
			}
		}
		static void TestInsertionPoints (string text)
		{
			TextEditorData data = new TextEditorData ();
			List<InsertionPoint> loc = new List<InsertionPoint> ();
			for (int i = 0; i < text.Length; i++) {
				char ch = text[i];
				if (ch == '@') {
					i++;
					ch = text[i];
					NewLineInsertion insertBefore = NewLineInsertion.None;
					NewLineInsertion insertAfter  = NewLineInsertion.None;
					
					switch (ch) {
					case 'n':
						break;
					case 'd':
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'D':
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'u':
						insertBefore = NewLineInsertion.Eol;
						break;
					case 'U':
						insertBefore = NewLineInsertion.BlankLine;
						break;
					case 's':
						insertBefore = insertAfter = NewLineInsertion.Eol;
						break;
					case 'S':
						insertBefore = insertAfter = NewLineInsertion.BlankLine;
						break;
						
					case 't':
						insertBefore = NewLineInsertion.Eol;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'v':
						insertBefore = NewLineInsertion.BlankLine;
						insertAfter = NewLineInsertion.Eol;
						break;
					default:
						Assert.Fail ("unknown insertion point:" + ch);
						break;
					}
					loc.Add (new InsertionPoint (data.Document.OffsetToLocation (data.Document.Length), insertBefore, insertAfter));
				} else {
					data.Insert (data.Document.Length, ch.ToString ());
				}
			}
			
			var parseResult = new NRefactoryParser ().Parse (null, "a.cs", data.Document.Text);
			
			var foundPoints = HelperMethods.GetInsertionPoints (data.Document, parseResult.CompilationUnit.Types[0]);
			Assert.AreEqual (loc.Count, foundPoints.Count, "point count doesn't match");
			for (int i = 0; i < loc.Count; i++) {
				Console.WriteLine (loc[i] + "/" + foundPoints[i]);
				Assert.AreEqual (loc[i].Location, foundPoints[i].Location, "point " + i + " doesn't match");
				Assert.AreEqual (loc[i].LineAfter, foundPoints[i].LineAfter, "point " + i + " ShouldInsertNewLineAfter doesn't match");
				Assert.AreEqual (loc[i].LineBefore, foundPoints[i].LineBefore, "point " + i + " ShouldInsertNewLineBefore doesn't match");
			}
		}
Example #18
0
		static void InsertFormattedText (TextEditorData data, int offset, string formattedText)
		{
			data.Document.BeginAtomicUndo ();
			//			DocumentLocation caretLocation = data.Caret.Location;
			
			int selAnchor = data.IsSomethingSelected ? data.Document.LocationToOffset (data.MainSelection.Anchor) : -1;
			int selLead = data.IsSomethingSelected ? data.Document.LocationToOffset (data.MainSelection.Lead) : -1;
			int textOffset = 0;
			int caretOffset = data.Caret.Offset;
			
//			Console.WriteLine ("formattedText3:" + formattedText.Replace ("\t", "->").Replace (" ", "°").Replace ("\n", "\\n").Replace ("\r", "\\r"));
			while (textOffset < formattedText.Length /*&& offset < caretOffset*/) {
				if (offset < 0) {
					offset++;
					textOffset++;
					continue;
				}
				char ch1 = data.Document.GetCharAt (offset);
				char ch2 = formattedText[textOffset];
				bool isCh1Eol = ch1 == '\n'|| ch1 == '\r';
				
				if (ch1 == '\r' && offset + 1 < data.Document.Length && data.Document.GetCharAt (offset + 1) == '\n')  {
					offset++;
					ch1 = '\n';
				}
				
				if (ch1 == ch2 || (ch2 == '\n' && isCh1Eol)) {
					textOffset++;
					offset++;
					continue;
				} else if (isCh1Eol) {
					
				//	int firstWhitespace = 0;
					
					 // skip all white spaces in formatted text - we had a line break
					int firstWhitespace = -1;
					while (textOffset < formattedText.Length && IsPlainWhitespace (formattedText[textOffset])) {
						if (firstWhitespace < 0)
							firstWhitespace = textOffset;
						textOffset++;
					}
					if (firstWhitespace >= 0 && firstWhitespace != textOffset && formattedText[textOffset] == '\n') {
						int length = textOffset - firstWhitespace - 1;
						data.Insert (offset, formattedText.Substring (firstWhitespace, length) + data.EolMarker);
						data.Document.CommitLineUpdate (data.Document.OffsetToLineNumber (offset));
						length += data.EolMarker.Length;
						if (offset < caretOffset)
							caretOffset += length;
						if (offset < selAnchor)
							selAnchor += length;
						if (offset < selLead)
							selLead += length;
						
						offset += length - 1;
						textOffset++;
					}
					
					offset++;
					while (offset < data.Caret.Offset && IsPlainWhitespace (data.Document.GetCharAt (offset))) {
						offset++;
					}
					continue;
				}
				bool ch1Ws = Char.IsWhiteSpace (ch1);
				bool ch2Ws = Char.IsWhiteSpace (ch2);

				if (ch2Ws && !ch1Ws) {
					if (ch2 == '\n') {
						data.Insert (offset, data.EolMarker);
						data.Document.CommitLineUpdate (data.Document.OffsetToLineNumber (offset));
						if (offset < caretOffset)
							caretOffset += data.EolMarker.Length;
						if (offset < selAnchor)
							selAnchor += data.EolMarker.Length;
						if (offset < selLead)
							selLead += data.EolMarker.Length;
						textOffset++;
						offset += data.EolMarker.Length;
					} else {
						data.Insert (offset, ch2.ToString ());
						data.Document.CommitLineUpdate (data.Document.OffsetToLineNumber (offset));
						if (offset < caretOffset)
							caretOffset++;
						if (offset < selAnchor)
							selAnchor++;
						if (offset < selLead)
							selLead++;
						textOffset++;
						offset++;
					}
					continue;
				}

				if ((!ch2Ws || ch2 == '\n') && ch1Ws) {
					if (offset < caretOffset)
						caretOffset--;
					if (offset < selAnchor)
						selAnchor--;
					if (offset < selLead)
						selLead--;
					data.Remove (offset, 1);
					data.Document.CommitLineUpdate (data.Document.OffsetToLineNumber (offset));
					continue;
				}
				if (ch1Ws && ch2Ws) {
					data.Replace (offset, 1, ch2.ToString ());
					data.Document.CommitLineUpdate (data.Document.OffsetToLineNumber (offset));
					textOffset++;
					offset++;
					continue;
				}
				Console.WriteLine ("BAIL OUT");
				break;
			}
			data.Caret.Offset = caretOffset;
			
			if (selAnchor >= 0)
				data.MainSelection = new Selection (data.Document.OffsetToLocation (selAnchor), data.Document.OffsetToLocation (selLead));
			data.Document.EndAtomicUndo ();
		}
Example #19
0
		static int PasteFrom (Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
		{
			int result = -1;
			if (!data.CanEdit (data.Document.OffsetToLineNumber (insertionOffset)))
				return result;
			if (clipboard.WaitIsTargetAvailable (CopyOperation.MD_ATOM)) {
				clipboard.RequestContents (CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
					if (selectionData.Length > 0) {
						byte[] selBytes = selectionData.Data;
	
						string text = System.Text.Encoding.UTF8.GetString (selBytes, 1, selBytes.Length - 1);
						bool pasteBlock = (selBytes [0] & 1) == 1;
						bool pasteLine = (selBytes [0] & 2) == 2;
						
//						var clearSelection = data.IsSomethingSelected ? data.MainSelection.SelectionMode != SelectionMode.Block : true;
						if (pasteBlock) {
							using (var undo = data.OpenUndoGroup ()) {
								var version = data.Document.Version;
								data.DeleteSelectedText (!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
								data.EnsureCaretIsNotVirtual ();
								insertionOffset = version.MoveOffsetTo (data.Document.Version, insertionOffset);

								data.Caret.PreserveSelection = true;
							
								string[] lines = text.Split ('\r');
								int lineNr = data.Document.OffsetToLineNumber (insertionOffset);
								int col = insertionOffset - data.Document.GetLine (lineNr).Offset;
								int visCol = data.Document.GetLine (lineNr).GetVisualColumn (data, col);
								DocumentLine curLine;
								int lineCol = col;
								result = 0;
								for (int i = 0; i < lines.Length; i++) {
									while (data.Document.LineCount <= lineNr + i) {
										data.Insert (data.Document.TextLength, Environment.NewLine);
										result += Environment.NewLine.Length;
									}
									curLine = data.Document.GetLine (lineNr + i);
									if (lines [i].Length > 0) {
										lineCol = curLine.GetLogicalColumn (data, visCol);
										if (curLine.Length + 1 < lineCol) {
											result += lineCol - curLine.Length;
											data.Insert (curLine.Offset + curLine.Length, new string (' ', lineCol - curLine.Length));
										}
										data.Insert (curLine.Offset + lineCol, lines [i]);
										result += lines [i].Length;
									}
									if (!preserveState)
										data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length;
								}
								if (!preserveState)
									data.ClearSelection ();
								data.Caret.PreserveSelection = false;
							}
						} else if (pasteLine) {
							using (var undo = data.OpenUndoGroup ()) {
								data.DeleteSelectedText (!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
								data.EnsureCaretIsNotVirtual ();

								data.Caret.PreserveSelection = true;
								result = text.Length;
								DocumentLine curLine = data.Document.GetLine (data.Caret.Line);
								data.Insert (curLine.Offset, text + data.EolMarker);
								if (!preserveState)
									data.ClearSelection ();
								data.Caret.PreserveSelection = false;
							}
						} else {
							result = PastePlainText (data, insertionOffset, text);
						}
					}
				});
				// we got MD_ATOM text - no need to request text. (otherwise buffer may get copied twice).
				return result;
			}
			
			if (result < 0 && clipboard.WaitIsTextAvailable ()) {
				clipboard.RequestText (delegate(Clipboard clp, string text) {
					if (string.IsNullOrEmpty (text))
						return;
					using (var undo = data.OpenUndoGroup ()) {
						result = PastePlainText (data, insertionOffset, text);
					}
				});
			}
			
			return result;
		}
Example #20
0
        protected void InsertCharacter(uint unicodeKey)
        {
            if (!textEditorData.CanEdit(Data.Caret.Line))
            {
                return;
            }

            HideMouseCursor();

            Document.BeginAtomicUndo();
            if (textEditorData.IsSomethingSelected && textEditorData.MainSelection.SelectionMode == SelectionMode.Block)
            {
                textEditorData.Caret.PreserveSelection = true;
                if (!textEditorData.MainSelection.IsDirty)
                {
                    textEditorData.DeleteSelectedText(false);
                    textEditorData.MainSelection.IsDirty = true;
                }
            }
            else
            {
                textEditorData.DeleteSelectedText();
            }

            char ch = (char)unicodeKey;

            if (!char.IsControl(ch) && textEditorData.CanEdit(Caret.Line))
            {
                LineSegment line = Document.GetLine(Caret.Line);
                if (Caret.IsInInsertMode || Caret.Column >= line.EditableLength)
                {
                    string text = Caret.Column > line.EditableLength ? textEditorData.GetVirtualSpaces(Caret.Line, Caret.Column) + ch.ToString() : ch.ToString();
                    if (textEditorData.IsSomethingSelected && textEditorData.MainSelection.SelectionMode == SelectionMode.Block)
                    {
                        int length = 0;
                        for (int lineNumber = textEditorData.MainSelection.MinLine; lineNumber <= textEditorData.MainSelection.MaxLine; lineNumber++)
                        {
                            length = textEditorData.Insert(textEditorData.Document.GetLine(lineNumber).Offset + Caret.Column, text);
                        }
                        Caret.Column += length - 1;
                        textEditorData.MainSelection.Lead    = new DocumentLocation(textEditorData.MainSelection.Lead.Line, Caret.Column + 1);
                        textEditorData.MainSelection.IsDirty = true;
                        Document.CommitMultipleLineUpdate(textEditorData.MainSelection.MinLine, textEditorData.MainSelection.MaxLine);
                    }
                    else
                    {
                        int length = textEditorData.Insert(Caret.Offset, text);
                        Caret.Column += length - 1;
                    }
                }
                else
                {
                    int length = textEditorData.Replace(Caret.Offset, 1, ch.ToString());
                    if (length > 1)
                    {
                        Caret.Offset += length - 1;
                    }
                }
                // That causes unnecessary redraws:
                //				bool autoScroll = Caret.AutoScrollToCaret;
                Caret.Column++;
                //				Caret.AutoScrollToCaret = autoScroll;
                //				if (autoScroll)
                //					Editor.ScrollToCaret ();
                //				Document.RequestUpdate (new LineUpdate (Caret.Line));
                //				Document.CommitDocumentUpdate ();
            }
            if (textEditorData.IsSomethingSelected && textEditorData.MainSelection.SelectionMode == SelectionMode.Block)
            {
                textEditorData.Caret.PreserveSelection = false;
            }
            Document.EndAtomicUndo();
            Document.OptimizeTypedUndo();
        }
Example #21
0
        static int PasteFrom(TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
        {
            int result = -1;

            if (!data.CanEdit(data.Document.OffsetToLineNumber(insertionOffset)))
            {
                return(result);
            }
            if (Clipboard.ContainsData <byte[]>())
            {
                byte[] selBytes   = Clipboard.GetData <byte[]>();
                var    upperBound = System.Math.Max(0, System.Math.Min(selBytes[1], selBytes.Length - 2));
                byte[] copyData   = new byte[upperBound];
                Array.Copy(selBytes, 2, copyData, 0, copyData.Length);
                var    rawTextOffset = 1 + 1 + copyData.Length;
                string text          = Encoding.UTF8.GetString(selBytes, rawTextOffset, selBytes.Length - rawTextOffset);
                bool   pasteBlock    = (selBytes[0] & 1) == 1;
                bool   pasteLine     = (selBytes[0] & 2) == 2;
                if (pasteBlock)
                {
                    using (var undo = data.OpenUndoGroup())
                    {
                        var version = data.Document.Version;
                        if (!preserveSelection)
                        {
                            data.DeleteSelectedText(!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
                        }
                        int startLine = data.Caret.Line;
                        data.EnsureCaretIsNotVirtual();
                        insertionOffset = version.MoveOffsetTo(data.Document.Version, insertionOffset);

                        data.Caret.PreserveSelection = true;
                        var lines  = new List <string>();
                        int offset = 0;
                        while (true)
                        {
                            var delimiter = LineSplitter.NextDelimiter(text, offset);
                            if (delimiter.IsInvalid)
                            {
                                break;
                            }

                            int delimiterEndOffset = delimiter.EndOffset;
                            lines.Add(text.Substring(offset, delimiter.Offset - offset));
                            offset = delimiterEndOffset;
                        }
                        if (offset < text.Length)
                        {
                            lines.Add(text.Substring(offset, text.Length - offset));
                        }

                        int          lineNr = data.Document.OffsetToLineNumber(insertionOffset);
                        int          col    = insertionOffset - data.Document.GetLine(lineNr).Offset;
                        int          visCol = data.Document.GetLine(lineNr).GetVisualColumn(data, col);
                        DocumentLine curLine;
                        int          lineCol = col;
                        result = 0;
                        for (int i = 0; i < lines.Count; i++)
                        {
                            while (data.Document.LineCount <= lineNr + i)
                            {
                                data.Insert(data.Document.TextLength, Environment.NewLine);
                                result += Environment.NewLine.Length;
                            }
                            curLine = data.Document.GetLine(lineNr + i);
                            if (lines[i].Length > 0)
                            {
                                lineCol = curLine.GetLogicalColumn(data, visCol);
                                if (curLine.Length + 1 < lineCol)
                                {
                                    result += lineCol - curLine.Length;
                                    data.Insert(curLine.Offset + curLine.Length, new string(' ', lineCol - curLine.Length));
                                }
                                data.Insert(curLine.Offset + lineCol, lines[i]);
                                result += lines[i].Length;
                            }
                            if (!preserveState)
                            {
                                data.Caret.Offset = curLine.Offset + lineCol + lines[i].Length;
                            }
                        }
                        if (!preserveState)
                        {
                            data.ClearSelection();
                        }
                        data.FixVirtualIndentation(startLine);
                        data.Caret.PreserveSelection = false;
                    }
                }
                else if (pasteLine)
                {
                    using (var undo = data.OpenUndoGroup())
                    {
                        if (!preserveSelection)
                        {
                            data.DeleteSelectedText(!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
                        }
                        data.EnsureCaretIsNotVirtual();

                        data.Caret.PreserveSelection = true;
                        result = text.Length;
                        DocumentLine curLine = data.Document.GetLine(data.Caret.Line);

                        result = PastePlainText(data, curLine.Offset, text + data.EolMarker, preserveSelection, copyData);
                        if (!preserveState)
                        {
                            data.ClearSelection();
                        }
                        data.Caret.PreserveSelection = false;
                        data.FixVirtualIndentation(curLine.LineNumber);
                    }
                }
                else
                {
                    result = PastePlainText(data, insertionOffset, text, preserveSelection, copyData);
                }
            }
            else if (Clipboard.ContainsData(TransferDataType.Text))
            {
                var text = Clipboard.GetText();
                result = PastePlainText(data, insertionOffset, text, preserveState);
            }



            return(result);
        }
Example #22
0
        public static void InsertNewLine(TextEditorData data)
        {
            if (!data.CanEditSelection)
            {
                return;
            }

            using (var undo = data.OpenUndoGroup()) {
                if (data.IsSomethingSelected)
                {
                    var end = data.MainSelection.End;
                    data.DeleteSelectedText();
                    if (end.Column == 1)
                    {
                        CaretMoveActions.InternalCaretMoveHome(data, true, false);
                        return;
                    }
                }
                switch (data.Options.IndentStyle)
                {
                case IndentStyle.None:
                    data.InsertAtCaret(data.EolMarker);
                    break;

                case IndentStyle.Auto:
                    data.EnsureCaretIsNotVirtual();
                    var indent = data.Document.GetLineIndent(data.Caret.Line);
                    if (data.Caret.Column >= indent.Length)
                    {
                        data.InsertAtCaret(data.EolMarker + indent);
                    }
                    else
                    {
                        data.InsertAtCaret(data.EolMarker);
                    }
                    break;

                case IndentStyle.Smart:
                    if (!data.HasIndentationTracker)
                    {
                        goto case IndentStyle.Auto;
                    }
                    NewLineSmartIndent(data);
                    break;

                case IndentStyle.Virtual:
                    if (!data.HasIndentationTracker)
                    {
                        goto case IndentStyle.Auto;
                    }
                    var oldLine   = data.Caret.Line;
                    var curLine   = data.GetLine(oldLine);
                    var indentCol = data.GetVirtualIndentationColumn(data.Caret.Location);
                    if (curLine.Length >= data.Caret.Column)
                    {
                        NewLineSmartIndent(data);
                        data.FixVirtualIndentation();
                        data.FixVirtualIndentation(oldLine);
                        break;
                    }
                    data.Insert(data.Caret.Offset, data.EolMarker);
                    data.FixVirtualIndentation(oldLine);
                    data.Caret.Column = indentCol;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Example #23
0
		static void IndentCode (TextEditorData data, string lineIndent)
		{
			for (int i = 1; i < data.LineCount; i++) {
				var line = data.GetLine (i + 1);
				if (line.Length > 0)
					data.Insert (line.Offset, lineIndent);
			}
		}
Example #24
0
		static int PasteFrom (Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
		{
			int result = -1;
			if (!data.CanEdit (data.Document.OffsetToLineNumber (insertionOffset)))
				return result;
			clipboard.RequestContents (CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
				if (selectionData.Length > 0) {
					byte[] selBytes = selectionData.Data;

					string text = System.Text.Encoding.UTF8.GetString (selBytes, 1, selBytes.Length - 1);
					bool pasteBlock = (selBytes[0] & 1) == 1;
					bool pasteLine = (selBytes[0] & 2) == 2;
					if (!pasteBlock && !pasteLine)
						return;
					
					data.Document.BeginAtomicUndo ();
					if (preserveSelection && data.IsSomethingSelected)
						data.DeleteSelectedText ();
					
					data.Caret.PreserveSelection = true;
					if (pasteBlock) {
						string[] lines = text.Split ('\r');
						int lineNr = data.Document.OffsetToLineNumber (insertionOffset);
						int col = insertionOffset - data.Document.GetLine (lineNr).Offset;
						int visCol = data.Document.GetLine (lineNr).GetVisualColumn (data, col);
						LineSegment curLine;
						int lineCol = col;
						result = 0;
						for (int i = 0; i < lines.Length; i++) {
							while (data.Document.LineCount <= lineNr + i) {
								data.Insert (data.Document.Length, Environment.NewLine);
								result += Environment.NewLine.Length;
							}
							curLine = data.Document.GetLine (lineNr + i);
							if (lines[i].Length > 0) {
								lineCol = curLine.GetLogicalColumn (data, visCol);
								if (curLine.EditableLength + 1 < lineCol) {
									result += lineCol - curLine.EditableLength;
									data.Insert (curLine.Offset + curLine.EditableLength, new string (' ', lineCol - curLine.EditableLength));
								}
								data.Insert (curLine.Offset + lineCol, lines[i]);
								result += lines[i].Length;
							}
							if (!preserveState)
								data.Caret.Offset = curLine.Offset + lineCol + lines[i].Length;
						}
					} else if (pasteLine) {
						result += text.Length;
						LineSegment curLine = data.Document.GetLine (data.Caret.Line);
						data.Insert (curLine.Offset, text + data.EolMarker);
						if (!preserveState)
							data.Caret.Offset += text.Length + data.EolMarker.Length;
					}
					/*				data.MainSelection = new Selection (data.Document.OffsetToLocation (insertionOffset),
					                                    data.Caret.Location,
					                                    lines.Length > 1 ? SelectionMode.Block : SelectionMode.Normal);*/
					if (!preserveState)
						data.ClearSelection ();
					data.Caret.PreserveSelection = false;
					data.Document.EndAtomicUndo ();
				}
			});

			if (result < 0) {
				clipboard.WaitIsTextAvailable ();
				clipboard.RequestText (delegate(Clipboard clp, string text) {
					if (string.IsNullOrEmpty (text))
						return;
					data.Document.BeginAtomicUndo ();
					int caretPos = data.Caret.Offset;
					if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block) {
						data.Caret.PreserveSelection = true;
						if (!data.MainSelection.IsDirty) {
							data.DeleteSelectedText (false);
							data.MainSelection.IsDirty = true;
						}
						int textLength = 0;
						int column = data.Caret.Column;
						int minLine = data.MainSelection.MinLine;
						int maxLine = data.MainSelection.MaxLine;
						for (int lineNumber = minLine; lineNumber <= maxLine; lineNumber++) {
							int offset = data.Document.GetLine (lineNumber).Offset + column;
							textLength = data.Insert (offset, text);
							data.PasteText (offset, text);
						}
						
						data.Caret.Offset += textLength;
						data.MainSelection.Anchor = new DocumentLocation (data.Caret.Line == minLine ? maxLine : minLine, data.Caret.Column - textLength);
						data.MainSelection.Lead = new DocumentLocation (data.Caret.Line, data.Caret.Column);
						data.Caret.PreserveSelection = false;
						data.Document.CommitMultipleLineUpdate (data.MainSelection.MinLine, data.MainSelection.MaxLine);
					} else {
						ISegment selection = data.SelectionRange;
						if (preserveSelection && data.IsSomethingSelected)
							data.DeleteSelectedText ();
						data.Caret.PreserveSelection = true;
						//int oldLine = data.Caret.Line;
						int textLength = data.Insert (insertionOffset, text);
						result = textLength;
	
						if (data.IsSomethingSelected && data.SelectionRange.Offset >= insertionOffset)
							data.SelectionRange.Offset += textLength;
						if (data.IsSomethingSelected && data.MainSelection.GetAnchorOffset (data) >= insertionOffset)
							data.MainSelection.Anchor = data.Document.OffsetToLocation (data.MainSelection.GetAnchorOffset (data) + textLength);
						
						data.Caret.PreserveSelection = false;
						if (!preserveState) {
							data.Caret.Offset += textLength;
						} else {
							if (caretPos >= insertionOffset)
								data.Caret.Offset += textLength;
							if (selection != null) {
								int offset = selection.Offset;
								if (offset >= insertionOffset)
									offset += textLength;
								data.SelectionRange = new Segment (offset, selection.Length);
							}
						}
						data.PasteText (insertionOffset, text);
					}
					data.Document.EndAtomicUndo ();
				});
			}
			
			return result;
		}
Example #25
0
		public static void DuplicateLine (TextEditorData data)
		{
			using (var undoGroup = data.OpenUndoGroup ()) {
				if (data.IsSomethingSelected) {
					var selectedText = data.SelectedText;
					data.ClearSelection ();
					data.InsertAtCaret (selectedText);
				} else {
					DocumentLine line = data.Document.GetLine (data.Caret.Line);
					if (line == null)
						return;
					if (line.DelimiterLength == 0) {
						data.Insert (line.Offset, data.GetTextAt (line.SegmentIncludingDelimiter) + data.EolMarker);
					} else {
						data.Insert (line.Offset, data.GetTextAt (line.SegmentIncludingDelimiter));
					}
				}
			}
		}
Example #26
0
        static int PasteFrom(Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
        {
            int result = -1;

            if (!data.CanEdit(data.Document.OffsetToLineNumber(insertionOffset)))
            {
                return(result);
            }
            if (clipboard.WaitIsTargetAvailable(CopyOperation.MD_ATOM))
            {
                clipboard.RequestContents(CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
                    if (selectionData.Length > 0)
                    {
                        byte[] selBytes = selectionData.Data;

                        string text     = System.Text.Encoding.UTF8.GetString(selBytes, 1, selBytes.Length - 1);
                        bool pasteBlock = (selBytes [0] & 1) == 1;
                        bool pasteLine  = (selBytes [0] & 2) == 2;

//						var clearSelection = data.IsSomethingSelected ? data.MainSelection.SelectionMode != SelectionMode.Block : true;
                        using (var undo = data.OpenUndoGroup()) {
                            if (pasteBlock)
                            {
                                data.Caret.PreserveSelection = true;

                                string[] lines = text.Split('\r');
                                int lineNr     = data.Document.OffsetToLineNumber(insertionOffset);
                                int col        = insertionOffset - data.Document.GetLine(lineNr).Offset;
                                int visCol     = data.Document.GetLine(lineNr).GetVisualColumn(data, col);
                                DocumentLine curLine;
                                int lineCol = col;
                                result      = 0;
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    while (data.Document.LineCount <= lineNr + i)
                                    {
                                        data.Insert(data.Document.TextLength, Environment.NewLine);
                                        result += Environment.NewLine.Length;
                                    }
                                    curLine = data.Document.GetLine(lineNr + i);
                                    if (lines [i].Length > 0)
                                    {
                                        lineCol = curLine.GetLogicalColumn(data, visCol);
                                        if (curLine.Length + 1 < lineCol)
                                        {
                                            result += lineCol - curLine.Length;
                                            data.Insert(curLine.Offset + curLine.Length, new string (' ', lineCol - curLine.Length));
                                        }
                                        data.Insert(curLine.Offset + lineCol, lines [i]);
                                        result += lines [i].Length;
                                    }
                                    if (!preserveState)
                                    {
                                        data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length;
                                    }
                                }
                                if (!preserveState)
                                {
                                    data.ClearSelection();
                                }
                                data.Caret.PreserveSelection = false;
                            }
                            else if (pasteLine)
                            {
                                data.Caret.PreserveSelection = true;
                                result = text.Length;
                                DocumentLine curLine = data.Document.GetLine(data.Caret.Line);
                                data.Insert(curLine.Offset, text + data.EolMarker);
                                if (!preserveState)
                                {
                                    data.ClearSelection();
                                }
                                data.Caret.PreserveSelection = false;
                            }
                            else
                            {
                                result = PastePlainText(data, insertionOffset, text);
                            }
                        }
                    }
                });
                // we got MD_ATOM text - no need to request text. (otherwise buffer may get copied twice).
                return(result);
            }

            if (result < 0 && clipboard.WaitIsTextAvailable())
            {
                clipboard.RequestText(delegate(Clipboard clp, string text) {
                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }
                    using (var undo = data.OpenUndoGroup()) {
                        result = PastePlainText(data, insertionOffset, text);
                    }
                });
            }

            return(result);
        }
		public void Insert (TextEditorData editor, string text)
		{
			int offset = editor.Document.LocationToOffset (Location);
			editor.Document.BeginAtomicUndo ();
			text = editor.FormatString (Location, text);
			
			LineSegment line = editor.Document.GetLineByOffset (offset);
			int insertionOffset = line.Offset + Location.Column - 1;
			offset = insertionOffset;
			InsertNewLine (editor, LineBefore, ref offset);
			
			offset += editor.Insert (offset, text);
			InsertNewLine (editor, LineAfter, ref offset);
			editor.Document.EndAtomicUndo ();
		}
Example #28
0
        protected void InsertCharacter(uint unicodeKey)
        {
            if (!textEditorData.CanEdit(Data.Caret.Line))
            {
                return;
            }

            HideMouseCursor();

            using (var undo = Document.OpenUndoGroup()) {
                if (textEditorData.IsSomethingSelected && textEditorData.Options.EnableSelectionWrappingKeys && IsSpecialKeyForSelection(unicodeKey))
                {
                    textEditorData.SelectionSurroundingProvider.HandleSpecialSelectionKey(textEditorData, unicodeKey);
                    return;
                }

                textEditorData.DeleteSelectedText(
                    textEditorData.IsSomethingSelected ? textEditorData.MainSelection.SelectionMode != SelectionMode.Block : true);
                // Needs to be called after delete text, delete text handles virtual caret postitions itself,
                // but afterwards the virtual position may need to be restored.
                textEditorData.EnsureCaretIsNotVirtual();

                char ch = (char)unicodeKey;
                if (!char.IsControl(ch) && textEditorData.CanEdit(Caret.Line))
                {
                    DocumentLine line = Document.GetLine(Caret.Line);
                    if (Caret.IsInInsertMode || Caret.Column >= line.Length + 1)
                    {
                        string text = ch.ToString();
                        if (textEditorData.IsSomethingSelected && textEditorData.MainSelection.SelectionMode == SelectionMode.Block)
                        {
                            var visualInsertLocation = textEditorData.LogicalToVisualLocation(Caret.Location);
                            var selection            = textEditorData.MainSelection;
                            Caret.PreserveSelection = true;
                            for (int lineNumber = selection.MinLine; lineNumber <= selection.MaxLine; lineNumber++)
                            {
                                DocumentLine lineSegment  = textEditorData.GetLine(lineNumber);
                                int          insertOffset = lineSegment.GetLogicalColumn(textEditorData, visualInsertLocation.Column) - 1;
                                string       textToInsert;
                                if (lineSegment.Length < insertOffset)
                                {
                                    int visualLastColumn = lineSegment.GetVisualColumn(textEditorData, lineSegment.Length + 1);
                                    int charsToInsert    = visualInsertLocation.Column - visualLastColumn;
                                    int spaceCount       = charsToInsert % editor.Options.TabSize;
                                    textToInsert = new string ('\t', (charsToInsert - spaceCount) / editor.Options.TabSize) +
                                                   new string (' ', spaceCount) + text;
                                    insertOffset = lineSegment.Length;
                                }
                                else
                                {
                                    textToInsert = text;
                                }
                                textEditorData.Insert(lineSegment.Offset + insertOffset, textToInsert);
                            }
                            var visualColumn = textEditorData.GetLine(Caret.Location.Line).GetVisualColumn(textEditorData, Caret.Column);

                            textEditorData.MainSelection = new Selection(
                                new DocumentLocation(selection.Anchor.Line, textEditorData.GetLine(selection.Anchor.Line).GetLogicalColumn(textEditorData, visualColumn)),
                                new DocumentLocation(selection.Lead.Line, textEditorData.GetLine(selection.Lead.Line).GetLogicalColumn(textEditorData, visualColumn)),
                                SelectionMode.Block
                                );
                            Document.CommitMultipleLineUpdate(textEditorData.MainSelection.MinLine, textEditorData.MainSelection.MaxLine);
                        }
                        else
                        {
                            textEditorData.Insert(Caret.Offset, text);
                        }
                    }
                    else
                    {
                        textEditorData.Replace(Caret.Offset, 1, ch.ToString());
                    }
                    // That causes unnecessary redraws:
                    //				bool autoScroll = Caret.AutoScrollToCaret;
//					Caret.Column++;
                    if (Caret.PreserveSelection)
                    {
                        Caret.PreserveSelection = false;
                    }
                    //				Caret.AutoScrollToCaret = autoScroll;
                    //				if (autoScroll)
                    //					Editor.ScrollToCaret ();
                    //				Document.RequestUpdate (new LineUpdate (Caret.Line));
                    //				Document.CommitDocumentUpdate ();
                }
            }
            Document.OptimizeTypedUndo();
        }
Example #29
0
		public static void Paste (TextEditorData data)
		{
			if (!data.CanEditSelection)
				return;
			LineSegment line = data.Document.GetLine (data.Caret.Line);
			if (data.Caret.Column > line.EditableLength + 1) {
				string text = data.GetVirtualSpaces (data.Caret.Line, data.Caret.Column);
				int offset = data.Caret.Offset;
				int textLength = data.Insert (offset, text);
				data.Caret.Offset = offset + textLength;
			}
			PasteFrom (Clipboard.Get (CopyOperation.CLIPBOARD_ATOM), data, true, data.IsSomethingSelected ? data.SelectionRange.Offset : data.Caret.Offset);
		}
        static int PasteFrom(Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
        {
            int result = -1;

            if (!data.CanEdit(data.Document.OffsetToLineNumber(insertionOffset)))
            {
                return(result);
            }
            clipboard.RequestContents(CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
                if (selectionData.Length > 0)
                {
                    byte[] selBytes = selectionData.Data;

                    string text     = System.Text.Encoding.UTF8.GetString(selBytes, 1, selBytes.Length - 1);
                    bool pasteBlock = (selBytes[0] & 1) == 1;
                    bool pasteLine  = (selBytes[0] & 2) == 2;
                    if (!pasteBlock && !pasteLine)
                    {
                        return;
                    }

                    data.Document.BeginAtomicUndo();
                    if (preserveSelection && data.IsSomethingSelected)
                    {
                        data.DeleteSelectedText();
                    }

                    data.Caret.PreserveSelection = true;
                    if (pasteBlock)
                    {
                        string[] lines = text.Split('\r');
                        int lineNr     = data.Document.OffsetToLineNumber(insertionOffset);
                        int col        = insertionOffset - data.Document.GetLine(lineNr).Offset;
                        int visCol     = data.Document.GetLine(lineNr).GetVisualColumn(data, col);
                        LineSegment curLine;
                        int lineCol = col;
                        result      = 0;
                        for (int i = 0; i < lines.Length; i++)
                        {
                            while (data.Document.LineCount <= lineNr + i)
                            {
                                data.Insert(data.Document.Length, Environment.NewLine);
                                result += Environment.NewLine.Length;
                            }
                            curLine = data.Document.GetLine(lineNr + i);
                            if (lines[i].Length > 0)
                            {
                                lineCol = curLine.GetLogicalColumn(data, visCol);
                                if (curLine.EditableLength < lineCol)
                                {
                                    result += lineCol - curLine.EditableLength;
                                    data.Insert(curLine.Offset + curLine.EditableLength, new string (' ', lineCol - curLine.EditableLength));
                                }
                                data.Insert(curLine.Offset + lineCol, lines[i]);
                                result += lines[i].Length;
                            }
                            if (!preserveState)
                            {
                                data.Caret.Offset = curLine.Offset + lineCol + lines[i].Length;
                            }
                        }
                    }
                    else if (pasteLine)
                    {
                        result += text.Length;
                        LineSegment curLine = data.Document.GetLine(data.Caret.Line);
                        data.Insert(curLine.Offset, text + data.EolMarker);
                        if (!preserveState)
                        {
                            data.Caret.Offset += text.Length + data.EolMarker.Length;
                        }
                    }

                    /*				data.MainSelection = new Selection (data.Document.OffsetToLocation (insertionOffset),
                     *                                  data.Caret.Location,
                     *                                  lines.Length > 1 ? SelectionMode.Block : SelectionMode.Normal);*/
                    if (!preserveState)
                    {
                        data.ClearSelection();
                    }
                    data.Caret.PreserveSelection = false;
                    data.Document.EndAtomicUndo();
                }
            });

            if (result < 0)
            {
                clipboard.WaitIsTextAvailable();
                clipboard.RequestText(delegate(Clipboard clp, string text) {
                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }
                    data.Document.BeginAtomicUndo();
                    int caretPos = data.Caret.Offset;
                    if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block)
                    {
                        data.Caret.PreserveSelection = true;
                        if (!data.MainSelection.IsDirty)
                        {
                            data.DeleteSelectedText(false);
                            data.MainSelection.IsDirty = true;
                        }
                        int textLength = 0;
                        int column     = data.Caret.Column;
                        int minLine    = data.MainSelection.MinLine;
                        int maxLine    = data.MainSelection.MaxLine;
                        for (int lineNumber = minLine; lineNumber <= maxLine; lineNumber++)
                        {
                            int offset = data.Document.GetLine(lineNumber).Offset + column;
                            textLength = data.Insert(offset, text);
                            data.PasteText(offset, text);
                        }

                        data.Caret.Offset           += textLength;
                        data.MainSelection.Anchor    = new DocumentLocation(data.Caret.Line == minLine ? maxLine : minLine, data.Caret.Column - textLength);
                        data.MainSelection.Lead      = new DocumentLocation(data.Caret.Line, data.Caret.Column);
                        data.Caret.PreserveSelection = false;
                        data.Document.CommitMultipleLineUpdate(data.MainSelection.MinLine, data.MainSelection.MaxLine);
                    }
                    else
                    {
                        ISegment selection = data.SelectionRange;
                        if (preserveSelection && data.IsSomethingSelected)
                        {
                            data.DeleteSelectedText();
                        }
                        data.Caret.PreserveSelection = true;
                        //int oldLine = data.Caret.Line;
                        int textLength = data.Insert(insertionOffset, text);
                        result         = textLength;

                        if (data.IsSomethingSelected && data.SelectionRange.Offset >= insertionOffset)
                        {
                            data.SelectionRange.Offset += textLength;
                        }
                        if (data.IsSomethingSelected && data.MainSelection.GetAnchorOffset(data) >= insertionOffset)
                        {
                            data.MainSelection.Anchor = data.Document.OffsetToLocation(data.MainSelection.GetAnchorOffset(data) + textLength);
                        }

                        data.Caret.PreserveSelection = false;
                        if (!preserveState)
                        {
                            data.Caret.Offset += textLength;
                        }
                        else
                        {
                            if (caretPos >= insertionOffset)
                            {
                                data.Caret.Offset += textLength;
                            }
                            if (selection != null)
                            {
                                int offset = selection.Offset;
                                if (offset >= insertionOffset)
                                {
                                    offset += textLength;
                                }
                                data.SelectionRange = new Segment(offset, selection.Length);
                            }
                        }
                        data.PasteText(insertionOffset, text);
                    }
                    data.Document.EndAtomicUndo();
                });
            }

            return(result);
        }
		public static void InsertNewLine (TextEditorData data)
		{
			if (!data.CanEditSelection)
				return;
			
			using (var undo = data.OpenUndoGroup ()) {
				if (data.IsSomethingSelected)
					data.DeleteSelectedText ();
				switch (data.Options.IndentStyle) {
				case IndentStyle.None:
					data.InsertAtCaret (data.EolMarker);
					break;
				case IndentStyle.Auto:
					data.EnsureCaretIsNotVirtual ();
					var sb = new StringBuilder (data.EolMarker);
					sb.Append (data.Document.GetLineIndent (data.Caret.Line));
					data.InsertAtCaret (sb.ToString ());
					break;
				case IndentStyle.Smart:
					if (!data.HasIndentationTracker)
						goto case IndentStyle.Auto;
					NewLineSmartIndent (data);
					break;
				case IndentStyle.Virtual:
					if (!data.HasIndentationTracker)
						goto case IndentStyle.Auto;
					var oldLine = data.Caret.Line;
					var curLine = data.GetLine (oldLine);
					var indentCol = data.GetVirtualIndentationColumn (data.Caret.Location);
					if (curLine.Length >= data.Caret.Column) {
						NewLineSmartIndent (data);
						data.FixVirtualIndentation ();
						data.FixVirtualIndentation (oldLine);
						break;
					}
					data.Insert (data.Caret.Offset, data.EolMarker);
					data.FixVirtualIndentation (oldLine);
					data.Caret.Column = indentCol;
					break;
				default:
					throw new ArgumentOutOfRangeException ();
				}
			}
		}
Example #32
0
        /// <summary>
        /// Transpose characters (Emacs C-t)
        /// </summary>
        public static void TransposeCharacters(TextEditorData data)
        {
            if (data.Caret.Offset == 0)
            {
                return;
            }
            DocumentLine line = data.Document.GetLine(data.Caret.Line);

            if (line == null)
            {
                return;
            }
            int  transposeOffset = data.Caret.Offset - 1;
            char ch;

            if (data.Caret.Column == 0)
            {
                DocumentLine lineAbove = data.Document.GetLine(data.Caret.Line - 1);
                if (lineAbove.Length == 0 && line.Length == 0)
                {
                    return;
                }

                if (line.Length != 0)
                {
                    ch = data.Document.GetCharAt(data.Caret.Offset);
                    data.Remove(data.Caret.Offset, 1);
                    data.Insert(lineAbove.Offset + lineAbove.Length, ch.ToString());
                    data.Document.CommitLineUpdate(data.Caret.Line - 1);
                    return;
                }

                int lastCharOffset = lineAbove.Offset + lineAbove.Length - 1;
                ch = data.Document.GetCharAt(lastCharOffset);
                data.Remove(lastCharOffset, 1);
                data.InsertAtCaret(ch.ToString());
                return;
            }

            int offset = data.Caret.Offset;

            if (data.Caret.Column >= line.Length + 1)
            {
                offset          = line.Offset + line.Length - 1;
                transposeOffset = offset - 1;
                // case one char in line:
                if (transposeOffset < line.Offset)
                {
                    DocumentLine lineAbove = data.Document.GetLine(data.Caret.Line - 1);
                    transposeOffset = lineAbove.Offset + lineAbove.Length;
                    ch = data.Document.GetCharAt(offset);
                    data.Remove(offset, 1);
                    data.Insert(transposeOffset, ch.ToString());
                    data.Caret.Offset = line.Offset;
                    data.Document.CommitLineUpdate(data.Caret.Line - 1);
                    return;
                }
            }

            ch = data.Document.GetCharAt(offset);
            data.Replace(offset, 1, data.Document.GetCharAt(transposeOffset).ToString());
            data.Replace(transposeOffset, 1, ch.ToString());
            if (data.Caret.Column < line.Length + 1)
            {
                data.Caret.Offset = offset + 1;
            }
        }
		public static void DuplicateLine (TextEditorData data)
		{
			if (data.IsSomethingSelected) {
				var selectedText = data.SelectedText;
				data.ClearSelection ();
				data.InsertAtCaret (selectedText);
			}
			else {
				DocumentLine line = data.Document.GetLine (data.Caret.Line);
				if (line == null)
					return;
				data.Insert (line.Offset, data.GetTextAt (line.SegmentIncludingDelimiter));
			}
		}
Example #34
0
        static int PasteFrom(Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
        {
            int result = -1;

            if (!data.CanEdit(data.Document.OffsetToLineNumber(insertionOffset)))
            {
                return(result);
            }
            if (clipboard.WaitIsTargetAvailable(CopyOperation.MD_ATOM))
            {
                clipboard.RequestContents(CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
                    if (selectionData.Length > 0)
                    {
                        byte[] selBytes = selectionData.Data;
                        byte[] copyData = new byte[selBytes[1]];
                        Array.Copy(selBytes, 2, copyData, 0, copyData.Length);
                        var rawTextOffset = 1 + 1 + copyData.Length;
                        string text       = Encoding.UTF8.GetString(selBytes, rawTextOffset, selBytes.Length - rawTextOffset);
                        bool pasteBlock   = (selBytes [0] & 1) == 1;
                        bool pasteLine    = (selBytes [0] & 2) == 2;
                        if (pasteBlock)
                        {
                            using (var undo = data.OpenUndoGroup()) {
                                var version = data.Document.Version;
                                if (!preserveSelection)
                                {
                                    data.DeleteSelectedText(!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
                                }
                                int startLine = data.Caret.Line;
                                data.EnsureCaretIsNotVirtual();
                                insertionOffset = version.MoveOffsetTo(data.Document.Version, insertionOffset);

                                data.Caret.PreserveSelection = true;
                                var lines  = new List <string> ();
                                int offset = 0;
                                while (true)
                                {
                                    var delimiter = LineSplitter.NextDelimiter(text, offset);
                                    if (delimiter.IsInvalid)
                                    {
                                        break;
                                    }

                                    int delimiterEndOffset = delimiter.Offset + delimiter.Length;
                                    lines.Add(text.Substring(offset, delimiter.Offset - offset));
                                    offset = delimiterEndOffset;
                                }
                                if (offset < text.Length)
                                {
                                    lines.Add(text.Substring(offset, text.Length - offset));
                                }

                                int lineNr = data.Document.OffsetToLineNumber(insertionOffset);
                                int col    = insertionOffset - data.Document.GetLine(lineNr).Offset;
                                int visCol = data.Document.GetLine(lineNr).GetVisualColumn(data, col);
                                DocumentLine curLine;
                                int lineCol = col;
                                result      = 0;
                                for (int i = 0; i < lines.Count; i++)
                                {
                                    while (data.Document.LineCount <= lineNr + i)
                                    {
                                        data.Insert(data.Document.TextLength, Environment.NewLine);
                                        result += Environment.NewLine.Length;
                                    }
                                    curLine = data.Document.GetLine(lineNr + i);
                                    if (lines [i].Length > 0)
                                    {
                                        lineCol = curLine.GetLogicalColumn(data, visCol);
                                        if (curLine.Length + 1 < lineCol)
                                        {
                                            result += lineCol - curLine.Length;
                                            data.Insert(curLine.Offset + curLine.Length, new string (' ', lineCol - curLine.Length));
                                        }
                                        data.Insert(curLine.Offset + lineCol, lines [i]);
                                        result += lines [i].Length;
                                    }
                                    if (!preserveState)
                                    {
                                        data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length;
                                    }
                                }
                                if (!preserveState)
                                {
                                    data.ClearSelection();
                                }
                                data.FixVirtualIndentation(startLine);
                                data.Caret.PreserveSelection = false;
                            }
                        }
                        else if (pasteLine)
                        {
                            using (var undo = data.OpenUndoGroup()) {
                                if (!preserveSelection)
                                {
                                    data.DeleteSelectedText(!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
                                }
                                data.EnsureCaretIsNotVirtual();

                                data.Caret.PreserveSelection = true;
                                result = text.Length;
                                DocumentLine curLine = data.Document.GetLine(data.Caret.Line);

                                result = PastePlainText(data, curLine.Offset, text + data.EolMarker, preserveSelection, copyData);
                                if (!preserveState)
                                {
                                    data.ClearSelection();
                                }
                                data.Caret.PreserveSelection = false;
                                data.FixVirtualIndentation(curLine.LineNumber);
                            }
                        }
                        else
                        {
                            result = PastePlainText(data, insertionOffset, text, preserveSelection, copyData);
                        }
                    }
                });
                // we got MD_ATOM text - no need to request text. (otherwise buffer may get copied twice).
                return(result);
            }

            if (result < 0 && clipboard.WaitIsTextAvailable())
            {
                clipboard.RequestText(delegate(Clipboard clp, string text) {
                    if (string.IsNullOrEmpty(text))
                    {
                        return;
                    }
                    result = PastePlainText(data, insertionOffset, text, preserveSelection);
                });
            }

            return(result);
        }
Example #35
0
		static int PasteFrom (Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
		{
			int result = -1;
			if (!data.CanEdit (data.Document.OffsetToLineNumber (insertionOffset)))
				return result;
			if (clipboard.WaitIsTargetAvailable (CopyOperation.MD_ATOM)) {
				clipboard.RequestContents (CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
					if (selectionData.Length > 0) {
						byte[] selBytes = selectionData.Data;
	
						string text = System.Text.Encoding.UTF8.GetString (selBytes, 1, selBytes.Length - 1);
						bool pasteBlock = (selBytes [0] & 1) == 1;
						bool pasteLine = (selBytes [0] & 2) == 2;
						
						using (var undo = data.OpenUndoGroup ()) {
							if (preserveSelection && data.IsSomethingSelected)
								data.DeleteSelectedText ();
							
							data.Caret.PreserveSelection = true;
							if (pasteBlock) {
								string[] lines = text.Split ('\r');
								int lineNr = data.Document.OffsetToLineNumber (insertionOffset);
								int col = insertionOffset - data.Document.GetLine (lineNr).Offset;
								int visCol = data.Document.GetLine (lineNr).GetVisualColumn (data, col);
								DocumentLine curLine;
								int lineCol = col;
								result = 0;
								for (int i = 0; i < lines.Length; i++) {
									while (data.Document.LineCount <= lineNr + i) {
										data.Insert (data.Document.TextLength, Environment.NewLine);
										result += Environment.NewLine.Length;
									}
									curLine = data.Document.GetLine (lineNr + i);
									if (lines [i].Length > 0) {
										lineCol = curLine.GetLogicalColumn (data, visCol);
										if (curLine.Length + 1 < lineCol) {
											result += lineCol - curLine.Length;
											data.Insert (curLine.Offset + curLine.Length, new string (' ', lineCol - curLine.Length));
										}
										data.Insert (curLine.Offset + lineCol, lines [i]);
										result += lines [i].Length;
									}
									if (!preserveState)
										data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length;
								}
							} else if (pasteLine) {
								result = text.Length;
								DocumentLine curLine = data.Document.GetLine (data.Caret.Line);
								data.Insert (curLine.Offset, text + data.EolMarker);
							} else {
								int offset = data.Caret.Offset;
								data.InsertAtCaret (text);
								data.PasteText (offset, text, data.Caret.Offset - offset);
							}
							/*				data.MainSelection = new Selection (data.Document.OffsetToLocation (insertionOffset),
							                                    data.Caret.Location,
							                                    lines.Length > 1 ? SelectionMode.Block : SelectionMode.Normal);*/
							if (!preserveState)
								data.ClearSelection ();
							data.Caret.PreserveSelection = false;
						}
					}
				});
				// we got MD_ATOM text - no need to request text. (otherwise buffer may get copied twice).
				return result;
			}
			
			if (result < 0 && clipboard.WaitIsTextAvailable ()) {
				clipboard.RequestText (delegate(Clipboard clp, string text) {
					if (string.IsNullOrEmpty (text))
						return;
					using (var undo = data.OpenUndoGroup ()) {
						int caretPos = data.Caret.Offset;
						if (data.IsSomethingSelected && data.MainSelection.SelectionMode == SelectionMode.Block) {
							data.Caret.PreserveSelection = true;
							data.DeleteSelectedText (false);
							int textLength = 0;
							int minLine = data.MainSelection.MinLine;
							int maxLine = data.MainSelection.MaxLine;
							var visualInsertLocation = data.LogicalToVisualLocation (data.Caret.Location);
							for (int lineNumber = minLine; lineNumber <= maxLine; lineNumber++) {
								DocumentLine lineSegment = data.GetLine (lineNumber);
								int insertOffset = lineSegment.GetLogicalColumn (data, visualInsertLocation.Column) - 1;
								if (lineSegment.Length < insertOffset) {
									int visualLastColumn = lineSegment.GetVisualColumn (data, lineSegment.Length + 1);
									int charsToInsert = visualInsertLocation.Column - visualLastColumn;
									int spaceCount = charsToInsert % data.Options.TabSize;
									string textToInsert = new string ('\t', (charsToInsert - spaceCount) / data.Options.TabSize) + new string (' ', spaceCount) + text;
									insertOffset = lineSegment.Length;
									int insertedChars = data.Insert (lineSegment.Offset + insertOffset, textToInsert);
									data.PasteText (lineSegment.Offset + insertOffset, textToInsert, insertedChars);
								} else {
									textLength = data.Insert (lineSegment.Offset + insertOffset, text);
									data.PasteText (lineSegment.Offset + insertOffset, text, textLength);
								}
							}
							
							data.MainSelection.Anchor = new DocumentLocation (System.Math.Max (DocumentLocation.MinLine, data.Caret.Line == minLine ? maxLine : minLine), System.Math.Max (DocumentLocation.MinColumn, data.Caret.Column - textLength));
							data.MainSelection.Lead = new DocumentLocation (data.Caret.Line, data.Caret.Column);
							data.Caret.PreserveSelection = false;
							data.Document.CommitMultipleLineUpdate (data.MainSelection.MinLine, data.MainSelection.MaxLine);
						} else {
							TextSegment selection = data.SelectionRange;
							if (preserveSelection && data.IsSomethingSelected)
								data.DeleteSelectedText ();
							data.Caret.PreserveSelection = true;
							//int oldLine = data.Caret.Line;
							int textLength = data.Insert (insertionOffset, text);
							result = textLength;
		
							if (data.IsSomethingSelected && data.SelectionRange.Offset >= insertionOffset)
								data.SelectionRange = new TextSegment (data.SelectionRange.Offset + textLength, data.SelectionRange.Length);
							if (data.IsSomethingSelected && data.MainSelection.GetAnchorOffset (data) >= insertionOffset)
								data.MainSelection.Anchor = data.Document.OffsetToLocation (data.MainSelection.GetAnchorOffset (data) + textLength);
							
							data.Caret.PreserveSelection = false;
							if (!preserveState) {
							} else {
								if (!selection.IsInvalid) {
									int offset = selection.Offset;
									if (offset >= insertionOffset)
										offset += textLength;
									data.SelectionRange = new TextSegment (offset, selection.Length);
								}
							}
							data.PasteText (insertionOffset, text, textLength);
						}
					}
				});
			}
			
			return result;
		}
		public void AddRegisterDirective (RegisterDirective directive, TextEditorData editor, bool preserveCaretPosition)
		{
			var node = GetRegisterInsertionPointNode ();
			if (node == null)
				return;
			
			Doc.Info.RegisteredTags.Add (directive);
			
			var line = Math.Max (node.Region.EndLine, node.Region.BeginLine);
			var pos = editor.Document.LocationToOffset (line, editor.Document.GetLine (line - 1).Length);
			if (pos < 0)
				return;
			
			using (var undo = editor.OpenUndoGroup ()) {
				var oldCaret = editor.Caret.Offset;
				
				var inserted = editor.Insert (pos, editor.EolMarker + directive.ToString ());
				if (preserveCaretPosition) {
					editor.Caret.Offset = (pos < oldCaret)? oldCaret + inserted : oldCaret;
				}
			}
		}
		public static bool FixLineStart (TextEditorData textEditorData, DocumentStateTracker<CSharpIndentEngine> stateTracker, int lineNumber)
		{
			if (lineNumber > DocumentLocation.MinLine) {
				DocumentLine line = textEditorData.Document.GetLine (lineNumber);
				if (line == null)
					return false;

				DocumentLine prevLine = textEditorData.Document.GetLine (lineNumber - 1);
				if (prevLine == null)
					return false;
				string trimmedPreviousLine = textEditorData.Document.GetTextAt (prevLine).TrimStart ();

				//xml doc comments
				//check previous line was a doc comment
				//check there's a following line?
				if (trimmedPreviousLine.StartsWith ("///", StringComparison.Ordinal)) {
					if (textEditorData.GetTextAt (line.Offset, line.Length).TrimStart ().StartsWith ("///", StringComparison.Ordinal))
						return false;
					//check that the newline command actually inserted a newline
					textEditorData.EnsureCaretIsNotVirtual ();
					string nextLine = textEditorData.Document.GetTextAt (textEditorData.Document.GetLine (lineNumber + 1)).TrimStart ();

					if (trimmedPreviousLine.Length > "///".Length || nextLine.StartsWith ("///", StringComparison.Ordinal)) {
						var insertionPoint = line.Offset + line.GetIndentation (textEditorData.Document).Length;
						textEditorData.Insert (insertionPoint, "/// ");
						return true;
					}
					//multi-line comments
				} else if (stateTracker.Engine.IsInsideMultiLineComment) {
					if (textEditorData.GetTextAt (line.Offset, line.Length).TrimStart ().StartsWith ("*", StringComparison.Ordinal))
						return false;
					textEditorData.EnsureCaretIsNotVirtual ();
					string commentPrefix = string.Empty;
					if (trimmedPreviousLine.StartsWith ("* ", StringComparison.Ordinal)) {
						commentPrefix = "* ";
					} else if (trimmedPreviousLine.StartsWith ("/**", StringComparison.Ordinal) || trimmedPreviousLine.StartsWith ("/*", StringComparison.Ordinal)) {
						commentPrefix = " * ";
					} else if (trimmedPreviousLine.StartsWith ("*", StringComparison.Ordinal)) {
						commentPrefix = "*";
					}

					int indentSize = line.GetIndentation (textEditorData.Document).Length;
					var insertedText = prevLine.GetIndentation (textEditorData.Document) + commentPrefix;
					textEditorData.Replace (line.Offset, indentSize, insertedText);
					textEditorData.Caret.Offset = line.Offset + insertedText.Length;
					return true;
				} else if (stateTracker.Engine.IsInsideStringLiteral) {
					var lexer = new CSharpCompletionEngineBase.MiniLexer (textEditorData.Document.GetTextAt (0, prevLine.EndOffset));
					lexer.Parse ();
					if (!lexer.IsInString)
						return false;
					textEditorData.EnsureCaretIsNotVirtual ();
					textEditorData.Insert (prevLine.Offset + prevLine.Length, "\" +");

					int indentSize = line.GetIndentation (textEditorData.Document).Length;
					var insertedText = prevLine.GetIndentation (textEditorData.Document) + (trimmedPreviousLine.StartsWith ("\"", StringComparison.Ordinal) ? "" : "\t") + "\"";
					textEditorData.Replace (line.Offset, indentSize, insertedText);
					return true;
				}
			}
			return false;
		}
Example #38
0
        public override void AddLocalNamespaceImport(RefactorerContext ctx, string fileName, string nsName, DomLocation caretLocation)
        {
            IEditableTextFile file        = ctx.GetFile(fileName);
            int            pos            = 0;
            ParsedDocument parsedDocument = parser.Parse(ctx.ParserContext, fileName, file.Text);
            StringBuilder  text           = new StringBuilder();
            string         indent         = "";

            if (parsedDocument.CompilationUnit != null)
            {
                IUsing containingUsing = null;
                foreach (IUsing u in parsedDocument.CompilationUnit.Usings)
                {
                    if (u.IsFromNamespace && u.Region.Contains(caretLocation))
                    {
                        containingUsing = u;
                    }
                }

                if (containingUsing != null)
                {
                    indent = GetLineIndent(file, containingUsing.Region.Start.Line);

                    IUsing lastUsing = null;
                    foreach (IUsing u in parsedDocument.CompilationUnit.Usings)
                    {
                        if (u == containingUsing)
                        {
                            continue;
                        }
                        if (containingUsing.Region.Contains(u.Region))
                        {
                            if (u.IsFromNamespace)
                            {
                                break;
                            }
                            lastUsing = u;
                        }
                    }

                    if (lastUsing != null)
                    {
                        pos = file.GetPositionFromLineColumn(lastUsing.Region.End.Line, lastUsing.Region.End.Column);
                    }
                    else
                    {
                        pos = file.GetPositionFromLineColumn(containingUsing.ValidRegion.Start.Line, containingUsing.ValidRegion.Start.Column);
                        // search line end
                        while (pos < file.Length)
                        {
                            char ch = file.GetCharAt(pos);
                            if (ch == '\n')
                            {
                                if (file.GetCharAt(pos + 1) == '\r')
                                {
                                    pos++;
                                }
                                break;
                            }
                            else if (ch == '\r')
                            {
                                break;
                            }
                            pos++;
                        }
                    }
                }
                else
                {
                    AddGlobalNamespaceImport(ctx, fileName, nsName);
                    return;
                }
            }
            if (pos != 0)
            {
                text.AppendLine();
            }
            text.Append(indent);
            text.Append("\t");
            text.Append("using ");
            text.Append(nsName);
            text.Append(";");
            if (file is Mono.TextEditor.ITextEditorDataProvider)
            {
                Mono.TextEditor.TextEditorData data = ((Mono.TextEditor.ITextEditorDataProvider)file).GetTextEditorData();
                if (pos == 0)
                {
                    text.Append(data.EolMarker);
                }
                int caretOffset   = data.Caret.Offset;
                int insertedChars = data.Insert(pos, text.ToString());
                if (pos < caretOffset)
                {
                    data.Caret.Offset = caretOffset + insertedChars;
                }
            }
            else
            {
                if (pos == 0)
                {
                    text.AppendLine();
                }
                file.InsertText(pos, text.ToString());
            }
        }
Example #39
0
		static int PastePlainText (TextEditorData data, int offset, string text)
		{
			int inserted;
			using (var undo = data.OpenUndoGroup ()) {
				var version = data.Document.Version;
				data.DeleteSelectedText (!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
				data.EnsureCaretIsNotVirtual ();
				offset = version.MoveOffsetTo (data.Document.Version, offset);
				inserted = data.Insert (offset, text);
			}
			data.PasteText (offset, text, inserted);
			return inserted;
		}
Example #40
0
		static int PasteFrom (Clipboard clipboard, TextEditorData data, bool preserveSelection, int insertionOffset, bool preserveState)
		{
			int result = -1;
			if (!data.CanEdit (data.Document.OffsetToLineNumber (insertionOffset)))
				return result;
			if (clipboard.WaitIsTargetAvailable (CopyOperation.MD_ATOM)) {
				clipboard.RequestContents (CopyOperation.MD_ATOM, delegate(Clipboard clp, SelectionData selectionData) {
					if (selectionData.Length > 0) {
						byte[] selBytes = selectionData.Data;
						var upperBound = System.Math.Max (0, System.Math.Min (selBytes [1], selBytes.Length - 2));
						byte[] copyData = new byte[upperBound];
						Array.Copy (selBytes, 2, copyData, 0, copyData.Length);
						var rawTextOffset = 1 + 1 + copyData.Length;
						string text = Encoding.UTF8.GetString (selBytes, rawTextOffset, selBytes.Length - rawTextOffset);
						bool pasteBlock = (selBytes [0] & 1) == 1;
						bool pasteLine = (selBytes [0] & 2) == 2;
						if (pasteBlock) {
							using (var undo = data.OpenUndoGroup ()) {
								var version = data.Document.Version;
								if (!preserveSelection)
									data.DeleteSelectedText (!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
								int startLine = data.Caret.Line;
								data.EnsureCaretIsNotVirtual ();
								insertionOffset = version.MoveOffsetTo (data.Document.Version, insertionOffset);

								data.Caret.PreserveSelection = true;
								var lines = new List<string> ();
								int offset = 0;
								while (true) {
									var delimiter = LineSplitter.NextDelimiter (text, offset);
									if (delimiter.IsInvalid)
										break;

									int delimiterEndOffset = delimiter.EndOffset;
									lines.Add (text.Substring (offset, delimiter.Offset - offset));
									offset = delimiterEndOffset;
								}
								if (offset < text.Length)
									lines.Add (text.Substring (offset, text.Length - offset));

								int lineNr = data.Document.OffsetToLineNumber (insertionOffset);
								int col = insertionOffset - data.Document.GetLine (lineNr).Offset;
								int visCol = data.Document.GetLine (lineNr).GetVisualColumn (data, col);
								DocumentLine curLine;
								int lineCol = col;
								result = 0;
								for (int i = 0; i < lines.Count; i++) {
									while (data.Document.LineCount <= lineNr + i) {
										data.Insert (data.Document.TextLength, Environment.NewLine);
										result += Environment.NewLine.Length;
									}
									curLine = data.Document.GetLine (lineNr + i);
									if (lines [i].Length > 0) {
										lineCol = curLine.GetLogicalColumn (data, visCol);
										if (curLine.Length + 1 < lineCol) {
											result += lineCol - curLine.Length;
											data.Insert (curLine.Offset + curLine.Length, new string (' ', lineCol - curLine.Length));
										}
										data.Insert (curLine.Offset + lineCol, lines [i]);
										result += lines [i].Length;
									}
									if (!preserveState)
										data.Caret.Offset = curLine.Offset + lineCol + lines [i].Length;
								}
								if (!preserveState)
									data.ClearSelection ();
								data.FixVirtualIndentation (startLine); 
								data.Caret.PreserveSelection = false;
							}
						} else if (pasteLine) {
							using (var undo = data.OpenUndoGroup ()) {
								if (!preserveSelection)
									data.DeleteSelectedText (!data.IsSomethingSelected || data.MainSelection.SelectionMode != SelectionMode.Block);
								data.EnsureCaretIsNotVirtual ();

								data.Caret.PreserveSelection = true;
								result = text.Length;
								DocumentLine curLine = data.Document.GetLine (data.Caret.Line);

								result = PastePlainText (data, curLine.Offset,  text + data.EolMarker, preserveSelection, copyData);
								if (!preserveState)
									data.ClearSelection ();
								data.Caret.PreserveSelection = false;
								data.FixVirtualIndentation (curLine.LineNumber); 
							}
						} else {
							result = PastePlainText (data, insertionOffset, text, preserveSelection, copyData);
						}
					}
				});
				// we got MD_ATOM text - no need to request text. (otherwise buffer may get copied twice).
				return result;
			}
			
			if (result < 0 && clipboard.WaitIsTextAvailable ()) {
				clipboard.RequestText (delegate(Clipboard clp, string text) {
					if (string.IsNullOrEmpty (text))
						return;
					result = PastePlainText (data, insertionOffset, text, preserveSelection);
				});
			}
			
			return result;
		}
		public int Insert (TextEditorData editor, string text)
		{
			int offset = editor.Document.LocationToOffset (Location);
			using (var undo = editor.OpenUndoGroup ()) {
				text = editor.FormatString (Location, text);
				
				DocumentLine line = editor.Document.GetLineByOffset (offset);
				int insertionOffset = line.Offset + Location.Column - 1;
				offset = insertionOffset;
				InsertNewLine (editor, LineBefore, ref offset);
				int result = offset - insertionOffset;

				offset += editor.Insert (offset, text);
				InsertNewLine (editor, LineAfter, ref offset);
				return result;
			}
		}
Example #42
0
        /// <summary>
        /// Don't use this unless you're implementing ICodeTemplateWidget. Use Insert instead.
        /// </summary>

/*		public TemplateResult InsertTemplateContents (TextEditor editor)//(MonoDevelop.Ide.Gui.Document document)
 *              {
 *                      //ProjectDom dom = document.Dom;
 *                      //ParsedDocument doc = document.ParsedDocument ?? MonoDevelop.Projects.Dom.Parser.ProjectDomService.GetParsedDocument (dom, document.FileName);
 *                      //MonoDevelop.Ide.Gui.TextEditor editor = document.TextEditor;
 *
 *                      Mono.TextEditor.TextEditorData data = editor.GetTextEditorData();
 *
 *                      int offset = data.Caret.Offset;
 *                      int line, col;
 *                      editor.GetLineColumnFromPosition (offset, out line, out col);
 * //			string leadingWhiteSpace = GetLeadingWhiteSpace (editor, editor.CursorLine);
 *
 *                      TemplateContext context = new TemplateContext {
 *                              Template = this,
 *                              //Document = document,
 *                              //ProjectDom = dom,
 *                              //ParsedDocument = doc,
 *                              InsertPosition = new DomLocation (line, col),
 *                              LineIndent = GetIndent (editor, line, 0),
 *                              TemplateCode = IndentCode (Code, document.TextEditorData.EolMarker, GetIndent (editor, line, 0))
 *                      };
 *
 *                      if (data.IsSomethingSelected) {
 *                              int start = data.SelectionRange.Offset;
 *                              while (Char.IsWhiteSpace (data.Document.GetCharAt (start))) {
 *                                      start++;
 *                              }
 *                              int end = data.SelectionRange.EndOffset;
 *                              while (Char.IsWhiteSpace (data.Document.GetCharAt (end - 1))) {
 *                                      end--;
 *                              }
 *                              context.LineIndent = GetIndent (editor, data.Document.OffsetToLineNumber (start) + 1, 0);
 *                              context.SelectedText = RemoveIndent (data.Document.GetTextBetween (start, end), context.LineIndent);
 *                              data.Remove (start, end - start);
 *                              offset = start;
 *                      } else {
 *                              string word = GetWordBeforeCaret (editor).Trim ();
 *                              if (word.Length > 0)
 *                                      offset = DeleteWordBeforeCaret (editor);
 *                      }
 *
 *                      TemplateResult template = FillVariables (context);
 *                      template.InsertPosition = offset;
 *                      document.TextEditorData.Insert (offset, template.Code);
 *
 *                      if (template.CaretEndOffset >= 0) {
 *                              data.Caret.Offset = offset + template.CaretEndOffset;
 *                      } else {
 *                              data.Caret.Offset= offset + template.Code.Length;
 *                      }
 *                      return template;
 *              }*/

        public CodeTemplate.TemplateResult InsertTemplateContents(TextEditor editor)         //MonoDevelop.Ide.Gui.Document document)
        {
            //ProjectDom dom = document.Dom;
            //ParsedDocument doc = document.ParsedDocument ?? MonoDevelop.Projects.Dom.Parser.ProjectDomService.GetParsedDocument (dom, document.FileName);
            //Mono.TextEditor.TextEditorData data = document.Editor;
            Mono.TextEditor.TextEditorData data = editor.GetTextEditorData();

            int offset = data.Caret.Offset;
//			string leadingWhiteSpace = GetLeadingWhiteSpace (editor, editor.CursorLine);

            TemplateContext context = new TemplateContext {
                Template = this,
                Document = data,
                //ProjectDom = dom,
                //ParsedDocument = doc,
                InsertPosition = data.Caret.Location,
                LineIndent     = data.Document.GetLineIndent(data.Caret.Line),
                TemplateCode   = Code
            };

            if (editor.IsSomethingSelected)              //data.IsSomethingSelected
            {
                int start = data.SelectionRange.Offset;
                while (Char.IsWhiteSpace(data.Document.GetCharAt(start)))
                {
                    start++;
                }
                int end = data.SelectionRange.EndOffset;
                while (Char.IsWhiteSpace(data.Document.GetCharAt(end - 1)))
                {
                    end--;
                }
                context.LineIndent   = data.Document.GetLineIndent(data.Document.OffsetToLineNumber(start));
                context.SelectedText = RemoveIndent(data.Document.GetTextBetween(start, end), context.LineIndent);
                data.Remove(start, end - start);
                offset = start;
            }
            else
            {
                string word = GetWordBeforeCaret(editor).Trim();
                if (word.Length > 0)
                {
                    offset = DeleteWordBeforeCaret(editor);
                }
            }

            TemplateResult template = FillVariables(context);

            template.InsertPosition = offset;
            data.Insert(offset, template.Code);

            int newoffset;

            if (template.CaretEndOffset >= 0)
            {
                newoffset = offset + template.CaretEndOffset;
            }
            else
            {
                newoffset = offset + template.Code.Length;
            }
            editor.Caret.Location = editor.Document.OffsetToLocation(newoffset);

//			if (PropertyService.Get ("OnTheFlyFormatting", false)) {
//				string mt = DesktopService.GetMimeTypeForUri (document.FileName);
//				var formatter = MonoDevelop.Ide.CodeFormatting.CodeFormatterService.GetFormatter (mt);
//				if (formatter != null && formatter.SupportsOnTheFlyFormatting) {
//					document.Editor.Document.BeginAtomicUndo ();
//					formatter.OnTheFlyFormat (document.Project != null ? document.Project.Policies : null,
//						document.Editor, offset, offset + length);
//					document.Editor.Document.EndAtomicUndo ();
//				}
//			}
            return(template);
        }