/// <summary>
        /// 获取行尾类型
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        public static LineEnding GetLineEnding(string line)
        {
            LineEnding ending = LineEnding.Others;

            if (line.Length == 1)
            {
                switch (line[0])
                {
                case '\n': ending = LineEnding.LF; break;

                case '\r': ending = LineEnding.CR; break;
                }
            }
            else
            {
                char last1 = line[line.Length - 1];
                char last2 = line[line.Length - 2];

                if (last2 == '\r' && last1 == '\n')
                {
                    ending = LineEnding.CRLF;
                }
                else if (last2 != '\r' && last1 == '\n')
                {
                    ending = LineEnding.LF;
                }
                else if (last2 != '\r' && last1 == '\r')
                {
                    ending = LineEnding.CR;
                }
            }

            return(ending);
        }
示例#2
0
        private void OpenNewTextEditor(string text,
                                       StorageFile file,
                                       long dateModifiedFileTime,
                                       Encoding encoding,
                                       LineEnding lineEnding)
        {
            //LoggingService.LogInfo("Opening a text editor.");
            var textEditor = new TextEditor
            {
                ExtensionProvider = _extensionProvider
            };

            textEditor.Init(new TextFile(text, encoding, lineEnding, dateModifiedFileTime), file);
            textEditor.Loaded           += TextEditor_Loaded;
            textEditor.Unloaded         += TextEditor_Unloaded;
            textEditor.SelectionChanged += TextEditor_SelectionChanged;
            textEditor.KeyDown          += TextEditorKeyDown;
            textEditor.EditorModificationStateChanged += TextEditor_OnEditorModificationStateChanged;
            textEditor.ModeChanged += TextEditor_ModeChanged;
            textEditor.FileModificationStateChanged += (sender, args) => { TextEditorFileModificationStateChanged?.Invoke(this, sender as TextEditor); };
            textEditor.LineEndingChanged            += (sender, args) => { TextEditorLineEndingChanged?.Invoke(this, sender as TextEditor); };
            textEditor.EncodingChanged += (sender, args) => { TextEditorEncodingChanged?.Invoke(this, sender as TextEditor); };

            var newItem = new SetsViewItem
            {
                Header  = file == null ? DefaultNewFileName : file.Name,
                Content = textEditor,
                SelectionIndicatorForeground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush,
                Icon = new SymbolIcon(Symbol.Save)
                {
                    Foreground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush,
                }
            };

            if (newItem.Content == null || newItem.Content is Page)
            {
                throw new Exception("Content should not be null and type should not be Page (SetsView does not work well with Page controls)");
            }

            newItem.Icon.Visibility = Visibility.Collapsed;
            newItem.ContextFlyout   = new TabContextFlyout(this, textEditor);

            // Notepads should replace current "Untitled.txt" with open file if it is empty and it is the only tab that has been created.
            if (GetNumberOfOpenedTextEditors() == 1 && file != null)
            {
                var selectedEditor = GetAllTextEditors().First();
                if (selectedEditor.EditingFile == null && !selectedEditor.IsModified)
                {
                    Sets.Items?.Clear();
                }
            }

            Sets.Items?.Add(newItem);

            if (GetNumberOfOpenedTextEditors() > 1)
            {
                Sets.SelectedItem = newItem;
                Sets.ScrollToLastSet();
            }
        }
示例#3
0
            public void When_SpecificLineEnding(LineEnding lineEnding, string expectedOutput)
            {
                var writer = new StringWriter();

                lineEnding.WriteTo(writer);
                Assert.That(writer.ToString(), Is.EqualTo(expectedOutput));
            }
示例#4
0
 public TextFile(string content, Encoding encoding, LineEnding lineEnding, long dateModifiedFileTime)
 {
     Content              = content;
     Encoding             = encoding;
     LineEnding           = lineEnding;
     DateModifiedFileTime = dateModifiedFileTime;
 }
示例#5
0
        internal Line(Document document, int LineNo, string Text, HorizontalAlignment align, Font font, Color color,
                      Color back_color, TextPositioning text_position, float char_offset, float left_indent, float hanging_indent,
                      float right_indent, float spacing_before, float spacing_after, float line_spacing, bool line_spacing_multiple,
                      TabStopCollection tab_stops, bool visible, LineEnding ending) : this(document, ending)
        {
            space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length + 1 : DEFAULT_TEXT_LEN;

            text                       = new StringBuilder(Text, space);
            line_no                    = LineNo;
            this.ending                = ending;
            alignment                  = align;
            indent                     = left_indent;
            HangingIndent              = hanging_indent;
            this.right_indent          = right_indent;
            this.spacing_before        = spacing_before;
            this.spacing_after         = spacing_after;
            this.tab_stops             = tab_stops;
            this.line_spacing          = line_spacing;
            this.line_spacing_multiple = line_spacing_multiple;

            widths = new float[space + 1];


            tags              = new LineTag(this, 1);
            tags.Font         = font;
            tags.Color        = color;
            tags.BackColor    = back_color;
            tags.TextPosition = text_position;
            tags.CharOffset   = char_offset;
            tags.Visible      = visible;
        }
