aboutsummaryrefslogtreecommitdiffstatsci
path: root/CrowIDE/src/SourceEditor/CodeBuffer.cs
blob: 31739bdc4a09fff716e6ffb728eb00c12aa352ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//
//  CodeTextBuffer.cs
//
//  Author:
//       Jean-Philippe Bruyère <jp.bruyere@hotmail.com>
//
//  Copyright (c) 2017 jp
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Crow.Coding
{
	/// <summary>
	/// Code buffer, lines are arranged in a List<string>, new line chars are removed during string.split on '\n...',
	/// </summary>
	public class CodeBuffer
	{
		public object EditMutex = new object();
		//those events are handled in SourceEditor to help keeping sync between textbuffer,parser and editor.
		//modified lines are marked for reparse
		#region Events
		public event EventHandler<CodeBufferEventArgs> LineUpadateEvent;
		public event EventHandler<CodeBufferEventArgs> LineRemoveEvent;
		public event EventHandler<CodeBufferEventArgs> LineAdditionEvent;
		public event EventHandler<CodeBufferEventArgs> FoldingEvent;
		public event EventHandler BufferCleared;
		public event EventHandler SelectionChanged;
		public event EventHandler PositionChanged;
		#endregion

		#region CTOR
		public CodeBuffer () {

		}
		#endregion

		string lineBreak = Interface.LineBreak;
		List<CodeLine> lines = new List<CodeLine>();
		public int longestLineIdx = 0;
		public int longestLineCharCount = 0;
		/// <summary>
		/// real position in char arrays, tab = 1 char
		/// </summary>
		int _currentLine = 0;
		int _currentCol = 0;

		public int LineCount { get { return lines.Count;}}
		public int IndexOf (CodeLine cl) {
			return lines.IndexOf (cl);
		}

		public CodeLine this[int i]
		{
			get { return lines[i]; }
			set {
				if (lines [i] == value)
					return;
				lock (EditMutex) {
					lines [i] = value;
					LineUpadateEvent.Raise (this, new CodeBufferEventArgs (i));
				}
			}
		}

		public void RemoveAt(int i){
			lock (EditMutex) {
				lines.RemoveAt (i);
				LineRemoveEvent.Raise (this, new CodeBufferEventArgs (i));
			}
		}
		public void Insert(int i, string item){
			lock (EditMutex) {
				lines.Insert (i, item);
				LineAdditionEvent.Raise (this, new CodeBufferEventArgs (i));
			}
		}
		public void Add(CodeLine item){
			lock (EditMutex) {
				lines.Add (item);
				LineAdditionEvent.Raise (this, new CodeBufferEventArgs (lines.Count - 1));
			}
		}
		public void AddRange (string[] items){
			int start = lines.Count;
			lock (EditMutex) {
				for (int i = 0; i < items.Length; i++)
					lines.Add (items [i]);
				LineAdditionEvent.Raise (this, new CodeBufferEventArgs (start, items.Length));
			}
		}
		public void AddRange (CodeLine[] items){
			int start = lines.Count;
			lock (EditMutex) {
				lines.AddRange (items);
				LineAdditionEvent.Raise (this, new CodeBufferEventArgs (start, items.Length));
			}
		}
		public void Clear () {
			lock (EditMutex) {
				longestLineCharCount = 0;
				lines.Clear ();
				BufferCleared.Raise (this, null);
			}
		}
		public void UpdateLine(int i, string newContent){
			lock (EditMutex) {
				this [i].Content = newContent;
				LineUpadateEvent.Raise (this, new CodeBufferEventArgs (i));
			}
		}
		public void AppenedLine(int i, string newContent){
			lock (EditMutex) {
				this [i].Content += newContent;
				LineUpadateEvent.Raise (this, new CodeBufferEventArgs (i));
			}
		}
		public void ToogleFolding (int line) {
			if (!this [line].IsFoldable)
				return;
			lock (EditMutex) {
				this [line].IsFolded = !this [line].IsFolded;
				FoldingEvent.Raise (this, new CodeBufferEventArgs (line));
			}
		}
		public void Load(string rawSource) {
			this.Clear();

			if (string.IsNullOrEmpty (rawSource))
				return;

			AddRange (Regex.Split (rawSource, "\r\n|\r|\n|\\\\n"));

			lineBreak = detectLineBreakKind (rawSource);
		}

		/// <summary>
		/// Finds the longest visual line as printed on screen with tabulation replaced with n spaces
		/// </summary>
		public void FindLongestVisualLine(){
			longestLineCharCount = 0;
			for (int i = 0; i < this.LineCount; i++) {
				if (lines[i].PrintableLength > longestLineCharCount) {
					longestLineCharCount = lines[i].PrintableLength;
					longestLineIdx = i;
				}
			}
			Debug.WriteLine ("Longest line: {0}->{1}", longestLineIdx, longestLineCharCount);
		}
		/// <summary> line break could be '\r' or '\n' or '\r\n' </summary>
		static string detectLineBreakKind(string buffer){
			string strLB = "";

			if (string.IsNullOrEmpty(buffer))
				return Interface.LineBreak;
			int i = 0;
			while ( i < buffer.Length) {
				if (buffer [i] == '\r') {
					strLB += '\r';
					i++;
				}
				if (i < buffer.Length) {
					if (buffer [i] == '\r')
						return "\r";
					if (buffer[i] == '\n')
						strLB += '\n';
				}
				if (!string.IsNullOrEmpty (strLB))
					return strLB;
				i++;
			}
			return Interface.LineBreak;
		}
		/// <summary>
		/// return all lines with linebreaks
		/// </summary>
		public string FullText{
			get {
				if (lines.Count == 0)
					return "";
				string tmp = "";
				for (int i = 0; i < lines.Count -1; i++)
					tmp += lines [i].Content + this.lineBreak;
				tmp += lines [lines.Count - 1].Content;
				return tmp;
			}
		}

		/// <summary>
		/// unfolded and not in folds line count
		/// </summary>
		public int UnfoldedLines {
			get {
				int i = 0, vl = 0;
				while (i < LineCount) {
					if (this [i].IsFolded)
						i = GetEndNodeIndex (i);
					i++;
					vl++;
				}
				//Debug.WriteLine ("unfolded lines: " + vl);
				return vl;
			}
		}

		/// <summary>
		/// convert visual position to buffer position
		/// </summary>
		Point getBuffPos (Point visualPos) {
			int i = 0;
			int buffCol = 0;
			while (i < visualPos.X) {
				if (this [visualPos.Y] [buffCol] == '\t')
					i += Interface.TabSize;
				else
					i++;
				buffCol++;
			}
			return new Point (buffCol, visualPos.Y);
		}

		public int GetEndNodeIndex (int line) {
			return IndexOf (this [line].SyntacticNode.EndLine);
		}
		/// <summary>
		/// Gets visual position computed from actual buffer position
		/// </summary>
//		public Point TabulatedPosition {
//			get { return new Point (TabulatedColumn, _currentLine); }
//		}
		/// <summary>
		/// set buffer current position from visual position
		/// </summary>
//		public void SetBufferPos(Point tabulatedPosition) {
//			CurrentPosition = getBuffPos(tabulatedPosition);
//		}

		#region Editing and moving cursor
		Point selStartPos = -1;	//selection start (row,column)
		Point selEndPos = -1;	//selection end (row,column)

		public bool SelectionInProgress { get { return selStartPos >= 0; }}
		public void SetSelStartPos () {
			selStartPos = selEndPos = CurrentPosition;
			SelectionChanged.Raise (this, null);
		}
		public void SetSelEndPos () {
			selEndPos = CurrentPosition;
			SelectionChanged.Raise (this, null);
		}
		/// <summary>
		/// Set selection in buffer to -1, empty selection
		/// </summary>
		public void ResetSelection () {
			selStartPos = selEndPos = -1;
			SelectionChanged.Raise (this, null);
		}

		public string SelectedText {
			get {
				if (SelectionIsEmpty)
					return "";
				Point selStart = SelectionStart;
				Point selEnd = SelectionEnd;
				if (selStart.Y == selEnd.Y)
					return this [selStart.Y].Content.Substring (selStart.X, selEnd.X - selStart.X);
				string tmp = "";
				tmp = this [selStart.Y].Content.Substring (selStart.X);
				for (int l = selStart.Y + 1; l < selEnd.Y; l++) {
					tmp += Interface.LineBreak + this [l].Content;
				}
				tmp += Interface.LineBreak + this [selEnd.Y].Content.Substring (0, selEnd.X);
				return tmp;
			}
		}
		/// <summary>
		/// ordered selection start and end positions in char units
		/// </summary>
		public Point SelectionStart	{
			get { return selEndPos < 0 || selStartPos.Y < selEndPos.Y ? selStartPos :
					selStartPos.Y > selEndPos.Y ? selEndPos :
					selStartPos.X < selEndPos.X ? selStartPos : selEndPos; }
		}
		public Point SelectionEnd {
			get { return selEndPos < 0 || selStartPos.Y > selEndPos.Y ? selStartPos :
					selStartPos.Y < selEndPos.Y ? selEndPos :
					selStartPos.X > selEndPos.X ? selStartPos : selEndPos; }
		}
		public bool SelectionIsEmpty
		{ get { return selEndPos == selStartPos; } }
		/// <summary>
		/// Current column in buffer coordinate, tabulation = 1 char
		/// </summary>
		public int CurrentColumn{
			get { return _currentCol; }
			set {
				if (value == _currentCol)
					return;
				if (value < 0)
					_currentCol = 0;
				else if (value >  lines [_currentLine].Length)
					_currentCol = lines [_currentLine].Length;
				else
					_currentCol = value;

				PositionChanged.Raise (this, null);
			}
		}
		/// <summary>
		/// Current row in buffer coordinate, tabulation = 1 char
		/// </summary>
		public int CurrentLine{
			get { return _currentLine; }
			set {
				if (value == _currentLine)
					return;
				if (value >= lines.Count)
					_currentLine = lines.Count-1;
				else if (value < 0)
					_currentLine = 0;
				else
					_currentLine = value;

				if (_currentCol >  lines [_currentLine].Length)
					_currentCol = lines [_currentLine].Length;
				//Debug.WriteLine ("buff cur line: " + _currentLine);
				PositionChanged.Raise (this, null);
			}
		}
		public CodeLine CurrentCodeLine {
			get { return this [_currentLine]; }
		}
		/// <summary>
		/// Current position in buffer coordinate, tabulation = 1 char
		/// </summary>
		public Point CurrentPosition {
			get { return new Point(CurrentColumn, CurrentLine); }
//			set {
//				_currentCol = value.X;
//				_currentLine = value.Y;
//			}
		}
		/// <summary>
		/// get char at current position in buffer
		/// </summary>
		protected Char CurrentChar { get { return lines [CurrentLine] [CurrentColumn]; } }

		public void GotoWordStart(){
			if (this[CurrentLine].Length == 0)
				return;
			CurrentColumn--;
			//skip white spaces
			while (!char.IsLetterOrDigit (this.CurrentChar) && CurrentColumn > 0)
				CurrentColumn--;
			while (char.IsLetterOrDigit (this.CurrentChar) && CurrentColumn > 0)
				CurrentColumn--;
			if (!char.IsLetterOrDigit (this.CurrentChar))
				CurrentColumn++;
		}
		public void GotoWordEnd(){
			//skip white spaces
			if (CurrentColumn >= this [CurrentLine].Length - 1)
				return;
			while (!char.IsLetterOrDigit (this.CurrentChar) && CurrentColumn < this [CurrentLine].Length-1)
				CurrentColumn++;
			while (char.IsLetterOrDigit (this.CurrentChar) && CurrentColumn < this [CurrentLine].Length-1)
				CurrentColumn++;
			if (char.IsLetterOrDigit (this.CurrentChar))
				CurrentColumn++;
		}
		public void DeleteChar()
		{
			lock (EditMutex) {
				if (SelectionIsEmpty) {
					if (CurrentColumn == 0) {
						if (CurrentLine == 0)
							return;
						CurrentLine--;
						CurrentColumn = this [CurrentLine].Length;
						AppenedLine (CurrentLine, this [CurrentLine + 1].Content);
						RemoveAt (CurrentLine + 1);
						return;
					}
					CurrentColumn--;
					UpdateLine (CurrentLine, this [CurrentLine].Content.Remove (CurrentColumn, 1));
				} else {
					int linesToRemove = SelectionEnd.Y - SelectionStart.Y + 1;
					int l = SelectionStart.Y;

					if (linesToRemove > 0) {
						UpdateLine (l, this [l].Content.Remove (SelectionStart.X, this [l].Length - SelectionStart.X) +
						this [SelectionEnd.Y].Content.Substring (SelectionEnd.X, this [SelectionEnd.Y].Length - SelectionEnd.X));
						l++;
						for (int c = 0; c < linesToRemove - 1; c++)
							RemoveAt (l);
						CurrentLine = SelectionStart.Y;
						CurrentColumn = SelectionStart.X;
					} else
						UpdateLine (l, this [l].Content.Remove (SelectionStart.X, SelectionEnd.X - SelectionStart.X));
					CurrentColumn = SelectionStart.X;
					ResetSelection ();
				}
			}
		}
		/// <summary>
		/// Insert new string at caret position, should be sure no line break is inside.
		/// </summary>
		/// <param name="str">String.</param>
		public void Insert(string str)
		{
			if (!SelectionIsEmpty)
				this.DeleteChar ();
			string[] strLines = Regex.Split (str, "\r\n|\r|\n|" + @"\\n").ToArray();
			UpdateLine (CurrentLine, this [CurrentLine].Content.Insert (CurrentColumn, strLines[0]));
			CurrentColumn += strLines[0].Length;
			for (int i = 1; i < strLines.Length; i++) {
				InsertLineBreak ();
				UpdateLine (CurrentLine, this [CurrentLine].Content.Insert (CurrentColumn, strLines[i]));
				CurrentColumn += strLines[i].Length;
			}
		}
		/// <summary>
		/// Insert a line break.
		/// </summary>
		public void InsertLineBreak()
		{
			if (CurrentColumn > 0) {
				Insert (CurrentLine + 1, this [CurrentLine].Content.Substring (CurrentColumn));
				UpdateLine (CurrentLine, this [CurrentLine].Content.Substring (0, CurrentColumn));
			} else
				Insert(CurrentLine, "");

			CurrentColumn = 0;
			CurrentLine++;
		}
		#endregion
	}
}