/// <summary>
        /// Scrolls to nearest bookmark or to first bookmark
        /// </summary>
        /// <param name="textbox"></param>
        /// <param name="iLine">Current bookmark line index</param>
        public static bool GotoNextBookmark(FastColoredTextBox textbox, int iLine)
        {
            Bookmark nearestBookmark = null;
            int minNextLineIndex = int.MaxValue;
            Bookmark minBookmark = null;
            int minLineIndex = int.MaxValue;
            foreach (Bookmark bookmark in textbox.Bookmarks)
            {
                if (bookmark.LineIndex < minLineIndex)
                {
                    minLineIndex = bookmark.LineIndex;
                    minBookmark = bookmark;
                }

                if (bookmark.LineIndex > iLine && bookmark.LineIndex < minNextLineIndex)
                {
                    minNextLineIndex = bookmark.LineIndex;
                    nearestBookmark = bookmark;
                }
            }

            if (nearestBookmark != null)
            {
                nearestBookmark.DoVisible();
                return true;
            }
            else if (minBookmark != null)
            {
                minBookmark.DoVisible();
                return true;
            }

            return false;
        }
Example #2
0
    public MgfService(FastColoredTextBox tb)
    {
        this.tb = tb;
        tb.AddStyle(preprocStyle);
        tb.AddStyle(commentStyle);
        tb.AddStyle(operatorStyle);
        tb.AddStyle(linkStyle);
        tb.AddStyle(linkTlpdStyle);
        tb.AddStyle(wavyError);
        tb.AddStyle(wavyUndefined);
        tb.AddStyle(wavyRedefined);

        tb.AddStyle(entityStyle);
        tb.AddStyle(seriesStyle);

        //tb.AddStyle(terranStyle);
        //tb.AddStyle(zergStyle);
        //tb.AddStyle(protossStyle);
        //tb.AddStyle(randomStyle);
        tb.AddStyle(playerStyle);
        tb.AddStyle(mapStyle);

        tb.AddStyle(winnerStyle);
        tb.AddStyle(loserStyle);

        tb.AddStyle(rangeStyle);
    }
Example #3
0
        internal AutocompleteListView(FastColoredTextBox tb)
        {
            SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
            base.Font = new Font(FontFamily.GenericSansSerif, 9);
            visibleItems = new List<AutocompleteItem>();
            itemHeight = Font.Height + 2;
            VerticalScroll.SmallChange = itemHeight;
            BackColor = Color.White;
            MaximumSize = new Size(Size.Width, 180);
            toolTip.ShowAlways = false;
            AppearInterval = 500;
            timer.Tick += new EventHandler(timer_Tick);

            this.tb = tb;

            tb.KeyDown += new KeyEventHandler(tb_KeyDown);
            tb.SelectionChanged += new EventHandler(tb_SelectionChanged);
            tb.KeyPressed += new KeyPressEventHandler(tb_KeyPressed);

            Form form = tb.FindForm();
            if (form != null)
            {
                form.LocationChanged += (o, e) => Menu.Close();
                form.ResizeBegin += (o, e) => Menu.Close();
                form.FormClosing += (o, e) => Menu.Close();
                form.LostFocus += (o, e) => Menu.Close();
            }

            tb.LostFocus += (o, e) =>
            {
                if (!Menu.Focused) Menu.Close();
            };
            tb.Scroll += (o, e) => Menu.Close();
        }