示例#6
0
        /// <summary>
        /// Increments the count for a specifica line ending by the provided number
        /// </summary>
        /// <param name="lineEnding">Line ending to be adjusted</param>
        /// <param name="count">May be any positive or negative value</param>
        public void Increment(LineEnding lineEnding, int count)
        {
            switch (lineEnding)
            {
            case LineEnding.CRLF:
                _crlf += count;
                break;

            case LineEnding.CR:
                _cr += count;
                break;

            case LineEnding.LF:
                _lf += count;
                break;

            case LineEnding.NEL:
                _nel += count;
                break;

            case LineEnding.LS:
                _ls += count;
                break;

            case LineEnding.PS:
                _ps += count;
                break;

            default:
                throw new ArgumentException($"Unknown line ending value {lineEnding}", nameof(lineEnding));
            }
        }
示例#7
0
 static TextToken CreateTextToken(string text, LineEnding lineEnding)
 {
     return(new TextToken()
     {
         Text = text, LineEnding = lineEnding
     });
 }
示例#8
0
 public override int GetHashCode()
 {
     return(17
            ^ EditorFontFamily.GetHashCode()
            ^ EditorFontSize.GetHashCode()
            ^ EditorHighlightCurrentLine.GetHashCode()
            ^ EditorOpenLastCursorPosition.GetHashCode()
            ^ EditorOpenLastFile.GetHashCode()
            ^ EditorShowEndOfLine.GetHashCode()
            ^ EditorShowLineNumbers.GetHashCode()
            ^ EditorShowSpaces.GetHashCode()
            ^ EditorShowTabs.GetHashCode()
            ^ EditorVerticalScrollBarVisible.GetHashCode()
            ^ SynchronizeScrollPositions.GetHashCode()
            ^ SpellCheckDictionary.GetHashCode()
            ^ SpellCheckIgnoreCodeBlocks.GetHashCode()
            ^ SpellCheckIgnoreMarkupTags.GetHashCode()
            ^ SpellCheckIgnoreWordsWithDigits.GetHashCode()
            ^ IgnoreYaml.GetHashCode()
            ^ IgnoreTaskbarOnMaximize.GetHashCode()
            ^ FormatOnSave.GetHashCode()
            ^ GitHubMarkdown.GetHashCode()
            ^ Theme.GetHashCode()
            ^ SinglePaneMargin.GetHashCode()
            ^ LineEnding.GetHashCode()
            ^ CustomMarkdownConverter.GetHashCode()
            ^ UseDefaultEditor.GetHashCode());
 }
示例#9
0
 public void AddLines(IEnumerable <string> contents, LineEnding lineEnding = LineEnding.Unknown)
 {
     foreach (var content in contents)
     {
         AddLine(content, lineEnding);
     }
 }
示例#10
0
        private static string GetLineEndingString(LineEnding lineEnding)
        {
            string result;

            switch (lineEnding)
            {
            case LineEnding.Windows:
                result = "\r\n";
                break;

            case LineEnding.Linux:
                result = "\n";
                break;

            case LineEnding.MacOs:
                result = "\r";
                break;

            default:
                result = "\n";
                break;
            }

            return(result);
        }
示例#11
0
 internal MarkdownProcessorContext(PSDocumentOption option, Document document)
 {
     Option   = option;
     Document = document;
     Builder  = new StringBuilder();
     _Ending  = LineEnding.None;
 }
示例#12
0
        public static void AnalyzeFile(string filename, out string oldEncodingName, out LineEnding oldEnding)
        {
            var    bytes = File.ReadAllBytes(filename);
            string text  = DecodeString(bytes, out oldEncodingName);

            oldEnding = DetermineLineEnding(text);
        }
示例#13
0
 public ConvertCommand(string filepath, Encoding enc, LineEnding endg, bool dontConvertEndings)
 {
     path             = filepath;
     newEncoding      = enc;
     newLineEnding    = endg;
     dontTouchEndings = dontConvertEndings;
 }
示例#14
0
 public override ITreeNode CreateNewLine(LineEnding lineEnding, NodeType lineBreakType = null) =>
 new T4Token(
     T4TokenNodeTypes.NEW_LINE,
     new StringBuffer(lineEnding.GetPresentation()),
     TreeOffset.Zero,
     new TreeOffset(lineEnding.GetPresentation().Length)
     );
        static void ForceLineEnding(string path, LineEnding ending)
        {
            var lines = File.ReadAllLines(path);

            var formatted = string.Join(LineEndingValue(ending), lines);

            File.WriteAllText(path, formatted);
        }
 private void UpdateLineEndingIndicator(LineEnding lineEnding)
 {
     if (StatusBar == null)
     {
         return;
     }
     LineEndingIndicator.Text = LineEndingUtility.GetLineEndingDisplayText(lineEnding);
 }
示例#17
0
 public LineFormatter(
     ICategoryFormatter categoryFormatter = null,
     bool doAsyncExceptionCleanup         = true,
     LineEnding lineEnding = LineEnding.CRLF)
 {
     _categoryFormatter       = categoryFormatter;
     _doAsyncExceptionCleanup = doAsyncExceptionCleanup;
     _lineEnding = lineEnding;
 }
示例#18
0
            public void When_WithTypeKeyLineEndingAndValue(InstructionType type, LineEnding lineEnding)
            {
                var instruction = new InstructionToken(type, "key", "value", lineEnding);

                Assert.That(instruction.InstructionType, Is.EqualTo(type));
                Assert.That(instruction.Key, Is.EqualTo("key"));
                Assert.That(instruction.Value, Is.EqualTo("value"));
                Assert.That(instruction.LineEnding, Is.EqualTo(lineEnding));
            }
