Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TextUtilities.cs « TextDataUtil « Util « Text « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 26aa19a0b075b0d5c6d3a518b344908ed69d8f86 (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
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  Licensed under the MIT License. See License.txt in the project root for license information.
//
namespace Microsoft.VisualStudio.Text.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Diagnostics;
    using System.Threading.Tasks;

    /// <summary>
    /// Handy text-oriented utilities.
    /// </summary>
    internal static class TextUtilities
    {
        public static readonly Task CompletedNonInliningTask = CreateCompletedNonInliningTask();

        private static Task CreateCompletedNonInliningTask()
        {
            var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
            tcs.SetResult(null);
            return tcs.Task;
        }

        public static Span? Overlap(this Span span, Span? otherSpan)
        {
            return otherSpan != null ? span.Overlap(otherSpan.Value) : null;
        }

        public static int LengthOfLineBreak(string source, int start, int end)
        {
            char c1 = source[start];
            if (c1 == '\r')
            {
                return ((++start < end) && (source[start] == '\n')) ? 2 : 1;
            }
            else if ((c1 == '\n') || (c1 == '\u0085') ||
                     (c1 == '\u2028' /*unicode line separator*/) ||
                     (c1 == '\u2029' /*unicode paragraph separator*/))
            {
                return 1;
            }
            else
                return 0;
        }

        public static int LengthOfLineBreak(char[] source, int start, int end)
        {
            char c1 = source[start];
            if (c1 == '\r')
            {
                return ((++start < end) && (source[start] == '\n')) ? 2 : 1;
            }
            else if ((c1 == '\n') || (c1 == '\u0085') ||
                     (c1 == '\u2028' /*unicode line separator*/) ||
                     (c1 == '\u2029' /*unicode paragraph separator*/))
            {
                return 1;
            }
            else
                return 0;
        }

        /// <summary>
        /// A utility function that returns the number of lines in a given block of 
        /// text
        ///
        /// We honor the MAC, UNIX and PC way of line counting.
        /// 
        /// 0x2028, 0x2929, 0x85, \r, \n and \r\n are considered as valid line breaks.  However, \n\r is not
        /// (that is to say, \n\r comprises TWO line breaks).
        /// </summary>
        static public int ScanForLineCount(string text)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            int lines = 0;
            for (int i = 0; i < text.Length; )
            {
                int breakLength = LengthOfLineBreak(text, i, text.Length);
                if (breakLength > 0)
                {
                    ++lines;
                    i += breakLength;
                }
                else
                    ++i;
            }

            return lines;
        }

        /// <summary>
        /// A utility function that returns the number of lines in a given block of text.
        ///
        /// We honor the MAC, UNIX and PC way of line counting.
        /// 
        /// 0x2028, 0x2929, 0x85, \r, \n and \r\n are considered as valid line breaks.  However, \n\r is not
        /// (that is to say, \n\r comprises TWO line breaks).
        /// </summary>
        static public int ScanForLineCount(char[] text, int start, int length)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            int lines = 0;
            for (int i = 0; i < length; )
            {
                int breakLength = LengthOfLineBreak(text, start + i, length);
                if (breakLength > 0)
                {
                    ++lines;
                    i += breakLength;
                }
                else
                    ++i;
            }

            return lines;
        }

        /// <summary>
        /// Perform stable merge sort on <paramref name="elements"/>.
        /// </summary>
        /// <param name="elements">List of elements to be sorted.</param>
        /// <param name="comparer">He who knows how to compare elements.</param>
        /// <returns>Array of parameter T sorted in ascending order.</returns>
        static public T[] StableSort<T>(IReadOnlyList<T> elements, Comparison<T> comparer)
        {
            int count = elements.Count;
            T[] target = new T[count];
            bool alreadySorted = true;
            if (count > 0)
            {
                target[0] = elements[0];
                for (int i = 1; i < count; ++i)
                {
                    target[i] = elements[i];
                    // check for already-sorted array; quite likely in applicable text editor scenarios
                    if (comparer(target[i - 1], target[i]) > 0)
                    {
                        alreadySorted = false;
                    }
                }
            }
            if (alreadySorted)
            {
                return target;
            }
            else
            {
                // do a merge sort

                T[] source = new T[count];
                int subcount = 1;     // the length of the subsequences to merge
                while (subcount < count)
                {
                    T[] t = source;
                    source = target;
                    target = t;

                    MergePass(source, target, subcount, comparer);

                    subcount *= 2;
                }
#if DEBUG
                // trust, but verify
                for (int i = 1; i < count; ++i)
                {
                    System.Diagnostics.Debug.Assert(comparer(target[i - 1], target[i]) <= 0);
                }
#endif
                return target;
            }
        }

        /// <summary>
        /// Make one pass over <paramref name="source"/>, merging runs of size <paramref name="subcount"/> into <paramref name="target"/>.
        /// </summary>
        /// <param name="source">Array containing sorted runs of size <paramref name="subcount"/>.</param>
        /// <param name="target">Array into which runs of size 2 * <paramref name="subcount"/> will be placed.</param>
        /// <param name="subcount">Size of sorted runs that will be generated into <paramref name="target"/>.</param>
        /// <param name="comparer">He who knows how to compare elements.</param>
        static private void MergePass<T>(T[] source, T[] target, int subcount, Comparison<T> comparer)
        {
            int offset = 0;     // offset of the pair of subsequences that are being merged
            while (offset <= source.Length - 2 * subcount)
            {
                Merge(source, target, offset, offset + subcount, offset + 2 * subcount, comparer);
                offset += 2 * subcount;
            }
            if (offset + subcount < source.Length)
            {
                // two subsequences remain, but the second one is smaller than subcount
                Merge(source, target, offset, offset + subcount, source.Length, comparer);
            }
            else
            {
                // only one (already sorted) subsequence remains; copy it across
                for (int i = offset; i < source.Length; ++i)
                {
                    target[i] = source[i];
                }
            }
        }

        /// <summary>
        /// Merge two ordered runs from <paramref name="source"/> array into <paramref name="target"/> array.
        /// </summary>
        /// <param name="source">Array containing input runs.</param>
        /// <param name="target">Array into which output run is placed.</param>
        /// <param name="left">Starting position of first source run.</param>
        /// <param name="right">Starting position of second source run.</param>
        /// <param name="end">First position past second source run.</param>
        /// <param name="comparer">He who knows how to compare elements.</param>
        static private void Merge<T>(T[] source, T[] target, int left, int right, int end, Comparison<T> comparer)
        {
            int s1 = left;
            int s2 = right;
            int t = left;
            while (s1 < right && s2 < end)
            {
                target[t++] = (comparer(source[s1], source[s2]) <= 0) ? source[s1++] : source[s2++];
            }
            if (s1 == right)
            {
                // copy any leftovers from second source run.
                for (int i = t; i < end; ++i)
                {
                    target[i] = source[s2++];
                }
            }
            else
            {
                // copy any leftovers from first source run.
                for (int i = t; i < end; ++i)
                {
                    target[i] = source[s1++];
                }
            }
        }

        /// <summary>
        /// Associate a string-valued tag with the buffer for diagnostic purposes.
        /// </summary>
        /// <param name="buffer">The <see cref="ITextBuffer"/> of interest.</param>
        /// <param name="tag">Informative tag to associate with the buffer.</param>
        /// <exception cref="ArgumentNullException">if <paramref name="buffer"/> is null.</exception>
        /// <exception cref="ArgumentNullException">if <paramref name="tag"/> is null.</exception>
        /// <remarks>If the buffer already has a tag, the new tag is concatenated to it (with an intervening "::".</remarks>
        public static void TagBuffer(ITextBuffer buffer, string tag)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (tag == null)
            {
                throw new ArgumentNullException("tag");
            }
            string existingTag = "";
            if (!buffer.Properties.TryGetProperty<string>("tag", out existingTag))
            {
                buffer.Properties.AddProperty("tag", tag);
            }
            else
            {
                buffer.Properties["tag"] = existingTag + "::" + tag;
            }
        }

        /// <summary>
        /// Return the string-valued tag previously associated with the buffer by <see cref="TagBuffer"/>.
        /// </summary>
        /// <param name="buffer">The <see cref="ITextBuffer"/> of interest.</param>
        /// <returns>The previously associated tag, or "" if no tag has been associated.</returns>
        /// <exception cref="ArgumentNullException">if <paramref name="buffer"/> is null.</exception>
        public static string GetTag(ITextBuffer buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            string tag = "";
            buffer.Properties.TryGetProperty<string>("tag", out tag);
            return tag;
        }

        public static string GetTagOrContentType(ITextBuffer buffer)
        {
            return GetTag(buffer) ?? buffer.ContentType.TypeName;
        }

        public static string Escape(string text)
        {
            StringBuilder result = new StringBuilder();
            for (int c = 0; c < text.Length; ++c)
            {
                char ch = text[c];
                AppendChar(result, ch);
            }
            return result.ToString();
        }

        public static string Escape(string text, int truncateLength)
        {
            StringBuilder result = new StringBuilder();
            if (text.Length <= truncateLength)
            {
                return Escape(text);
            }
            else
            {
                for (int c = 0; c < truncateLength / 2; ++c)
                {
                    char ch = text[c];
                    AppendChar(result, ch);
                }
                result.Append(" � ");
                for (int c = text.Length - (truncateLength / 2); c < text.Length; ++c)
                {
                    char ch = text[c];
                    AppendChar(result, ch);
                }
            }
            return result.ToString();
        }

        private static void AppendChar(StringBuilder result, char ch)
        {
            switch (ch)
            {
                case '\\':
                    result.Append(@"\\");
                    break;
                case '\r':
                    result.Append(@"\r");
                    break;
                case '\n':
                    result.Append(@"\n");
                    break;
                case '\t':
                    result.Append(@"\t");
                    break;
                case '"':
                    result.Append("\\\"");
                    break;
                default:
                    result.Append(ch);
                    break;
            }
        }

        internal static void RaiseEvent(object sender, EventHandler eventHandlers, IEnumerable<IExtensionErrorHandler> errorHandlers)
        {
            if (eventHandlers == null)
                return;

            var handlers = eventHandlers.GetInvocationList();

            foreach (EventHandler handler in handlers)
            {
                try
                {
                    handler(sender, EventArgs.Empty);
                }
                catch (Exception e)
                {
                    HandleException(sender, e, errorHandlers);
                }
            }
        }

        internal static void RaiseEvent<TArgs>(object sender, EventHandler<TArgs> eventHandlers, TArgs args,
            IEnumerable<IExtensionErrorHandler> errorHandlers) where TArgs : EventArgs
        {
            if (eventHandlers == null)
                return;

            var handlers = eventHandlers.GetInvocationList();

            foreach (EventHandler<TArgs> handler in handlers)
            {
                try
                {
                    handler(sender, args);
                }
                catch (Exception e)
                {
                    HandleException(sender, e, errorHandlers);
                }
            }
        }

        internal static void CallExtensionPoint(object errorSource, Action call, IEnumerable<IExtensionErrorHandler> errorHandlers)
        {
            try
            {
                call();
            }
            catch (Exception e)
            {
                HandleException(errorSource, e, errorHandlers);
            }
        }

        internal static void HandleException(object errorSource, Exception e, IEnumerable<IExtensionErrorHandler> errorHandlers)
        {
            bool handled = false;
            if (errorHandlers != null)
            {
                foreach (var errorHandler in errorHandlers)
                {
                    try
                    {
                        errorHandler.HandleError(errorSource, e);
                        handled = true;
                    }
                    catch (Exception doubleFaultException)
                    {
                        // TODO: What is the right behavior here?
                        Debug.Fail(doubleFaultException.ToString());
                    }
                }
            }
            if (!handled)
            {
                // TODO: What is the right behavior here?
                Debug.Fail(e.ToString());
            } 
        }
    }
}