Example #4
0
        public Sandbox()
        {
            InitializeComponent();

            fctb = new FastColoredTextBox() { Parent = this, Dock = DockStyle.Fill };
            fctb.TextChangedDelayed += new EventHandler<TextChangedEventArgs>(fctb_TextChangedDelayed);
            fctb.Text = @"<?xml version=""1.0"" encoding=""ISO-8859-1""?>
<!-- Edited by XMLSpy® -->
<CATALOG>
	<PLANT>
		<COMMON>Bloodroot</COMMON><AVAILABILITY>
			031599
		</AVAILABILITY>
	</PLANT>
	<PLANT><PRICE value=""11.34""></PRICE>
		<COMMON Name=""Bloodroot"" /><BLABLA/>
		<BOTANICAL Title=""Sanguinaria canadensis""
			Name="""" /><ZONE>4</ZONE>
		<LIGHT>Mostly Shady</LIGHT> <PRICE Value=""$2.44""/>
		<AVAILABILITY No=""3454"">
			031599
		</AVAILABILITY>
	</PLANT>
</CATALOG>
";
        }
 public StringTextSource(FastColoredTextBox tb)
     : base(tb)
 {
     timer.Interval = 10000;
     timer.Tick += new EventHandler(timer_Tick);
     timer.Enabled = true;
 }
 public static void SelectText(string target, FastColoredTextBox editor)
 {
     int index = Match(editor.Text, $@"(?<=\n)\({target}\)").Index; //finding the goto destination
     Range range = editor.GetRange(index + target.Length + 2, index + target.Length + 2);
     editor.Selection = new Range(editor, range.Start.iLine);
     editor.DoCaretVisible();
 }
        public void MoveWordRightToPatientDays()
        {
            var tb = new FastColoredTextBox();
            //var range = new Range(tb, 0,0,0,0);
            string s = TabSizeCalculatorTests.CreateLongString();
            var words = s.Split('\t');
            tb.Text = s;
            Assert.AreEqual(new Place(0, 0), tb.Selection.Start);
            Assert.AreEqual(new Place(0, 0), tb.Selection.End);

            int wordIndex = 0;
            while (words[wordIndex] != "PatientDays")
            {
                tb.Selection.GoWordRight(false); // to the next end of the word
                wordIndex++;
            }
            // before "PatientDays"
            tb.Selection.GoWordRight(false);
            Assert.AreEqual(new Place(190, 0), tb.Selection.Start);
            Assert.AreEqual(new Place(190, 0), tb.Selection.End);

            string substring = s.Substring(0, 190);
            Assert.IsTrue(substring.EndsWith("PatientDays"));

            int width = TextSizeCalculator.TextWidth(s.Substring(0, 190), 4);
            Assert.AreEqual(211, width);
        }
 public StringTextSource(FastColoredTextBox tb)
     : base(tb)
 {
     _timer.Interval = 10000;
     _timer.Tick += timer_Tick;
     _timer.Enabled = true;
 }
Example #9
0
 public string GetHtml(FastColoredTextBox tb)
 {
     this.tb = tb;
     Range sel = new Range(tb);
     sel.SelectAll();
     return GetHtml(sel);
 }
        public static void ApplyTheme(string source, SyntaxHighlighter highlighter, FastColoredTextBox tb)
        {
            source = Path.Combine(GlobalSettings.SettingsDir, source);
            using (var reader = XmlReader.Create(source))
            {
                while (reader.Read())
                    // Only detect start elements.
                    if (reader.IsStartElement())
                    {
                        // Get element name and switch on it.
                        switch (reader.Name)
                        {
                            case "Style":
                                // Search for the attribute name on this current node.
                                var name = reader["Name"];
                                var fontstyle = (FontStyle) Enum.Parse(typeof (FontStyle), reader["Font"]);
                                var color = reader["Color"];
                                InitStyle(name, fontstyle, GetColorFromHexVal(color), highlighter);
                                // if (reader.Read())
                                //     InitStyle(name, fontstyle, GetColorFromHexVal(color), highlighter);
                                break;

                            case "Key":
                                // Search for the attribute name on this current node.
                                InitKey(tb, reader["Name"], reader["Value"]);
                                // if (reader.Read())
                                //     KeyInit(tb, reader["Name"], reader["Value"]);
                                break;
                        }
                    }
            }
        }
Example #11
0
 internal static void InsertChar(char c, ref char deletedChar, FastColoredTextBox tb)
 {
     switch (c)
     {
         case '\n':
             if (tb.LinesCount == 0)
                 InsertLine(tb);
             InsertLine(tb);
             break;
         case '\r': break;
         case '\b'://backspace
             if (tb.Selection.Start.iChar == 0 && tb.Selection.Start.iLine == 0)
                 return;
             if (tb.Selection.Start.iChar == 0)
             {
                 if (tb[tb.Selection.Start.iLine - 1].VisibleState != VisibleState.Visible)
                     tb.ExpandBlock(tb.Selection.Start.iLine - 1);
                 deletedChar = '\n';
                 MergeLines(tb.Selection.Start.iLine - 1, tb);
             }
             else
             {
                 deletedChar = tb[tb.Selection.Start.iLine][tb.Selection.Start.iChar - 1].c;
                 tb[tb.Selection.Start.iLine].RemoveAt(tb.Selection.Start.iChar - 1);
                 tb.Selection.Start = new Place(tb.Selection.Start.iChar - 1, tb.Selection.Start.iLine);
             }
             break;
         default:
             tb[tb.Selection.Start.iLine].Insert(tb.Selection.Start.iChar, new Char(c));
             tb.Selection.Start = new Place(tb.Selection.Start.iChar + 1, tb.Selection.Start.iLine);
             break;
     }
 }
 /// <summary>
 /// Moves selected lines down
 /// </summary>
 public static void MoveSelectedLinesDown(FastColoredTextBox textbox)
 {
     Range prevSelection = textbox.Selection.Clone();
     textbox.Selection.Expand();
     if (!textbox.Selection.ReadOnly)
     {
         int iLine = textbox.Selection.Start.iLine;
         if (textbox.Selection.End.iLine >= textbox.LinesCount - 1)
         {
             textbox.Selection = prevSelection;
             return;
         }
         string text = textbox.SelectedText;
         var temp = new List<int>();
         for (int i = textbox.Selection.Start.iLine; i <= textbox.Selection.End.iLine; i++)
         {
             temp.Add(i);
         }
         textbox.RemoveLines(temp);
         textbox.Selection.Start = new Place(textbox.GetLineLength(iLine), iLine);
         textbox.SelectedText = "\n" + text;
         textbox.Selection.Start = new Place(prevSelection.Start.iChar, prevSelection.Start.iLine + 1);
         textbox.Selection.End = new Place(prevSelection.End.iChar, prevSelection.End.iLine + 1);
     }
     else
     {
         textbox.Selection = prevSelection;
     }
 }
 /// <summary>
 /// Cut selected text into Clipboard
 /// </summary>
 public static void Cut(FastColoredTextBox textbox)
 {
     if (!textbox.Selection.IsEmpty)
     {
         EditorCommands.Copy(textbox);
         textbox.ClearSelected();
     }
     else
         if (textbox.LinesCount == 1)
         {
             textbox.Selection.SelectAll();
             EditorCommands.Copy(textbox);
             textbox.ClearSelected();
         }
         else
         {
             EditorCommands.Copy(textbox);
             //remove current line
             if (textbox.Selection.Start.iLine >= 0 && textbox.Selection.Start.iLine < textbox.LinesCount)
             {
                 int iLine = textbox.Selection.Start.iLine;
                 textbox.RemoveLines(new List<int> { iLine });
                 textbox.Selection.Start = new Place(0, Math.Max(0, Math.Min(iLine, textbox.LinesCount - 1)));
             }
         }
 }
Example #14
0
 public Bookmark(FastColoredTextBox tb, string name, int lineIndex)
 {
     this.TB = tb;
     this.Name = name;
     this.LineIndex = lineIndex;
     Color = tb.BookmarkColor;
 }
        /// <summary>
        /// Copy selected text into Clipboard
        /// </summary>
        public static void Copy(FastColoredTextBox textbox)
        {
            if (textbox.Selection.IsEmpty)
            {
                textbox.Selection.Expand();
            }

            if (!textbox.Selection.IsEmpty)
            {
                var exp = new ExportToHTML();
                exp.UseBr = false;
                exp.UseNbsp = false;
                exp.UseStyleTag = true;
                string html = "<pre>" + exp.GetHtml(textbox.Selection.Clone()) + "</pre>";
                var data = new DataObject();
                data.SetData(DataFormats.UnicodeText, true, textbox.Selection.Text);
                data.SetData(DataFormats.Html, PrepareHtmlForClipboard(html));
                data.SetData(DataFormats.Rtf, new ExportToRTF().GetRtf(textbox.Selection.Clone()));
                //
                var thread = new Thread(() => SetClipboard(data));
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
            }
        }
 public FileTextSource(FastColoredTextBox currentTB)
     : base(currentTB)
 {
     timer.Interval = 10000;
     timer.Tick += new EventHandler(timer_Tick);
     timer.Enabled = true;
 }
Example #17
0
 /// <summary>
 /// Get range of text
 /// </summary>
 /// <param name="textbox"></param>
 /// <param name="fromPos">Absolute start position</param>
 /// <param name="toPos">Absolute finish position</param>
 /// <returns>Range</returns>
 public static Range GetRange(FastColoredTextBox textbox, int fromPos, int toPos)
 {
     var sel = new Range(textbox);
     sel.Start = TextSourceUtil.PositionToPlace(textbox.lines, fromPos);
     sel.End = TextSourceUtil.PositionToPlace(textbox.lines, toPos);
     return sel;
 }
Example #18
0
        public Control Create()
        {
            txt = new FastColoredTextBox();
            txt.ReadOnly = false;
            //txt.MouseWheel += MouseWheel;
            txt.KeyDown += KeyDown;
            //txt.KeyPress += KeyPress;
            //txt.TextChanged += TextChanged;
            txt.SelectionChanged += SelectionChanged;

            //txt.Language = Language.CSharp;
            //txt.Language = Language.SQL;
            txt.Language = Language.Custom;
            txt.DescriptionFile = "isql_syntax_desc.xml";
            txt.Font = new Font("Courier New", 10);
            txt.WordWrap = true;
            txt.WordWrapMode = WordWrapMode.CharWrapControlWidth;
            txt.ShowLineNumbers = false;
            txt.AutoIndentNeeded += (object sender, AutoIndentEventArgs e) => { e.Shift = 0; e.AbsoluteIndentation = 0; e.ShiftNextLines = 0; }; // Disable auto-indentation

            //txt.Text = "> ";

            ClearAction = ActionManager.CreateAction("Clear console", this, "Clear");
            PrintCommandAction = ActionManager.CreateAction("Print command to console", this, "PrintCommand");
            ActionManager.Do(ClearAction);

            return txt;
        }
 public string GetRtf(FastColoredTextBox tb)
 {
     _tb = tb;
     var sel = new Range(tb);
     sel.SelectAll();
     return GetRtf(sel);
 }
        /// <summary>
        /// Scrolls to nearest previous bookmark or to last bookmark
        /// </summary>
        /// <param name="textbox"></param>
        /// <param name="iLine">Current bookmark line index</param>
        public static bool GotoPrevBookmark(FastColoredTextBox textbox, int iLine)
        {
            Bookmark nearestBookmark = null;
            int maxPrevLineIndex = -1;
            Bookmark maxBookmark = null;
            int maxLineIndex = -1;
            foreach (Bookmark bookmark in textbox.Bookmarks)
            {
                if (bookmark.LineIndex > maxLineIndex)
                {
                    maxLineIndex = bookmark.LineIndex;
                    maxBookmark = bookmark;
                }

                if (bookmark.LineIndex < iLine && bookmark.LineIndex > maxPrevLineIndex)
                {
                    maxPrevLineIndex = bookmark.LineIndex;
                    nearestBookmark = bookmark;
                }
            }

            if (nearestBookmark != null)
            {
                nearestBookmark.DoVisible();
                return true;
            }
            else if (maxBookmark != null)
            {
                maxBookmark.DoVisible();
                return true;
            }

            return false;
        }
 /// <summary>
 /// Moves selected lines up
 /// </summary>
 public static void MoveSelectedLinesUp(FastColoredTextBox textbox)
 {
     Range prevSelection = textbox.Selection.Clone();
     textbox.Selection.Expand();
     if (!textbox.Selection.ReadOnly)
     {
         int iLine = textbox.Selection.Start.iLine;
         if (iLine == 0)
         {
             textbox.Selection = prevSelection;
             return;
         }
         string text = textbox.SelectedText;
         var temp = new List<int>();
         for (int i = textbox.Selection.Start.iLine; i <= textbox.Selection.End.iLine; i++)
         {
             temp.Add(i);
         }
         textbox.RemoveLines(temp);
         textbox.Selection.Start = new Place(0, iLine - 1);
         textbox.SelectedText = text + "\n";
         textbox.Selection.Start = new Place(prevSelection.Start.iChar, prevSelection.Start.iLine - 1);
         textbox.Selection.End = new Place(prevSelection.End.iChar, prevSelection.End.iLine - 1);
     }
     else
     {
         textbox.Selection = prevSelection;
     }
 }
        private static void InitKey(FastColoredTextBox tb, string name, string value)
        {
            var keyval = GetColorFromHexVal(value);
            switch (name)
            {
                case "Background":
                    tb.BackColor = keyval;
                    break;

                case "Foreground":
                    tb.ForeColor = keyval;
                    break;

                case "BracketStyle":
                    tb.BracketsStyle = new MarkerStyle(new SolidBrush(Color.FromArgb(60, GetColorFromHexVal(value))));
                    break;

                case "BracketStyle2":
                    tb.BracketsStyle2 = new MarkerStyle(new SolidBrush(Color.FromArgb(60, GetColorFromHexVal(value))));
                    break;

                case "Bookmark":
                    tb.BookmarkColor = keyval;
                    break;

                case "Caret":
                    tb.CaretColor = keyval;
                    break;

                case "CurrentLine":
                    tb.CurrentLineColor = keyval;
                    break;

                case "FoldingIndication":
                    tb.FoldingIndicatorColor = keyval;
                    break;

                case "LineNumber":
                    tb.LineNumberColor = keyval;
                    break;

                case "LineNumberPadding":
                    tb.IndentBackColor = keyval;
                    break;

                case "Selection":
                    tb.SelectionColor = keyval;
                    break;

                case "ServicesLine":
                    tb.ServiceLinesColor = keyval;
                    break;

                case "SameWords":
                    tb.SameWordsStyle = new MarkerStyle(new SolidBrush(Color.FromArgb(60, keyval)));
                    // new MarkerStyle(new SolidBrush(Color.FromArgb(40, keyval)));
                    break;
            }
        }
 /// <summary>
 /// Highlights brackets around caret
 /// </summary>
 internal static void HighlightBrackets(FastColoredTextBox textbox, BracketsHighlightStrategy strategy, char LeftBracket, char RightBracket, ref Range leftBracketPosition, ref Range rightBracketPosition)
 {
     switch (strategy)
     {
         case BracketsHighlightStrategy.Strategy1: HighlightBrackets1(textbox, LeftBracket, RightBracket, ref leftBracketPosition, ref rightBracketPosition); break;
         case BracketsHighlightStrategy.Strategy2: HighlightBrackets2(textbox, LeftBracket, RightBracket, ref leftBracketPosition, ref rightBracketPosition); break;
     }
 }
Example #24
0
 /// <summary>
 /// Gets colored text as HTML
 /// </summary>
 /// <remarks>For more flexibility you can use ExportToHTML class also</remarks>
 public static string GetHtml(FastColoredTextBox textbox)
 {
     var exporter = new ExportToHTML();
         exporter.UseNbsp = false;
         exporter.UseStyleTag = false;
         exporter.UseBr = false;
         return "<pre>" + exporter.GetHtml(textbox) + "</pre>";
 }
Example #25
0
 /// <summary>
 /// Finds ranges for given regex pattern
 /// </summary>
 /// <param name="textbox"></param>
 /// <param name="regexPattern">Regex pattern</param>
 /// <param name="options"></param>
 /// <returns>Enumeration of ranges</returns>
 public static IEnumerable<Range> GetRanges(FastColoredTextBox textbox, string regexPattern, RegexOptions options)
 {
     var range = new Range(textbox);
     range.SelectAll();
     //
     foreach (Range r in range.GetRanges(regexPattern, options))
         yield return r;
 }
Example #26
0
        internal MacrosManager(FastColoredTextBox ctrl)
        {
            ActivateRecordingKey = Keys.M | Keys.Control;
            ExecutingKey = Keys.E | Keys.Control;

            UnderlayingControl = ctrl;
            AllowMacroRecordingByUser = true;
        }
Example #27
0
 public SpellChecker(FastColoredTextBox fctb)
 {
     var List = File.ReadAllLines(@"Configurations\\Dictionaries\dic.dic");
     words = new HashSet<string>(List, System.StringComparer.InvariantCultureIgnoreCase);
     this.tb = fctb;
     fctb = this.tb;
     this.tb.TextChangedDelayed += new System.EventHandler<TextChangedEventArgs>(tb_TextChangedDelayed);
 }
Example #28
0
        public FileTextSource(FastColoredTextBox currentTB)
            : base(currentTB)
        {
            timer.Interval = 10000;
            timer.Tick    += timer_Tick;
            timer.Enabled  = true;

            SaveEOL = Environment.NewLine;
        }
 public Scripter()
 {
     InitializeComponent();
     CanDirty = false;
     _textbox = new FastColoredTextBox {Dock = DockStyle.Fill};
     _textbox.TextChangedDelayed += _textbox_TextChangedDelayed;
     Controls.Add(_textbox);
     UpdateStyle();
 }
Example #30
0
 public SpellChecker(FastColoredTextBox fctb, string dictionarypath)
 {
     var List = File.ReadAllLines(dictionarypath);
     DictionaryPath = dictionarypath;
     words = new HashSet<string>(List, System.StringComparer.InvariantCultureIgnoreCase);
     this.tb = fctb;
     fctb = this.tb;
     this.tb.TextChangedDelayed += new System.EventHandler<TextChangedEventArgs>(tb_TextChangedDelayed);
 }
Example #31
0
 public TextSourceWithLineFiltering(FastColoredTextBox tb) : base(tb)
 {
 }
Example #32
0
 public LuaSyntaxSources(FastColoredTextBox textbox) : base(textbox)
 {
     Init();
 }
Example #33
0
 public Bookmarks(FastColoredTextBox tb)
 {
     this.tb          = tb;
     tb.LineInserted += tb_LineInserted;
     tb.LineRemoved  += tb_LineRemoved;
 }
 public DynamicCollection(AutocompleteMenu menu, FastColoredTextBox tb)
 {
     this.menu = menu;
     this.tb   = tb;
 }
        public static void UpdateFeatureValue(string feature, FastColoredTextBox fctbCurrentFirmware, FastColoredTextBox fctbNewFirmware)
        {
            // Get the last occurance for the feature in current firmware
            int    currentrow   = MarlinMigrateHelper.GetFirmwareFeatureRow(fctbCurrentFirmware, feature);
            string currentValue = MarlinMigrateHelper.GetFirmwareFeatureValue(fctbCurrentFirmware, feature);
            string currentLine  = fctbCurrentFirmware.GetLineText(currentrow).Trim();

            // Get the last occurance for the feature in new firmware
            int    newrow   = MarlinMigrateHelper.GetFirmwareFeatureRow(fctbNewFirmware, feature);
            string newValue = MarlinMigrateHelper.GetFirmwareFeatureValue(fctbNewFirmware, feature);
            string newLine  = fctbNewFirmware.GetLineText(newrow).Trim();


            //TODO: Fix Startwith
            if (currentLine.StartsWith("//"))
            {
                if (!newLine.StartsWith("//"))
                {
                    fctbNewFirmware.Navigate(newrow);
                    fctbNewFirmware.CommentSelected("//");
                }
            }

            //TODO: Fix Startwith
            if (!currentLine.StartsWith("//"))
            {
                if (newLine.StartsWith("//"))
                {
                    fctbNewFirmware.Navigate(newrow);
                    fctbNewFirmware.RemoveLinePrefix("//");
                }
            }

            //TODO: Fix Startwith
            if (!currentValue.StartsWith("//"))
            {
                string originalLine = fctbNewFirmware.GetLineText(newrow);
                fctbNewFirmware.Navigate(newrow);
                List <int> removeRow = new List <int>();

                removeRow.Add(newrow);
                fctbNewFirmware.RemoveLines(removeRow);
                fctbNewFirmware.Navigate(newrow);
                fctbNewFirmware.InsertText(originalLine.ReplaceFirst(newValue, currentValue) + Environment.NewLine);
            }

            fctbNewFirmware.DoAutoIndent(newrow);
            fctbNewFirmware.DoAutoIndent(newrow + 1);
        }
Example #36
0
 protected virtual void Subscribe(FastColoredTextBox target)
 {
     target.Scroll              += target_Scroll;
     target.SelectionChanged    += target_SelectionChanged;
     target.VisibleRangeChanged += target_VisibleRangeChanged;
 }
Example #37
0
 public AutocompleteClass(FastColoredTextBox txt, DBRegistrationClass dbReg)
 {
     _txtBox = txt;
     _dbReg  = dbReg;
 }
Example #38
0
 /// <summary>
 /// Shows VisualMarker
 /// Call this method in Draw method, when you need to show VisualMarker for your style
 /// </summary>
 protected virtual void AddVisualMarker(FastColoredTextBox tb, StyleVisualMarker marker)
 {
     tb.AddVisualMarker(marker);
 }
Example #39
0
 public FindForm(FastColoredTextBox tb)
 {
     InitializeComponent();
     this.tb = tb;
 }
 public XMLSyntaxSource(FastColoredTextBox textbox) : base(textbox)
 {
     Init();
 }
Example #41
0
        private bool _ProcessDiff(DiffMergeStuffs.Lines lines, FastColoredTextBox fctb1, FastColoredTextBox fctb2)
        {
            bool match = true;

            foreach (var line in lines)
            {
                switch (line.state)
                {
                case DiffMergeStuffs.DiffType.None:
                    fctb1.AppendText(line.line + Environment.NewLine);
                    fctb2.AppendText(line.line + Environment.NewLine);
                    break;

                case DiffMergeStuffs.DiffType.Deleted:
                    fctb1.AppendText(line.line + Environment.NewLine, HighlightSyntax.RedLineStyle);
                    fctb2.AppendText(Environment.NewLine);
                    match = false;
                    break;

                case DiffMergeStuffs.DiffType.Inserted:
                    fctb1.AppendText(Environment.NewLine);
                    fctb2.AppendText(line.line + Environment.NewLine, HighlightSyntax.GreenLineStyle);
                    match = false;
                    break;
                }
                if (line.subLines != null)
                {
                    bool res = _ProcessDiff(line.subLines, fctb1, fctb2);
                    match = match && res;
                }
            }
            return(match);
        }
Example #42
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            if (_richTextBox == null)
            {
                if (string.IsNullOrEmpty(FormName) ||
                    string.IsNullOrEmpty(TextBoxName))
                {
                    return;
                }

                Form form = Application.OpenForms[FormName];
                if (form == null)
                {
                    return;
                }

                _richTextBox = FindControlRecursive(form, TextBoxName) as FastColoredTextBox;
                if (_richTextBox == null)
                {
                    return;
                }

                form.FormClosing += (s, e) => _richTextBox = null;
            }

            lock (_richTextBox)
            {
                // This check is required a second time because this class
                // is executing on multiple threads.
                if (_richTextBox == null)
                {
                    return;
                }

                // Because the logging is running on a different thread than
                // the GUI, the control's "BeginInvoke" method has to be
                // leveraged in order to append the message. Otherwise, a
                // threading exception will be thrown.
                Action <FastColoredTextBox, string> del = new Action <FastColoredTextBox, string>((_richTextBox, s) =>
                {
                    //some stuffs for best performance
                    _richTextBox.BeginUpdate();
                    _richTextBox.Selection.BeginUpdate();
                    //remember user selection
                    Range userSelection = _richTextBox.Selection.Clone();
                    //add text with predefined style
                    _richTextBox.TextSource.CurrentTB = _richTextBox;
                    _richTextBox.AppendText("=======================================================\n", styles[loggingEvent.Level.Name]);
                    _richTextBox.AppendText(s, styles[loggingEvent.Level.Name]);
                    _richTextBox.AppendText("=======================================================\n", styles[loggingEvent.Level.Name]);
                    //restore user selection
                    if (!userSelection.IsEmpty || userSelection.Start.iLine < _richTextBox.LinesCount - 2)
                    {
                        _richTextBox.Selection.Start = userSelection.Start;
                        _richTextBox.Selection.End   = userSelection.End;
                    }
                    else
                    {
                        _richTextBox.GoEnd();    //scroll to end of the text
                    }
                    //
                    _richTextBox.Selection.EndUpdate();
                    _richTextBox.EndUpdate();
                }
                                                                                                  );
                _richTextBox.BeginInvoke(del, _richTextBox, loggingEvent.RenderedMessage + Environment.NewLine);
            }
        }
Example #43
0
        private void LineDown_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FastColoredTextBox textBox = tabControlCode.SelectedTab.Controls[0] as FastColoredTextBox;

            textBox.MoveSelectedLinesDown();
        }
Example #44
0
        /// <summary>
        /// Добавление новой вкладки для редактора запросов.
        /// </summary>
        /// <param name="indexError"></param>
        public void TabControlPageAdd(int indexError)
        {
            string fileName  = Errors[indexError, 1];
            int    indexPage = GetTabIndexByTagValue(fileName);

            if (indexPage > 0)
            {
                return;
            }

            string Code;
            int    LinesCount;
            string FileNameFull = Errors[indexError, 4];

            if (FileNameFull == null)
            {
                return;
            }
            if (!FBAFile.FileReadText(FileNameFull, true, out Code, out LinesCount))
            {
                return;
            }
            tabControl1.TabPages.Add(fileName);
            indexPage = tabControl1.TabPages.Count - 1;
            System.Windows.Forms.TabPage tb = tabControl1.TabPages[indexPage];
            tb.Tag = fileName;
            var fctb1 = new FastColoredTextBox();

            tb.Controls.Add(fctb1);
            fctb1.Text = Code;
            fctb1.Dock = TextBoxCode.Dock;
            fctb1.AutoCompleteBrackets      = TextBoxCode.AutoCompleteBrackets;
            fctb1.AutoScrollMinSize         = TextBoxCode.AutoScrollMinSize;
            fctb1.BookmarkColor             = TextBoxCode.BookmarkColor;
            fctb1.BracketsHighlightStrategy = TextBoxCode.BracketsHighlightStrategy;
            fctb1.Cursor        = TextBoxCode.Cursor;
            fctb1.DisabledColor = TextBoxCode.DisabledColor;
            fctb1.FindEndOfFoldingBlockStrategy = TextBoxCode.FindEndOfFoldingBlockStrategy;
            fctb1.Font         = TextBoxCode.Font;
            fctb1.Language     = TextBoxCode.Language;
            fctb1.LeftBracket  = TextBoxCode.LeftBracket;
            fctb1.RightBracket = TextBoxCode.RightBracket;
            //fctb1.Padding                       = TextBoxCode.Padding;
            fctb1.SelectionColor   = Color.Red;             //TextBoxCode.SelectionColor;
            fctb1.VirtualSpace     = TextBoxCode.VirtualSpace;
            fctb1.Name             = "textCode" + indexPage;
            fctb1.BackColor        = TextBoxCode.BackColor;
            fctb1.CurrentLineColor = TextBoxCode.CurrentLineColor;
            fctb1.VirtualSpace     = TextBoxCode.VirtualSpace;
            fctb1.BorderStyle      = TextBoxCode.BorderStyle;
            fctb1.ReadOnly         = true;

            int firstbookmark = 0;
            int countError    = 0;

            for (int i = 0; i < countPage; i++)
            {
                if (Errors[i, 1] != fileName)
                {
                    continue;
                }
                countError++;
                int N = Errors[i, 2].ToInt(false);
                if (firstbookmark == 0)
                {
                    firstbookmark = N;
                }
                fctb1.BookmarkLine(N - 1);
                fctb1.Navigate(N - 1);
                fctb1.CurrentLineColor = Color.Red;
                tb.Text = fileName + " (" + countError + ")";
            }
            SetCurrentBookmarkForFileName(fileName, firstbookmark);
            fctb1.Navigate(firstbookmark);
        }
Example #45
0
 public void SetTextObject(FastColoredTextBox txt)
 {
     _txtBox = txt;
 }
Example #46
0
        /////////////////////////////////////////////////////////////////////
        // CONSTRUCTOR
        /////////////////////////////////////////////////////////////////////

        public EditorForm()
        {
            InitializeComponent();
            if (IsDesignMode)
            {
                return;
            }

            //title
            lblTitle.Font = App.Theme.Titles.Large.Regular;

            //splash panel
            panMenuPage.Dock = DockStyle.Fill;

            //colours
            btnServerNew.Accent       = btnServerExisting.Accent = 2;
            btnServerTemporary.Accent = 3;
            lblAbout.ForeColor        = lblVersion.ForeColor = App.Theme.Background.Light.Colour;

            //about link
            lblAbout.Cursor      = Cursors.Hand;
            lblAbout.Font        = App.Theme.Controls.Normal.Underline;
            lblAbout.MouseEnter += (s, e) => { lblAbout.ForeColor = App.Theme.Foreground.Mid.Colour; };
            lblAbout.MouseLeave += (s, e) => { lblAbout.ForeColor = App.Theme.Background.Light.Colour; };
            lblAbout.Click      += (s, e) => { App.Website.LaunchWebsite(); };

            //version label
            lblVersion.Text = "v" + Marzersoft.Text.REGEX_VERSION_REPEATING_ZEROES.Replace(App.AssemblyVersion.ToString(), "");
            if (lblVersion.Text.IndexOf('.') == -1)
            {
                lblVersion.Text += ".0";
            }

            //client connection/server browser panel
            btnClient.TextAlign = btnServerNew.TextAlign = btnServerExisting.TextAlign
                                                               = btnServerTemporary.TextAlign = ContentAlignment.MiddleCenter;
            btnClientConnect.Image      = App.Images.Resource("next");
            btnClientCancel.Image       = App.Images.Resource("previous");
            btnClientConnect.ImageAlign = btnClientCancel.ImageAlign = ContentAlignment.MiddleCenter;
            tbClientAddress.Font        = tbClientPassword.Font = tbServerPassword.Font
                                                                      = nudClientUpdateInterval.Font = App.Theme.Monospaced.Normal.Regular;
            tbClientAddress.BackColor = tbClientPassword.BackColor = tbServerPassword.BackColor
                                                                         = nudClientUpdateInterval.BackColor = App.Theme.Background.Light.Colour;
            tbClientAddress.ForeColor = tbClientPassword.ForeColor = tbServerPassword.ForeColor
                                                                         = nudClientUpdateInterval.ForeColor = App.Theme.Foreground.BaseColour;
            lblManualEntry.Font       = lblServerBrowser.Font = App.Theme.Controls.Large.Regular;
            panServerBrowserPage.Dock = DockStyle.Fill;
            dgvServers.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvServers.Columns[1].DefaultCellStyle.Alignment   = DataGridViewContentAlignment.MiddleLeft;
            dgvServers.ShowCellToolTips = true;

            //'connecting' page
            panConnectingPage.Dock       = DockStyle.Fill;
            lblConnectingStatus.Width    = panConnectingPage.ClientSize.Width - 10;
            btnConnectingReconnect.Image = App.Images.Resource("refresh");
            btnConnectingBack.Image      = App.Images.Resource("previous");

            //file dialog filters
            FileFilterFactory filterFactory = new FileFilterFactory();

            filterFactory.Add("Text files", "txt");
            filterFactory.Add("C# files", "cs");
            filterFactory.Add("C/C++ files", "cpp", "h", "hpp", "cxx", "cc", "c", "inl", "inc", "rc", "hxx");
            filterFactory.Add("Log files", "log");
            filterFactory.Add("Javacode files", "java");
            filterFactory.Add("Javascript files", "js");
            filterFactory.Add("Visual Basic files", "vb", "vbs");
            filterFactory.Add("Web files", "htm", "html", "xml", "css", "htaccess", "php");
            filterFactory.Add("XML files", "xml", "xsl", "xslt", "xsd", "dtd");
            filterFactory.Add("PHP scripts", "php");
            filterFactory.Add("SQL scripts", "sql");
            filterFactory.Add("Luascript files", "lua");
            filterFactory.Add("Shell scripts", "bat", "sh", "ps");
            filterFactory.Add("Settings files", "ini", "config", "cfg", "conf", "reg");
            filterFactory.Add("Shader files", "hlsl", "glsl", "fx", "csh", "cshader", "dsh", "dshader",
                              "gsh", "gshader", "hlsli", "hsh", "hshader", "psh", "pshader", "vsh", "vshader");
            filterFactory.Apply(dlgServerCreateNew);
            filterFactory.Apply(dlgServerOpenExisting);

            //form styles
            FormBorderStyle      = FormBorderStyle.None;
            TextFlourishes       = false;
            Text                 = App.Name;
            CustomTitleBar       = true;
            ResizeHandleOverride = true;
            IconOverride         = (b) => { return(null); };
            flatIconImage        = App.Images.Resource("otex_icon_flat", App.Assembly, "OTEX");
            ImageOverride        = (b) => { return(flatIconImage); };

            //settings menu
            settingsForm            = new FlyoutForm(panSettings);
            settingsForm.Accent     = 3;
            settingsButton          = AddCustomTitleBarButton();
            settingsButton.Colour   = App.Theme.GetAccent(3).DarkDark.Colour;
            settingsButton.Image    = App.Images.Resource("cog", App.Assembly, "OTEX");
            settingsButton.OnClick += (b) => { settingsForm.Flyout(PointToScreen(b.Bounds.BottomMiddle())); };

            //logout button
            logoutButton          = AddCustomTitleBarButton();
            logoutButton.Colour   = Color.Red;
            logoutButton.Image    = App.Images.Resource("logout", App.Assembly, "OTEX");
            logoutButton.Visible  = false;
            logoutButton.OnClick += (b) =>
            {
                if (otexServer.Running && otexServer.ClientCount > 1 &&
                    !Logger.WarningQuestion("You are currently running in server mode. "
                                            + "Leaving the session will disconnect the other {0} connected users.\n\nLeave session?", otexServer.ClientCount - 1))
                {
                    return;
                }

                otexClient.Disconnect();
                otexServer.Stop();
            };

            // CREATE OTEX SERVER ///////////////////////////////////////////////

            /*
             * COMP7722: The OTEX Server is a self-contained class. "Host-mode" (i.e.
             * allowing a user to edit a load and edit a document using OTEX Editor without
             * first launching a dedicated server) simply launches a server and a client and
             * directly connects them together internally.
             */
            otexServer = new Server();
            otexServer.OnThreadException += (s, e) =>
            {
                Logger.W("Server: {0}: {1}", e.InnerException.GetType().FullName, e.InnerException.Message);
            };
            otexServer.OnStarted += (s) =>
            {
                Logger.I("Server: started for {0} on port {1}", s.FilePath, s.Port);
            };
            otexServer.OnClientConnected += (s, id) =>
            {
                Logger.I("Server: Client {0} connected.", id);
            };
            otexServer.OnClientDisconnected += (s, id) =>
            {
                Logger.I("Server: Client {0} disconnected.", id);
            };
            otexServer.OnStopped += (s) =>
            {
                Logger.I("Server: stopped.");
            };
            otexServer.OnFileSynchronized += (s) =>
            {
                Logger.I("Server: File synchronized.");
            };

            // CREATE OTEX CLIENT ///////////////////////////////////////////////

            /*
             * COMP7722: Like the server, the OTEX Client is a self-contained class.
             * All of the editor and OT functionality is handled via callbacks.
             */
            otexClient = new Client();
            otexClient.UpdateInterval     = (float)nudClientUpdateInterval.Value;
            otexClient.OnThreadException += (c, e) =>
            {
                Logger.W("Client: {0}: {1}", e.InnerException.GetType().Name, e.InnerException.Message);
            };
            otexClient.OnConnected += (c) =>
            {
                Logger.I("Client: connected to {0}:{1}.", c.ServerAddress, c.ServerPort);
                this.Execute(() =>
                {
                    /*
                     * COMP7722: when the client first connects, initial textbox contents is set to "",
                     * but must be done so while operation generation is disabled so
                     * TextChanging/TextChanged don't do diffs and push operations.
                     */
                    disableOperationGeneration = true;
                    tbEditor.Text = "";
                    disableOperationGeneration = false;

                    string ext = Path.GetExtension(c.ServerFilePath).ToLower();
                    if (ext.Length > 0 && (ext = ext.Substring(1)).Length > 0)
                    {
                        switch (ext)
                        {
                        case "cs": tbEditor.Language = Language.CSharp; break;

                        case "htm": tbEditor.Language = Language.HTML; break;

                        case "html": tbEditor.Language = Language.HTML; break;

                        case "js": tbEditor.Language = Language.JS; break;

                        case "lua": tbEditor.Language = Language.Lua; break;

                        case "php": tbEditor.Language = Language.PHP; break;

                        case "sql": tbEditor.Language = Language.SQL; break;

                        case "vb": tbEditor.Language = Language.VB; break;

                        case "vbs": tbEditor.Language = Language.VB; break;

                        case "xml": tbEditor.Language = Language.XML; break;

                        default: tbEditor.Language = Language.Custom; break;
                        }
                    }
                    else
                    {
                        tbEditor.Language = Language.Custom;
                    }

                    logoutButton.Visible = true;
                    EditorPage           = true;
                    tbEditor.Focus();
                }, false);
            };
            otexClient.OnRemoteOperations += (c, operations) =>
            {
                /*
                 * COMP7722: this event handler is fired when an OTEX Client receives remote
                 * operations from the server (they're already transformed internally, and just need
                 * to be applied).
                 *
                 * The "Execute" function is an extension method that ensures whatever delegate function
                 * is passed in will always be run on the main UI thread of a windows forms application,
                 * so this ensures the user is prevented from typing while the remote operations are
                 * being applied (virtually instantaneous).
                 */
                this.Execute(() =>
                {
                    disableOperationGeneration = true;

                    foreach (var operation in operations)
                    {
                        if (operation.IsInsertion)
                        {
                            tbEditor.InsertTextAndRestoreSelection(
                                new Range(tbEditor, tbEditor.PositionToPlace(operation.Offset),
                                          tbEditor.PositionToPlace(operation.Offset)),
                                operation.Text, null);
                        }
                        else if (operation.IsDeletion)
                        {
                            tbEditor.InsertTextAndRestoreSelection(
                                new Range(tbEditor, tbEditor.PositionToPlace(operation.Offset),
                                          tbEditor.PositionToPlace(operation.Offset + operation.Length)),
                                "", null);
                        }
                    }

                    disableOperationGeneration = false;
                }, false);
            };
            otexClient.OnMetadataUpdated += (c, id, md) =>
            {
                lock (remoteClients)
                {
                    remoteClients[id] = md.Deserialize <EditorClient>();
                }
                this.Execute(() => { tbEditor.Refresh(); });
            };
            otexClient.OnDisconnected += (c, serverSide) =>
            {
                Logger.I("Client: disconnected{0}.", serverSide ? " (connection closed by server)" : "");
                lock (remoteClients)
                {
                    remoteClients.Clear();
                }
                localClient.SelectionStart = 0;
                localClient.SelectionEnd   = 0;
                if (!closing)
                {
                    this.Execute(() =>
                    {
                        //non-host
                        if (serverSide)
                        {
                            if (lastConnectionEndpoint != null)
                            {
                                ConnectionLostPage = true;
                            }
                            else
                            {
                                MainMenuPage = true;
                            }
                        }
                        else
                        {
                            MainMenuPage = true;
                        }

                        Text = App.Name;
                        logoutButton.Visible = false;
                    });
                }
            };

            // CREATE OTEX SERVER LISTENER //////////////////////////////////////

            /*
             * COMP7722: I've given OTEX Servers the ability to advertise their existence to the
             * local network over UDP, so the ServerListener is a simple UDP listener. When new servers
             * are identified, or known servers change in some way, events are fired.
             */
            try
            {
                otexServerListener = new ServerListener();
                otexServerListener.OnThreadException += (sl, e) =>
                {
                    Logger.W("ServerListener: {0}: {1}", e.InnerException.GetType().FullName, e.InnerException.Message);
                };
                otexServerListener.OnServerAdded += (sl, s) =>
                {
                    Logger.I("ServerListener: new server {0}: {1}", s.ID, s.EndPoint);
                    this.Execute(() =>
                    {
                        var row = dgvServers.AddRow(s.Name.Length > 0 ? s.Name : "OTEX Server", s.TemporaryDocument ? "Yes" : "", s.EndPoint.Address,
                                                    s.EndPoint.Port, s.RequiresPassword ? "Yes" : "", string.Format("{0} / {1}", s.ClientCount, s.MaxClients), 0);
                        row.Tag = s;
                        s.Tag   = row;
                    });

                    s.OnUpdated += (sd) =>
                    {
                        Logger.I("ServerDescription: {0} updated.", sd.ID);
                        this.Execute(() =>
                        {
                            (s.Tag as DataGridViewRow).Update(s.Name.Length > 0 ? s.Name : "OTEX Server", s.TemporaryDocument ? "Yes" : "", s.EndPoint.Address,
                                                              s.EndPoint.Port, s.RequiresPassword ? "Yes" : "", string.Format("{0} / {1}", s.ClientCount, s.MaxClients), 0);
                        });
                    };

                    s.OnInactive += (sd) =>
                    {
                        Logger.I("ServerDescription: {0} inactive.", sd.ID);
                        this.Execute(() =>
                        {
                            var row = (s.Tag as DataGridViewRow);
                            row.DataGridView.Rows.Remove(row);
                            row.Tag = null;
                            s.Tag   = null;
                        });
                    };
                };
            }
            catch (Exception exc)
            {
                Logger.ErrorMessage("An error occurred while creating the server listener:\n\n{0}"
                                    + "\n\nYou can still use OTEX Editor, but the \"Public Documents\" list will be empty.",
                                    exc.Message);
                return;
            }

            // CREATE TEXT EDITOR ////////////////////////////////////////////////
            tbEditor                    = new FastColoredTextBox();
            tbEditor.Parent             = this;
            tbEditor.Dock               = DockStyle.Fill;
            tbEditor.BackBrush          = App.Theme.Background.Mid.Brush;
            tbEditor.IndentBackColor    = App.Theme.Background.Dark.Colour;
            tbEditor.ServiceLinesColor  = App.Theme.Background.Light.Colour;
            tbEditor.Font               = new Font(App.Theme.Monospaced.Normal.Regular.FontFamily, 11.0f);
            tbEditor.WordWrap           = true;
            tbEditor.WordWrapAutoIndent = true;
            tbEditor.WordWrapMode       = WordWrapMode.WordWrapControlWidth;
            tbEditor.TabLength          = 4;
            tbEditor.LineInterval       = 2;
            tbEditor.HotkeysMapping.Remove(Keys.Control | Keys.H);                     //remove default "replace" (CTRL + H, wtf?)
            tbEditor.HotkeysMapping[Keys.Control | Keys.R] = FCTBAction.ReplaceDialog; // CTRL + R for replace
            tbEditor.HotkeysMapping[Keys.Control | Keys.Y] = FCTBAction.Undo;          // CTRL + Y for undo

            /*
             * COMP7722: In this editor example, Operations are not generated by directly
             * intercepting key press events and the like, since they do not take special
             * circumstances like Undo, Redo, and text dragging with the mouse into account. Instead,
             * I've used a Least-Common-Substring-based diff generator (in this case, a package
             * called DiffPlex: https://www.nuget.org/packages/DiffPlex/) to compare text pre-
             * and post-change, and create the operations based on the calculated diffs.
             *
             * This does of course cause a slight overhead; in testing with large documents
             * (3.5mb of plain text, which is a lot!), diff calculation took ~100ms. Documents that
             * were more realistically-sized took ~3ms (on the same machine), which is imperceptible.
             *
             * I've also implemented some basic awareness painting, so the current position, line
             * and selection of other editors will be rendered (see PaintLine).
             */
            tbEditor.TextChanging += (sender, args) =>
            {
                if (disableOperationGeneration || !otexClient.Connected)
                {
                    return;
                }

                //cache previous version of the text
                previousText = tbEditor.Text;
            };
            tbEditor.TextChanged += (sender, args) =>
            {
                if (disableOperationGeneration || !otexClient.Connected)
                {
                    return;
                }

                //do diff on two versions of text
                var currentText = tbEditor.Text;
                var diffs       = differ.CreateCharacterDiffs(previousText, currentText, false, false);

                //convert changes into operations
                int position = 0;
                foreach (var diff in diffs.DiffBlocks)
                {
                    //skip unchanged characters
                    position = Math.Min(diff.InsertStartB, currentText.Length);

                    //process a deletion
                    if (diff.DeleteCountA > 0)
                    {
                        otexClient.Delete((uint)position, (uint)diff.DeleteCountA);
                    }

                    //process an insertion
                    if (position < (diff.InsertStartB + diff.InsertCountB))
                    {
                        otexClient.Insert((uint)position, currentText.Substring(position, diff.InsertCountB));
                    }
                }
            };
            tbEditor.SelectionChanged += (s, e) =>
            {
                if (!otexClient.Connected)
                {
                    return;
                }
                var sel = tbEditor.Selection;
                localClient.SelectionStart = tbEditor.PlaceToPosition(sel.Start);
                localClient.SelectionEnd   = tbEditor.PlaceToPosition(sel.End);
                PushUpdatedMetadata();
            };
            tbEditor.PaintLine += (s, e) =>
            {
                if (!otexClient.Connected || remoteClients.Count == 0)
                {
                    return;
                }

                Range lineRange = new Range(tbEditor, e.LineIndex);
                lock (remoteClients)
                {
                    var len = tbEditor.TextLength;
                    foreach (var kvp in remoteClients)
                    {
                        //check range
                        var selStart = tbEditor.PositionToPlace(kvp.Value.SelectionStart.Clamp(0, len));
                        var selEnd   = tbEditor.PositionToPlace(kvp.Value.SelectionEnd.Clamp(0, len));
                        var selRange = new Range(tbEditor, selStart, selEnd);
                        var range    = lineRange.GetIntersectionWith(selRange);
                        if (range.Length == 0 && !lineRange.Contains(selStart))
                        {
                            continue;
                        }

                        var ptStart = tbEditor.PlaceToPoint(range.Start);
                        var ptEnd   = tbEditor.PlaceToPoint(range.End);
                        var caret   = lineRange.Contains(selStart);
                        int colour  = kvp.Value.Colour & 0x00FFFFFF;

                        //draw "current line" fill
                        if (caret && selRange.Length == 0)
                        {
                            using (SolidBrush b = new SolidBrush((colour | 0x09000000).ToColour()))
                                e.Graphics.FillRectangle(b, e.LineRect);
                        }
                        //draw highlight
                        if (range.Length > 0)
                        {
                            using (SolidBrush b = new SolidBrush((colour | 0x20000000).ToColour()))
                                e.Graphics.FillRectangle(b, new Rectangle(ptStart.X, e.LineRect.Y,
                                                                          ptEnd.X - ptStart.X, e.LineRect.Height));
                        }
                        //draw caret
                        if (caret)
                        {
                            ptStart = tbEditor.PlaceToPoint(selStart);
                            using (Pen p = new Pen((colour | 0xBB000000).ToColour()))
                            {
                                p.Width = 2;
                                e.Graphics.DrawLine(p, ptEnd.X, e.LineRect.Top,
                                                    ptEnd.X, e.LineRect.Bottom);
                            }
                        }
                    }
                }
            };

            // CLIENT COLOURS ////////////////////////////////////////////////////
            cbClientColour.RegenerateItems(
                false, //darks
                true,  //mids
                false, //lights
                false, //transparents
                false, //monochromatics
                0.15f, //similarity threshold
                new Color[] { Color.Blue, Color.MediumBlue, Color.Red, Color.Fuchsia, Color.Magenta } //exlude (colours that contrast poorly with the app theme)
                );
            var cols = cbClientColour.Items.OfType <Color>().ToList();
            var col  = otexClient.ID.ToColour(cols.ToArray());

            ClientColour = col;
            cbClientColour.SelectedIndex = cols.IndexOf(col);
        }
Example #47
0
 public SemanticAnalysis(FastColoredTextBox code)
 {
     this.txtCode = code;
 }
        public string GetRtf(Range r)
        {
            this.tb = r.tb;
            var styles         = new Dictionary <StyleIndex, object>();
            var sb             = new StringBuilder();
            var tempSB         = new StringBuilder();
            var currentStyleId = StyleIndex.None;

            r.Normalize();
            int currentLine = r.Start.iLine;

            styles[currentStyleId] = null;
            colorTable.Clear();
            //
            var lineNumberColor = GetColorTableNumber(r.tb.LineNumberColor);

            if (IncludeLineNumbers)
            {
                tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", currentLine + 1, lineNumberColor);
            }
            //
            foreach (Place p in r)
            {
                Char c = r.tb[p.iLine][p.iChar];
                if (c.style != currentStyleId)
                {
                    Flush(sb, tempSB, currentStyleId);
                    currentStyleId         = c.style;
                    styles[currentStyleId] = null;
                }

                if (p.iLine != currentLine)
                {
                    for (int i = currentLine; i < p.iLine; i++)
                    {
                        tempSB.AppendLine(@"\line");
                        if (IncludeLineNumbers)
                        {
                            tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", i + 2, lineNumberColor);
                        }
                    }
                    currentLine = p.iLine;
                }
                switch (c.c)
                {
                case '\\':
                    tempSB.Append(@"\\");
                    break;

                case '{':
                    tempSB.Append(@"\{");
                    break;

                case '}':
                    tempSB.Append(@"\}");
                    break;

                default:
                    var ch   = c.c;
                    var code = (int)ch;
                    if (code < 128)
                    {
                        tempSB.Append(c.c);
                    }
                    else
                    {
                        tempSB.AppendFormat(@"{{\u{0}}}", code);
                    }
                    break;
                }
            }
            Flush(sb, tempSB, currentStyleId);

            //build color table
            var list = new SortedList <int, Color>();

            foreach (var pair in colorTable)
            {
                list.Add(pair.Value, pair.Key);
            }

            tempSB.Length = 0;
            tempSB.AppendFormat(@"{{\colortbl;");

            foreach (var pair in list)
            {
                tempSB.Append(GetColorAsString(pair.Value) + ";");
            }
            tempSB.AppendLine("}");

            //
            if (UseOriginalFont)
            {
                sb.Insert(0, string.Format(@"{{\fonttbl{{\f0\fmodern {0};}}}}{{\fs{1} ",
                                           tb.Font.Name, (int)(2 * tb.Font.SizeInPoints), tb.CharHeight));
                sb.AppendLine(@"}");
            }

            sb.Insert(0, tempSB.ToString());

            sb.Insert(0, @"{\rtf1\ud\deff0");
            sb.AppendLine(@"}");

            return(sb.ToString());
        }
Example #49
0
 internal MacrosManager(FastColoredTextBox ctrl)
 {
     UnderlayingControl        = ctrl;
     AllowMacroRecordingByUser = true;
 }
 /// <summary>
 ///     Required method for Designer support - do not modify
 ///     the contents of this method with the code editor.
 /// </summary>
 void InitializeComponent()
 {
     components   = new Container();
     txtOutput    = new FastColoredTextBox();
     txtInput     = new FastColoredTextBox();
     btnProcess   = new Button();
     btnClipboard = new Button();
     pnlLayout    = new TableLayoutPanel();
     pnlLayout.SuspendLayout();
     SuspendLayout();
     ((ISupportInitialize)txtOutput).BeginInit();
     ((ISupportInitialize)txtInput).BeginInit();
     //
     // txtOutput
     //
     txtOutput.Location = new Point(3, 152);
     txtOutput.Name     = "txtOutput";
     txtOutput.ReadOnly = true;
     txtOutput.Size     = new Size(309, 67);
     txtOutput.TabIndex = 7;
     TextEditorHelper.Initialize(txtOutput);
     //
     // txtInput
     //
     txtInput.Location = new Point(3, 152);
     txtInput.Name     = "txtInput";
     txtInput.Size     = new Size(309, 67);
     txtInput.TabIndex = 5;
     TextEditorHelper.Initialize(txtInput);
     //
     // btnProcess
     //
     btnProcess.Dock     = DockStyle.Fill;
     btnProcess.Location = new Point(3, 259);
     btnProcess.Name     = "btnProcess";
     btnProcess.Size     = new Size(844, 39);
     btnProcess.TabIndex = 6;
     btnProcess.Text     = "Process";
     btnProcess.UseVisualStyleBackColor = true;
     btnProcess.Click += btnProcess_Click;
     //
     // btnClipboard
     //
     btnClipboard.Dock     = DockStyle.Fill;
     btnClipboard.Location = new Point(3, 530);
     btnClipboard.Name     = "btnClipboard";
     btnClipboard.Size     = new Size(844, 41);
     btnClipboard.TabIndex = 8;
     btnClipboard.Text     = "Copy to Clipboard";
     btnClipboard.UseVisualStyleBackColor = true;
     btnClipboard.Click += btnClipboard_Click;
     //
     // pnlLayout
     //
     pnlLayout.ColumnCount = 1;
     pnlLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
     pnlLayout.Controls.Add(btnClipboard, 0, 3);
     pnlLayout.Controls.Add(txtOutput, 0, 2);
     pnlLayout.Controls.Add(btnProcess, 0, 1);
     pnlLayout.Controls.Add(txtInput, 0, 0);
     pnlLayout.Dock     = DockStyle.Fill;
     pnlLayout.Location = new Point(0, 0);
     pnlLayout.Name     = "pnlLayout";
     pnlLayout.RowCount = 4;
     pnlLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 241F));
     pnlLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 45F));
     pnlLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 241F));
     pnlLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 45F));
     pnlLayout.Size     = new Size(850, 574);
     pnlLayout.TabIndex = 10;
     //
     // StringUtilView
     //
     AutoScaleDimensions = new SizeF(7F, 18F);
     AutoScaleMode       = AutoScaleMode.Font;
     BackColor           = Color.Transparent;
     Controls.Add(pnlLayout);
     Font   = new Font("Trebuchet MS", 9.75F, FontStyle.Regular, GraphicsUnit.Point, 0);
     Margin = new Padding(3, 4, 3, 4);
     Name   = "StringUtilView";
     Size   = new Size(850, 574);
     ((ISupportInitialize)txtOutput).EndInit();
     ((ISupportInitialize)txtInput).EndInit();
     pnlLayout.ResumeLayout(false);
     ResumeLayout(false);
     PerformLayout();
 }
        public static void BookmarkChangeNeeded(string feature, FastColoredTextBox fctbCurrentFirmware, FastColoredTextBox fctbNewFirmware)
        {
            // Get the last occurance for the feature in current firmware
            int    currentrow   = GetFirmwareFeatureRow(fctbCurrentFirmware, feature);
            string currentValue = GetFirmwareFeatureValue(fctbCurrentFirmware, feature);
            string currentLine  = fctbCurrentFirmware.GetLineText(currentrow).Trim();

            // Get the last occurance for the feature in new firmware
            int    newrow   = GetFirmwareFeatureRow(fctbNewFirmware, feature);
            string newValue = GetFirmwareFeatureValue(fctbNewFirmware, feature);
            string newLine  = fctbNewFirmware.GetLineText(newrow).Trim();


            if ((newrow == 0) | currentValue != newValue)
            {
                fctbCurrentFirmware.BookmarkLine(currentrow);
                return;
            }

            //if (currentLine.StartsWith("//") && !newLine.StartsWith("//"))
            //{
            //    fctbCurrentFirmware.BookmarkLine(currentrow);
            //    return;
            //}
            //if (!currentLine.StartsWith("//") && newLine.StartsWith("//"))
            //{
            //    fctbCurrentFirmware.BookmarkLine(currentrow);
            //    return;
            //}


            fctbCurrentFirmware.UnbookmarkLine(currentrow);
        }
Example #52
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.InitialDirectory = @"~";
            ofd.Title            = "Open File";

            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.Multiselect     = true;

            ofd.DefaultExt       = "txt";
            ofd.Filter           = "Text files (*.txt)|*.txt |All files (*.*)|*.*";
            ofd.FilterIndex      = 2;
            ofd.RestoreDirectory = true;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                foreach (string path in ofd.FileNames)
                {
                    var tab  = new TabPage(Path.GetFileName(path));
                    var fctb = new FastColoredTextBox();
                    fctb.BackColor = fctb.IndentBackColor = Color.FromArgb(30, 30, 30);
                    fctb.ForeColor = Color.White;
                    fctb.Dock      = DockStyle.Fill;

                    string ext = Path.GetExtension(path);
                    switch (ext)
                    {
                    case ".cs":
                        fctb.Language = Language.CSharp;
                        break;

                    case ".js":
                        fctb.Language = Language.JS;
                        break;

                    case ".html":
                        fctb.Language = Language.HTML;
                        break;

                    case ".vb":
                        fctb.Language = Language.VB;
                        break;

                    case ".lua":
                        fctb.Language = Language.Lua;
                        break;

                    case ".php":
                        fctb.Language = Language.PHP;
                        break;

                    case ".sql":
                        fctb.Language = Language.SQL;
                        break;

                    case ".xml":
                        fctb.Language = Language.XML;
                        break;

                    default:
                        fctb.Language = Language.Custom;
                        break;
                    }
                    fctb.TextChanged += FCTBTextChanged;
                    fctb.OpenFile(path);
                    tab.Controls.Add(fctb);
                    tabControl1.Controls.Add(tab);
                }
            }
        }
 public FromXMLfileSyntaxSource(FastColoredTextBox textbox) : base(textbox)
 {
     XMLfile = textbox.DescriptionFile;
     LoadStyleSchema();
 }
Example #54
0
        /// <summary>
        /// RichTextBox自动补全
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="obj2"></param>
        public static void FastColoredTextBoxTextChangedVoid(object obj1, object obj2)
        {
            if (th != null)
            {
                th.Abort(); th = null;
            }
            FastColoredTextBox rtb        = (FastColoredTextBox)obj1;
            string             result     = "";
            string             text       = rtb.Text;
            string             startText  = text.Substring(0, rtb.SelectionStart);
            string             endtext    = "";
            string             selectText = "";

            if (rtb.SelectionStart != text.Length)
            {
                if (startText != "")
                {
                    endtext = text.Replace(startText, "");
                }
            }
            string[] array = System.Text.RegularExpressions.Regex.Split(startText, @"\s{1,}");
            if (array.Length >= 1)
            {
                selectText = array[array.Length - 1];
            }
            else
            {
                selectText = "";
            }

            if (th == null)
            {
                th = new System.Threading.Thread((System.Threading.ThreadStart) delegate
                {
                    Form1 f;
                    Point p = winApi.CaretPos();
                    f       = new Form1(selectText, textlist, new Point(p.X + 10, p.Y + 20));
                    try
                    {
                        if (!f.IsDisposed)
                        {
                            Application.Run(f);
                            result = f.result;
                            if (result != "")
                            {
                                rtb.BeginInvoke(new Action(() =>
                                {
                                    startText          = startText.Substring(0, startText.Length - selectText.Length) + result; //处理
                                    rtb.Text           = startText + endtext;
                                    rtb.SelectionStart = startText.Length;                                                      //增加后的光标位置
                                }));
                            }
                        }
                    }
                    catch (Exception ex) { f.Close(); }
                });
                th.SetApartmentState(ApartmentState.STA);
                th.IsBackground = true;
                th.Start();
            }
        }
Example #55
0
        private void _ShowMaxExceedMessage(FastColoredTextBox fctb)
        {
            string msg = "Error : Too large to open. ( > {0})";

            fctb.Text = string.Format(msg, Functions.FormatMemory(MaxFileSIZ));
        }
Example #56
0
 public static void SetControls(FastColoredTextBox scriptEditor, ListBox scriptList)
 {
     ScriptEditor = scriptEditor;
     ScriptList   = scriptList;
 }
 private void newToolStripButton_Click(object sender, EventArgs e)
 {
     FastColoredTextBox tb = CreateTab(null);
 }
Example #58
0
 protected virtual void Subscribe(FastColoredTextBox target)
 {
     target.Scroll              += new ScrollEventHandler(target_Scroll);
     target.SelectionChanged    += new EventHandler(target_SelectionChanged);
     target.VisibleRangeChanged += new EventHandler(target_VisibleRangeChanged);
 }
Example #59
0
        private void CreateTab(string fileName)
        {
            try
            {
                var tb = new FastColoredTextBox();
                tb.BackColor       = Color.FromArgb(31, 39, 42);
                tb.ForeColor       = Color.FromArgb(200, 200, 200);
                tb.IndentBackColor = Color.FromArgb(5, 7, 15);
                tb.LineNumberColor = Color.FromArgb(10, 192, 200);
                //  tb.SelectionColor =  Color.FromArgb(200,255,240,150);
                tb.SelectionColor = Color.FromArgb(255, 240, 150);
                ///   tb.FoldingIndicatorColor =  Color.FromArgb(240,208,88,37);
                tb.FoldingIndicatorColor = Color.FromArgb(240, 255, 196, 68);
                //   tb.High =  Color.FromArgb(240,208,88,37);

                // tb.Font = new Font("Courier New", 9.75f,FontStyle.Bold);
                tb.Font             = new Font("Consolas", 9.75f, FontStyle.Bold);
                tb.ContextMenuStrip = cmMain;
                tb.Dock             = DockStyle.Fill;
                tb.BorderStyle      = BorderStyle.Fixed3D;
                //tb.VirtualSpace = true;
                tb.LeftPadding = 17;
                tb.Language    = Language.CSharp;
                tb.AddStyle(sameWordsStyle);//same words style
                var tab = new FATabStripItem(fileName != null?Path.GetFileName(fileName):"[new]", tb);
                tab.Tag = fileName;

                //  tab.Cor = Color.FromArgb(255,196,68);
                if (fileName != null)
                {
                    tb.OpenFile(fileName);
                }
                tb.Tag = new TbInfo();
                tsFiles.AddTab(tab);


                tsFiles.SelectedItem = tab;
                tb.Focus();
                // tb.DelayedTextChangedInterval = 1000;
                tb.DelayedTextChangedInterval = 1;
                // tb.DelayedEventsInterval = 500;
                tb.DelayedEventsInterval    = 1;
                tb.TextChangedDelayed      += new EventHandler <TextChangedEventArgs>(tb_TextChangedDelayed);
                tb.SelectionChangedDelayed += new EventHandler(tb_SelectionChangedDelayed);
                tb.KeyDown         += new KeyEventHandler(tb_KeyDown);
                tb.MouseMove       += new MouseEventHandler(tb_MouseMove);
                tb.ChangedLineColor = changedLineColor;
                if (btHighlightCurrentLine.Checked)
                {
                    tb.CurrentLineColor = currentLineColor;
                }
                tb.ShowFoldingLines      = btShowFoldingLines.Checked;
                tb.HighlightingRangeType = HighlightingRangeType.VisibleRange;
                //create autocomplete popup menu
                AutocompleteMenu popupMenu = new AutocompleteMenu(tb);
                popupMenu.Items.ImageList = ilAutocomplete;
                popupMenu.Opening        += new EventHandler <CancelEventArgs>(popupMenu_Opening);
                BuildAutocompleteMenu(popupMenu);
                (tb.Tag as TbInfo).popupMenu = popupMenu;


                tab.BackColor = Color.FromArgb(255, 196, 68); //NotWork?
            }
            catch (Exception ex)
            {
                if (MessageBox.Show(ex.Message, "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.Retry)
                {
                    CreateTab(fileName);
                }
            }
        }
Example #60
0
 public CustomSyntaxSource(FastColoredTextBox textbox) : base(textbox)
 {
 }