示例#19
0
        public static void WriteLine(this IUART uart, string text, LineEnding lineEnding = LineEnding.CR)
        {
            foreach (var chr in text)
            {
                uart.WriteChar((byte)chr);
            }

            WriteLineEnding(uart, lineEnding);
        }
        /// <summary>
        /// Normalizes occurrences of "\r", "\n", and "\r\n" to the desired style.
        /// </summary>
        public static string Normalize(string input, LineEnding style)
        {
            if (input == null)
                return null;

            string ending;
            switch (style)
            {
                case LineEnding.CR:
                    ending = "\r"; break;
                case LineEnding.CRLF:
                    ending = "\r\n"; break;
                case LineEnding.LF:
                    ending = "\n"; break;
                default:
                    throw new ArgumentException("Unexpected style type", "style");
            }

            StringBuilder result = null;
            int len = input.Length;
            for (int i = 0; i < len; i++)
            {
                char c = input[i];
                switch (c)
                {
                    case '\r':
                    case '\n':
                        bool isCrLf = c == '\r' && input.Length > i + 1 && input[i + 1] == '\n';

                        if (result == null && !IsMatch(style, c, isCrLf))
                        {
                            // line ending is different; will need to return
                            // a result that is different than the input
                            result = new StringBuilder(style == LineEnding.CRLF ? (int)(input.Length * 1.1) : input.Length);
                            result.Append(input, 0, i);
                        }
                        if (result != null)
                        {
                            result.Append(ending);
                        }

                        if (isCrLf)
                            i++;
                        break;

                    default:
                        if (result != null)
                            result.Append(c);
                        break;
                }
            }

            if (result == null)
                return input;
            else
                return result.ToString();
        }
        public static void TestHelper(string input, string expectedOutput, LineEnding style)
        {
            string output = Normalize(input, style);

            if (output != expectedOutput)
            {
                Trace.Fail(string.Format(CultureInfo.InvariantCulture, "\"{0}\" != \"{1}\"", Escape(output), Escape(expectedOutput)));
            }
        }
示例#22
0
 public LineFormatter(
     ICategoryFormatter categoryFormatter = null, 
     bool doAsyncExceptionCleanup = true,
     LineEnding lineEnding = LineEnding.CRLF)
 {
     _categoryFormatter = categoryFormatter;
     _doAsyncExceptionCleanup = doAsyncExceptionCleanup;
     _lineEnding = lineEnding;
 }
示例#23
0
        internal void Write(char c, int count)
        {
            if (count == 0)
            {
                return;
            }

            _Ending = LineEnding.None;
            Builder.Append(c, count);
        }
示例#24
0
        private string TrimTextAndFixLineEnding(string text, LineEnding lineEnding)
        {
            // Trim end \r
            if (!string.IsNullOrEmpty(text) && text[text.Length - 1] == '\r')
            {
                text = text.Substring(0, text.Length - 1);
            }

            return(LineEndingUtility.ApplyLineEnding(text, lineEnding));
        }
示例#25
0
 public static string GetLineEndingTikz(this LineEnding lineEnding)
 {
     return(lineEnding switch
     {
         LineEnding.NONE => "-",
         LineEnding.BOTH => "<->",
         LineEnding.END => "->",
         LineEnding.START => "<-",
         _ => throw new ArgumentException("LineEnding cannot be converted"),
     });
示例#26
0
 /// <summary>
 /// Returns a string representation of the specified <paramref name="lineEnding"/>.
 /// </summary>
 /// <param name="lineEnding">The <see cref="LineEnding"/> to convert to a string.</param>
 /// <returns>A string representation of the <see cref="LineEnding"/>.</returns>
 public static string ToCharacters(this LineEnding lineEnding)
 {
     return(lineEnding switch
     {
         LineEnding.None => "",
         LineEnding.LineFeed => "\n",
         LineEnding.CarriageReturn => "\r",
         LineEnding.CarriageReturn | LineEnding.LineFeed => "\r\n",
         _ => throw new ArgumentOutOfRangeException(nameof(lineEnding), lineEnding, $"The value of argument '{nameof(lineEnding)}' ({lineEnding}) is invalid for enum type '{nameof(LineEnding)}'.")
     });
示例#27
0
        private void WriteDrawingStyleArrows(XmlTextWriter w, string key)
        {
            LineEnding             value = StyleElementLineEnding.Options[random.Next(StyleElementLineEnding.Options.Length)];
            StyleElementLineEnding style = new StyleElementLineEnding(value);

            w.WriteStartElement("Arrows");
            w.WriteAttributeString("Key", key);
            style.WriteXml(w);
            w.WriteEndElement();
        }
示例#28
0
 public void ChangeLineEnding(TextEditor textEditor, LineEnding lineEnding)
 {
     if (lineEnding == textEditor.LineEnding)
     {
         return;
     }
     textEditor.LineEnding = lineEnding;
     MarkTextEditorSetNotSaved(textEditor);
     OnTextEditorLineEndingChanged?.Invoke(this, textEditor);
 }
示例#29
0
        private void OpenNewTextEditor(string text,
                                       StorageFile file,
                                       Encoding encoding,
                                       LineEnding lineEnding)
        {
            var textEditor = new TextEditor()
            {
                EditingFile       = file,
                Encoding          = encoding,
                LineEnding        = lineEnding,
                Saved             = true,
                ExtensionProvider = _extensionProvider
            };

            textEditor.SetText(text);
            textEditor.ClearUndoQueue();
            textEditor.Loaded                 += TextEditor_Loaded;
            textEditor.Unloaded               += TextEditor_Unloaded;
            textEditor.TextChanging           += TextEditor_TextChanging;
            textEditor.SelectionChanged       += TextEditor_SelectionChanged;
            textEditor.KeyDown                += OnTextEditorKeyDown;
            textEditor.OnEditorClosingKeyDown += TextEditor_OnClosingKeyDown;

            var newItem = new SetsViewItem
            {
                Header  = file == null ? DefaultNewFileName : file.Name,
                Content = textEditor,
                SelectionIndicatorForeground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush,
                Icon = new SymbolIcon(Symbol.Save)
                {
                    Foreground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush,
                }
            };

            newItem.Icon.Visibility = Visibility.Collapsed;
            newItem.ContextFlyout   = new TabContextFlyout(this, textEditor);

            // Notepads should replace current "Untitled.txt" with open file if it is empty and it is the only tab that has been created.
            if (GetNumberOfOpenedTextEditors() == 1 && file != null)
            {
                var selectedEditor = GetSelectedTextEditor();
                if (selectedEditor.Saved && selectedEditor.EditingFile == null)
                {
                    Sets.Items?.Clear();
                }
            }

            Sets.Items?.Add(newItem);

            if (GetNumberOfOpenedTextEditors() > 1)
            {
                Sets.SelectedItem = newItem;
                Sets.ScrollToLastSet();
            }
        }
示例#30
0
        internal Line(Document document, int LineNo, string Text, LineTag tag, LineEnding ending) : this(document, ending)
        {
            space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length + 1 : DEFAULT_TEXT_LEN;

            text        = new StringBuilder(Text, space);
            this.ending = ending;
            line_no     = LineNo;

            widths = new float[space + 1];
            tags   = tag;
        }
 static string LineEndingValue(LineEnding ending)
 {
     switch (ending)
     {
         case LineEnding.Windows:
             return "\r\n";
         case LineEnding.Unix:
         default:
             return "\n";
     }
 }
示例#32
0
 public static string NormalizeLineEndings(this string s, LineEnding targetLineEnding = LineEnding.Lf)
 {
     if (targetLineEnding == LineEnding.Lf)
     {
         return(s.Replace("\r\n", "\n"));
     }
     else
     {
         throw new NotSupportedException();
     }
 }
示例#33
0
 public override void Write(TextWriter writer)
 {
     writer.Write(InstructionType.AsPrefixString());
     writer.Write(Key);
     if (Value != null)
     {
         writer.Write("=");
         writer.Write(Value);
     }
     LineEnding.WriteTo(writer);
 }
示例#34
0
 public static string NormalizeLineEndings(this string s, LineEnding targetLineEnding = LineEnding.Lf)
 {
     if (targetLineEnding == LineEnding.Lf)
     {
         return s.Replace("\r\n", "\n");
     }
     else
     {
         throw new NotSupportedException();
     }
 }
示例#35
0
        public static string[] GetStringLines(string data, LineEnding lineEnding)
        {
            if (data == null)
            {
                return(new string[0]);
            }

            var endLineString      = GetLineEndingString(lineEnding);
            var index              = 0;
            var beforeEndLineIndex = 0;
            var endLineBufIndex    = 0;
            var result             = new List <string>();

            while (index < data.Length)
            {
                for (var i = index; i < data.Length; ++i)
                {
                    if (endLineBufIndex < endLineString.Length)
                    {
                        if (endLineString[endLineBufIndex] == data[i])
                        {
                            if (endLineBufIndex == 0)
                            {
                                beforeEndLineIndex = i;
                            }

                            ++endLineBufIndex;
                        }

                        if (endLineBufIndex >= endLineString.Length)
                        {
                            if (index < data.Length)
                            {
                                var str = data.Substring(index, beforeEndLineIndex - index);
                                result.Add(str);
                            }
                            index = i + 1;
                            beforeEndLineIndex = i;
                            endLineBufIndex    = 0;
                        }
                    }
                }

                if (index < data.Length)
                {
                    var str = data.Substring(index, data.Length - index);
                    result.Add(str);
                    index = data.Length;
                }
            }

            return(result.ToArray());
        }
示例#36
0
		internal bool			recalc;			// Line changed
		#endregion	// Local Variables

		#region Constructors
		internal Line (Document document, LineEnding ending)
		{
			this.document = document; 
			color = LineColor.Red;
			left = null;
			right = null;
			parent = null;
			text = null;
			recalc = true;
			alignment = document.alignment;

			this.ending = ending;
		}
示例#37
0
		internal Line (Document document, int LineNo, string Text, Font font, Color color, LineEnding ending) : this (document, ending)
		{
			space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length+1 : DEFAULT_TEXT_LEN;

			text = new StringBuilder (Text, space);
			line_no = LineNo;
			this.ending = ending;

			widths = new float[space + 1];

			
			tags = new LineTag(this, 1);
			tags.Font = font;
			tags.Color = color;
		}
示例#38
0
        public Buffer(string str)
        {
            int cur = 0;
            int beg = 0;
            int numLF = 0;
            int numCRLF = 0;

            while (cur < str.Length)
            {
                if (str[cur] == '\n')
                {
                    Lines.Add(new Line(str.Substring(beg, cur - beg), LineEnding.LF));
                    cur += 1;
                    beg = cur;
                    numLF++;
                }
                else if (str[cur] == '\r' && cur + 1 < str.Length && str[cur + 1] == '\n')
                {
                    Lines.Add(new Line(str.Substring(beg, cur - beg), LineEnding.CRLF));
                    cur += 2;
                    beg = cur;
                    numCRLF++;
                }
                else
                {
                    cur++;
                }
            }

            if (numCRLF > numLF)
                DefaultEnding = LineEnding.CRLF;

            if (Lines.Count == 0)
                Lines.Add(new Line(str.Substring(beg, cur - beg), DefaultEnding));
            else
                Lines.Add(new Line(str.Substring(beg, cur - beg), Lines.Last().Ending));
        }
示例#39
0
		// Adds a line of text, with given font.
		// Bumps any line at that line number that already exists down
		internal void Add (int LineNo, string Text, Font font, Color color, LineEnding ending)
		{
			Add (LineNo, Text, alignment, font, color, ending);
		}
示例#40
0
文件: Line.cs 项目: Profit0004/mono
		private bool RecalculateLine (Graphics g, Document doc, bool handleKerning)
		{
			LineTag tag;
			int pos;
			int len;
			SizeF size;
			float w;
			int prev_offset;
			bool retval;
			bool wrapped;
			Line line;
			int wrap_pos;
			int prev_height;
			int prev_ascent;

			pos = 0;
			len = this.text.Length;
			tag = this.tags;
			prev_offset = this.offset;	// For drawing optimization calculations
			prev_height = this.height;
			prev_ascent = this.ascent;
			this.height = 0;		// Reset line height
			this.ascent = 0;		// Reset the ascent for the line
			tag.Shift = 0;			// Reset shift (which should be stored as pixels, not as points)

			if (ending == LineEnding.Wrap)
				widths[0] = document.left_margin + hanging_indent;
			else
				widths[0] = document.left_margin + indent;

			this.recalc = false;
			retval = false;
			wrapped = false;

			wrap_pos = 0;

			while (pos < len) {

				while (tag.Length == 0) {	// We should always have tags after a tag.length==0 unless len==0
					//tag.Ascent = 0;
					tag.Shift = (tag.Line.ascent - tag.Ascent) / 72;
					tag = tag.Next;
				}

				// kerning is a problem.  The original code in this method assumed that the
				// width of a string equals the sum of the widths of its characters.  This is
				// not true when kerning takes place during the display process.  Since it's
				// impossible to find out easily whether a font does kerning, and with which
				// characters, we just detect that kerning must have happened and use a slower
				// (but accurate) measurement for those fonts henceforth.  Without handling
				// kerning, many fonts for English become unreadable during typing for many
				// input strings, and text in many other languages is even worse trying to
				// type in TextBoxes.
				// See https://bugzilla.xamarin.com/show_bug.cgi?id=26478 for details.
				float newWidth;
				if (handleKerning && !Char.IsWhiteSpace(text[pos]))
				{
					// MeasureText doesn't measure trailing spaces, so we do the best we can for those
					// in the else branch.
					size = TextBoxTextRenderer.MeasureText (g, text.ToString (0, pos + 1), tag.Font);
					newWidth = widths[0] + size.Width;
				}
				else
				{
					size = tag.SizeOfPosition (g, pos);
					w = size.Width;
					newWidth = widths[pos] + w;
				}

				if (Char.IsWhiteSpace (text[pos]))
					wrap_pos = pos + 1;

				if (doc.wrap) {
					if ((wrap_pos > 0) && (wrap_pos != len) && (newWidth + 5) > (doc.viewport_width - this.right_indent)) {
						// Make sure to set the last width of the line before wrapping
						widths[pos + 1] = newWidth;

						pos = wrap_pos;
						len = text.Length;
						doc.Split (this, tag, pos);
						ending = LineEnding.Wrap;
						len = this.text.Length;

						retval = true;
						wrapped = true;
					} else if (pos > 1 && newWidth > (doc.viewport_width - this.right_indent)) {
						// No suitable wrap position was found so break right in the middle of a word

						// Make sure to set the last width of the line before wrapping
						widths[pos + 1] = newWidth;

						doc.Split (this, tag, pos);
						ending = LineEnding.Wrap;
						len = this.text.Length;
						retval = true;
						wrapped = true;
					}
				}

				// Contract all wrapped lines that follow back into our line
				if (!wrapped) {
					pos++;

					widths[pos] = newWidth;

					if (pos == len) {
						line = doc.GetLine (this.line_no + 1);
						if ((line != null) && (ending == LineEnding.Wrap || ending == LineEnding.None)) {
							// Pull the two lines together
							doc.Combine (this.line_no, this.line_no + 1);
							len = this.text.Length;
							retval = true;
						}
					}
				}

				if (pos == (tag.Start - 1 + tag.Length)) {
					// We just found the end of our current tag
					tag.Height = tag.MaxHeight ();

					// Check if we're the tallest on the line (so far)
					if (tag.Height > this.height)
						this.height = tag.Height;	// Yep; make sure the line knows

					if (tag.Ascent > this.ascent) {
						LineTag t;

						// We have a tag that has a taller ascent than the line;
						t = tags;
						while (t != null && t != tag) {
							t.Shift = (tag.Ascent - t.Ascent) / 72;
							t = t.Next;
						}

						// Save on our line
						this.ascent = tag.Ascent;
					} else {
						tag.Shift = (this.ascent - tag.Ascent) / 72;
					}

					tag = tag.Next;
					if (tag != null) {
						tag.Shift = 0;
						wrap_pos = pos;
					}
				}
			}

			var fullText = text.ToString();
			if (!handleKerning && fullText.Length > 1 && !wrapped)
			{
				// Check whether kerning takes place for this string and font.
				var realSize = TextBoxTextRenderer.MeasureText(g, fullText, tags.Font);
				float realWidth = realSize.Width + widths[0];
				// MeasureText ignores trailing whitespace, so we will too at this point.
				int length = fullText.TrimEnd().Length;
				float sumWidth = widths[length];
				if (realWidth != sumWidth)
				{
					kerning_fonts.Add(tags.Font.GetHashCode (), true);
					// Using a slightly incorrect width this time around isn't that bad. All that happens
					// is that the cursor is a pixel or two off until the next character is typed.  It's
					// the accumulation of pixel after pixel that causes display problems.
				}
			}

			while (tag != null) {	
				tag.Shift = (tag.Line.ascent - tag.Ascent) / 72;
				tag = tag.Next;
			}

			if (this.height == 0) {
				this.height = tags.Font.Height;
				tags.Height = this.height;
				tags.Shift = 0;
			}

			if (prev_offset != offset || prev_height != this.height || prev_ascent != this.ascent)
				retval = true;

			return retval;
		}
示例#41
0
		public override ITreeNode CreateNewLine(LineEnding lineEnding) {
			T4TokenNodeType nodeType = T4TokenNodeTypes.NewLine;
			return nodeType.Create(lineEnding.GetPresentation());
		}
示例#42
0
		/// <summary>
		/// Go through all tags on a line and recalculate all size-related values;
		/// returns true if lineheight changed
		/// </summary>
		internal bool RecalculateLine (Graphics g, Document doc)
		{
			LineTag tag;
			int pos;
			int len;
			SizeF size;
			float w;
			int prev_offset;
			bool retval;
			bool wrapped;
			Line line;
			int wrap_pos;
			int prev_height;
			int prev_ascent;

			pos = 0;
			len = this.text.Length;
			tag = this.tags;
			prev_offset = this.offset;	// For drawing optimization calculations
			prev_height = this.height;
			prev_ascent = this.ascent;
			this.height = 0;		// Reset line height
			this.ascent = 0;		// Reset the ascent for the line
			tag.Shift = 0;			// Reset shift (which should be stored as pixels, not as points)

			if (ending == LineEnding.Wrap)
				widths[0] = document.left_margin + hanging_indent;
			else
				widths[0] = document.left_margin + indent;

			this.recalc = false;
			retval = false;
			wrapped = false;

			wrap_pos = 0;

			while (pos < len) {

				while (tag.Length == 0) {	// We should always have tags after a tag.length==0 unless len==0
					//tag.Ascent = 0;
					tag.Shift = (tag.Line.ascent - tag.Ascent) / 72;
					tag = tag.Next;
				}

				size = tag.SizeOfPosition (g, pos);
				w = size.Width;

				if (Char.IsWhiteSpace (text[pos]))
					wrap_pos = pos + 1;

				if (doc.wrap) {
					if ((wrap_pos > 0) && (wrap_pos != len) && (widths[pos] + w) + 5 > (doc.viewport_width - this.right_indent)) {
						// Make sure to set the last width of the line before wrapping
						widths[pos + 1] = widths[pos] + w;

						pos = wrap_pos;
						len = text.Length;
						doc.Split (this, tag, pos);
						ending = LineEnding.Wrap;
						len = this.text.Length;

						retval = true;
						wrapped = true;
					} else if (pos > 1 && (widths[pos] + w) > (doc.viewport_width - this.right_indent)) {
						// No suitable wrap position was found so break right in the middle of a word

						// Make sure to set the last width of the line before wrapping
						widths[pos + 1] = widths[pos] + w;

						doc.Split (this, tag, pos);
						ending = LineEnding.Wrap;
						len = this.text.Length;
						retval = true;
						wrapped = true;
					}
				}

				// Contract all wrapped lines that follow back into our line
				if (!wrapped) {
					pos++;

					widths[pos] = widths[pos - 1] + w;

					if (pos == len) {
						line = doc.GetLine (this.line_no + 1);
						if ((line != null) && (ending == LineEnding.Wrap || ending == LineEnding.None)) {
							// Pull the two lines together
							doc.Combine (this.line_no, this.line_no + 1);
							len = this.text.Length;
							retval = true;
						}
					}
				}

				if (pos == (tag.Start - 1 + tag.Length)) {
					// We just found the end of our current tag
					tag.Height = tag.MaxHeight ();

					// Check if we're the tallest on the line (so far)
					if (tag.Height > this.height)
						this.height = tag.Height;	// Yep; make sure the line knows

					if (tag.Ascent > this.ascent) {
						LineTag t;

						// We have a tag that has a taller ascent than the line;
						t = tags;
						while (t != null && t != tag) {
							t.Shift = (tag.Ascent - t.Ascent) / 72;
							t = t.Next;
						}

						// Save on our line
						this.ascent = tag.Ascent;
					} else {
						tag.Shift = (this.ascent - tag.Ascent) / 72;
					}

					tag = tag.Next;
					if (tag != null) {
						tag.Shift = 0;
						wrap_pos = pos;
					}
				}
			}

			while (tag != null) {	
				tag.Shift = (tag.Line.ascent - tag.Ascent) / 72;
				tag = tag.Next;
			}

			if (this.height == 0) {
				this.height = tags.Font.Height;
				tags.Height = this.height;
				tags.Shift = 0;
			}

			if (prev_offset != offset || prev_height != this.height || prev_ascent != this.ascent)
				retval = true;

			return retval;
		}
示例#43
0
		public override ITreeNode CreateNewLine(LineEnding lineEnding, IPsiSourceFile psiSourceFile)
			=> T4TokenNodeTypes.NewLine.Create(lineEnding.GetPresentation());
示例#44
0
		private int GetLineEnding (string line, int start, out LineEnding ending)
		{
			int res;
			int rich_index;

			if (start >= line.Length) {
				ending = LineEnding.Wrap;
				return -1;
			}
			
			res = line.IndexOf ('\r', start);
			rich_index = line.IndexOf ('\n', start);
			
			// Handle the case where we find both of them, and the \n is before the \r
			if (res != -1 && rich_index != -1)
				if (rich_index < res) {
					ending = LineEnding.Rich;
					return rich_index;				
				}
			
			if (res != -1) {
				if (res + 2 < line.Length && line [res + 1] == '\r' && line [res + 2] == '\n') {
					ending = LineEnding.Soft;
					return res;
				}
				if (res + 1 < line.Length && line [res + 1] == '\n') {
					ending = LineEnding.Hard;
					return res;
				}
				ending = LineEnding.Limp;
				return res;
			}

			if (rich_index != -1) {
				ending = LineEnding.Rich;
				return rich_index;
			}

			ending = LineEnding.Wrap;
			return line.Length;
		}
 private static bool IsMatch(LineEnding style, char c, bool isCrLf)
 {
     switch (style)
     {
         case LineEnding.CR:
             return !isCrLf && c == '\r';
         case LineEnding.LF:
             return c == '\n';
         case LineEnding.CRLF:
             return isCrLf;
         default:
             throw new ArgumentException("Unexpected style type", "style");
     }
 }
示例#46
0
		// Get the line ending, but only of the types specified
		private int GetLineEnding (string line, int start, out LineEnding ending, LineEnding type)
		{
			int index = start;
			int last_length = 0;

			do {
				index = GetLineEnding (line, index + last_length, out ending);
				last_length = LineEndingLength (ending);
			} while 
				((ending & type) != ending && index != -1);
			
			return index == -1 ? line.Length : index;
		}
 public static void TestHelper(string input, string expectedOutput, LineEnding style)
 {
     string output = Normalize(input, style);
     if (output != expectedOutput)
         Trace.Fail(string.Format(CultureInfo.InvariantCulture, "\"{0}\" != \"{1}\"", Escape(output), Escape(expectedOutput)));
 }
示例#48
0
		internal int LineEndingLength (LineEnding ending)
		{
			switch (ending) {
				case LineEnding.Limp:
				case LineEnding.Rich:
					return 1;
				case LineEnding.Hard:
					return 2;
				case LineEnding.Soft:
					return 3;
			}

			return 0;
		}
示例#49
0
 public CaptionOptions(
     DateTime? elementListVersion = null,
     string speakerChangeToken = null,
     bool? maskProfanity = null,
     bool? removeDisfluencies = null,
     List<Tag> removeSoundsList = null,
     bool? removeSoundReferences = null,
     bool? replaceSlang = null,
     char[] soundBoundaries = null,
     bool? buildUri = null,
     int? captionWordsMin = null,
     bool? captionBySentence = null,
     int? charactersPerCaptionLine = null,
     string dfxpHeader = null,
     bool? disallowDangling = null,
     string effectsSpeaker = null,
     SpeakerId? displaySpeakerId = null,
     Case? forceCase = null,
     bool? includeDfxpMetadata = null,
     int? layoutDefaultCaptionLengthMs = null,
     bool? lineBreakOnSentence = null,
     LineEnding? lineEndingFormat = null,
     int? linesPerCaption = null,
     int? maximumCaptionDuration = null,
     int? mergeGapInterval = null,
     int? minimumCaptionLengthMs = null,
     int? minimumGapBetweenCaptionsMs = null,
     int? minimumMergeGapInterval = null,
     bool? qtSeamless = null,
     int? silenceMaxMs = null,
     bool? singleSpeakerPerCaption = null,
     int? soundThreshold = null,
     bool? soundTokensByCaption = null,
     bool? soundTokensByLine = null,
     List<Tag> soundTokensByCaptionList = null,
     List<Tag> soundTokensByLineList = null,
     bool? speakerOnNewLine = null,
     string srtFormat = null,
     bool? stripSquareBrackets = null,
     bool? utf8_mark = null)
     : base(elementListVersion,
            speakerChangeToken,
            maskProfanity,
            removeDisfluencies,
            removeSoundsList,
            removeSoundReferences,
            replaceSlang,
            soundBoundaries)
 {
     this.BuildUrl = buildUri;
     this.CaptionWordsMin = captionWordsMin;
     this.CaptionBySentence = captionBySentence;
     this.CharactersPerCaptionLine = charactersPerCaptionLine;
     this.DfxpHeader = dfxpHeader;
     this.DisallowDangling = disallowDangling;
     this.EffectsSpeaker = effectsSpeaker;
     this.DisplayedSpeakerId = displaySpeakerId;
     this.ForceCase = forceCase;
     this.IncludeDfxpMetadata = includeDfxpMetadata;
     this.LayoutTargetCaptionLengthMs = layoutDefaultCaptionLengthMs;
     this.LineBreakOnSentence = lineBreakOnSentence;
     this.LineEndingFormat = lineEndingFormat;
     this.LinesPerCaption = linesPerCaption;
     this.MaximumCaptionDuration = maximumCaptionDuration;
     this.MergeGapInterval = mergeGapInterval;
     this.MinimumCaptionLengthMs = minimumCaptionLengthMs;
     this.MinimumGapBetweenCaptionsMs = minimumGapBetweenCaptionsMs;
     this.MinimumMergeGapInterval = minimumMergeGapInterval;
     this.QtSeamless = qtSeamless;
     this.SilenceMaxMs = silenceMaxMs;
     this.SingleSpeakerPerCaption = singleSpeakerPerCaption;
     this.SoundThreshold = soundThreshold;
     this.SoundTokensByCaption = soundTokensByCaption;
     this.SoundTokensByLine = soundTokensByLine;
     this.SoundTokensByCaptionList = soundTokensByCaptionList;
     this.SoundTokensByLineList = soundTokensByLineList;
     this.SpeakerOnNewLine = speakerOnNewLine;
     this.SrtFormat = srtFormat;
     this.StripSquareBrackets = stripSquareBrackets;
     this.Utf8Mark = utf8_mark;
 }
示例#50
0
		internal string LineEndingToString (LineEnding ending)
		{
			switch (ending) {
				case LineEnding.Limp:
					return "\r";
				case LineEnding.Hard:
					return "\r\n";
				case LineEnding.Soft:
					return "\r\r\n";
				case LineEnding.Rich:
					return "\n";
			}
			
			return string.Empty;
		}
示例#51
0
		internal void Add (int LineNo, string Text, HorizontalAlignment align, Font font, Color color, LineEnding ending)
		{
			Line	add;
			Line	line;
			int	line_no;

			CharCount += Text.Length;

			if (LineNo<1 || Text == null) {
				if (LineNo<1) {
					throw new ArgumentNullException("LineNo", "Line numbers must be positive");
				} else {
					throw new ArgumentNullException("Text", "Cannot insert NULL line");
				}
			}

			add = new Line (this, LineNo, Text, align, font, color, ending);

			line = document;
			while (line != sentinel) {
				add.parent = line;
				line_no = line.line_no;

				if (LineNo > line_no) {
					line = line.right;
				} else if (LineNo < line_no) {
					line = line.left;
				} else {
					// Bump existing line numbers; walk all nodes to the right of this one and increment line_no
					IncrementLines(line.line_no);
					line = line.left;
				}
			}

			add.left = sentinel;
			add.right = sentinel;

			if (add.parent != null) {
				if (LineNo > add.parent.line_no) {
					add.parent.right = add;
				} else {
					add.parent.left = add;
				}
			} else {
				// Root node
				document = add;
			}

			RebalanceAfterAdd(add);

			lines++;
		}
示例#52
0
        // based on Group.RotationalMapping()
        private static void RotationalMappingLineEndTex(LineEnding ending, PointF p1, PointF p2, IndentedTextWriter writer, Group refgroup)
        {
            if (ending.EnableRotationalMapping)
            {
                PointF tf = p2;
                PointF vector = new PointF(p1.X - tf.X, p1.Y - tf.Y);
                vector = SBMLExtension.Util.NormalizePoint(vector);
                if ((vector.X != 0f) || (vector.Y != 0f))
                {
                    PointF tf3;
                    if (vector.X == 0f)
                    {
                        tf3 = new PointF(vector.Y, 0f);
                    }
                    else
                    {
                        tf3 = new PointF(-vector.Y * vector.X, 1f - (vector.Y * vector.Y));
                    }
                    tf3 = SBMLExtension.Util.NormalizePoint(tf3);

                    writer.WriteLine("\\pgftransformcm {{ {0} }}{{ {1} }}{{ {2} }}{{ {3} }}{{\\pgfpoint{{ {4}pt }}{{ {5}pt }} }}",
                        (vector.X).ToString(),
                        (vector.Y).ToString(),
                        (tf3.X).ToString(),
                        (tf3.Y).ToString(),
                        0f.ToString(),
                        0f.ToString());
                }
            }
        }
示例#53
0
		internal Line (Document document, int LineNo, string Text, LineTag tag, LineEnding ending) : this(document, ending)
		{
			space = Text.Length > DEFAULT_TEXT_LEN ? Text.Length+1 : DEFAULT_TEXT_LEN;

			text = new StringBuilder (Text, space);
			this.ending = ending;
			line_no = LineNo;

			widths = new float[space + 1];
			tags = tag;
		}