Beispiel #1
0
        private List <List <Atom> > ReadMatrixCells(
            TexFormulaParser parser,
            TexFormula formula,
            SourceSpan source,
            ICommandEnvironment parentEnvironment)
        {
            var rows = new List <List <Atom> > {
                new List <Atom>()
            };                                                    // enter first row by default

            // Commands from the environment will add all the finished cells to the matrix body, but the last one should
            // be extracted here.
            var environment  = new MatrixInternalEnvironment(parentEnvironment, rows);
            var lastCellAtom = parser.Parse(source, formula.TextStyle, environment).RootAtom;

            if (lastCellAtom != null)
            {
                var lastRow = rows.LastOrDefault();
                if (lastRow == null)
                {
                    rows.Add(lastRow = new List <Atom>());
                }

                lastRow.Add(lastCellAtom);
            }

            MakeRectangular(rows);

            return(rows);
        }
Beispiel #2
0
            public CommandProcessingResult ProcessCommand(CommandContext context)
            {
                var source     = context.CommandSource;
                var position   = context.ArgumentsStartPosition;
                var topFormula = context.Parser.Parse(
                    TexFormulaParser.ReadElement(source, ref position),
                    context.Formula.TextStyle,
                    context.Environment.CreateChildEnvironment());
                var bottomFormula = context.Parser.Parse(
                    TexFormulaParser.ReadElement(source, ref position),
                    context.Formula.TextStyle,
                    context.Environment.CreateChildEnvironment());
                var start      = context.CommandNameStartPosition;
                var atomSource = source.Segment(start, position - start);
                var topAtom    = new List <Atom?> {
                    topFormula.RootAtom
                };
                var bottomAtom = new List <Atom?> {
                    bottomFormula.RootAtom
                };
                var atoms = new List <List <Atom?> > {
                    topAtom, bottomAtom
                };
                var matrixAtom = new MatrixAtom(atomSource, atoms, MatrixCellAlignment.Center);
                var left       = new SymbolAtom(atomSource, "(", TexAtomType.Opening, true);
                var right      = new SymbolAtom(atomSource, ")", TexAtomType.Closing, true);
                var fencedAtom = new FencedAtom(atomSource, matrixAtom, left, right);

                return(new CommandProcessingResult(fencedAtom, position));
            }
Beispiel #3
0
        static TexPredefinedFormulaParser()
        {
            typeMappings    = new Dictionary <string, Type>();
            argValueParsers = new Dictionary <string, ArgumentValueParser>();
            actionParsers   = new Dictionary <string, ActionParser>();
            formulaParser   = new TexFormulaParser();

            typeMappings.Add("Formula", typeof(TexFormula));
            typeMappings.Add("string", typeof(string));
            typeMappings.Add("double", typeof(double));
            typeMappings.Add("int", typeof(int));
            typeMappings.Add("bool", typeof(bool));
            typeMappings.Add("char", typeof(char));
            typeMappings.Add("Color", typeof(Color));
            typeMappings.Add("Unit", typeof(TexUnit));
            typeMappings.Add("AtomType", typeof(TexAtomType));

            actionParsers.Add("CreateFormula", new CreateTeXFormulaParser());
            actionParsers.Add("MethodInvocation", new MethodInvocationParser());
            actionParsers.Add("Return", new ReturnParser());

            argValueParsers.Add("Formula", new TeXFormulaValueParser());
            argValueParsers.Add("string", new StringValueParser());
            argValueParsers.Add("double", new DoubleValueParser());
            argValueParsers.Add("int", new IntValueParser());
            argValueParsers.Add("bool", new BooleanValueParser());
            argValueParsers.Add("char", new CharValueParser());
            argValueParsers.Add("Color", new ColorConstantValueParser());
            argValueParsers.Add("Unit", new EnumParser(typeof(TexUnit)));
            argValueParsers.Add("AtomType", new EnumParser(typeof(TexAtomType)));
        }
Beispiel #4
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="DifferenceQuotientDialog" /> class.
        /// </summary>
        public DifferenceQuotientDialog()
        {
            this.InitializeComponent();

            var formulaParser   = new TexFormulaParser();
            var forwardFormula  = formulaParser.Parse("v(t)=\\frac{s(t+\\Delta t)-s(t)}{\\Delta t}");
            var centralFormula  = formulaParser.Parse("v(t)=\\frac{s(t+\\Delta t)-s(t-\\Delta t )}{2\\cdot \\Delta t}");
            var backwardFormula = formulaParser.Parse("v(t)=\\frac{s(t)-s(t-\\Delta t )}{\\Delta t}");

            // Render formula to visual.
            var forwardVisual   = new DrawingVisual();
            var forwardRenderer = forwardFormula.GetRenderer(TexStyle.Display, 14d);

            using (var drawingContext = forwardVisual.RenderOpen())
            {
                forwardRenderer.Render(drawingContext, 0, 1);
            }

            this.ForwardFormulaContainerElement.Visual = forwardVisual;

            // Render formula to visual.
            var centralVisual   = new DrawingVisual();
            var centralRenderer = centralFormula.GetRenderer(TexStyle.Display, 14d);

            using (var drawingContext = centralVisual.RenderOpen())
            {
                centralRenderer.Render(drawingContext, 0, 1);
            }

            this.CentralFormulaContainerElement.Visual = centralVisual;

            // Render formula to visual.
            var backwardVisual   = new DrawingVisual();
            var backwardRenderer = backwardFormula.GetRenderer(TexStyle.Display, 14d);

            using (var drawingContext = backwardVisual.RenderOpen())
            {
                backwardRenderer.Render(drawingContext, 0, 1);
            }

            this.BackwardFormulaContainerElement.Visual = backwardVisual;

            switch (Viana.Project.ProcessingData.DifferenceQuotientType)
            {
            case DifferenceQuotientType.Forward:
                this.ForwardRadioButton.IsChecked = true;
                break;

            case DifferenceQuotientType.Backward:
                this.BackwardRadioButton.IsChecked = true;
                break;

            case DifferenceQuotientType.Central:
                this.CentralRadioButton.IsChecked = true;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public SampleMatrixViewModel()
        {
            PluginName = PluginName.SampleMatrix;
            matrix     = Matrix <double> .Build.Dense(3, 3);

            formulaParser = new TexFormulaParser();
            InputText     = "1+1=2";
        }
        private void DisplayEquation()
        {
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(eqnLaTeX);
            var pngBytes = formula.RenderToPng(15.0, 0.0, 0.0, "Times New Roman");

            pictureBoxEquation.Image = ByteToImage(pngBytes);
        }
Beispiel #7
0
        public BitmapSource RenderFormula(string data)
        {
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(data);
            var renderer = formula.GetRenderer(TexStyle.Display, 15.0, "Arial");

            return(renderer.RenderToBitmap(0.0, 0.0));
        }
Beispiel #8
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.formulaParser = new TexFormulaParser();

            var testFormula1 = "\\int_0^{\\infty}{x^{2n} e^{-a x^2} dx} = \\frac{2n-1}{2a} \\int_0^{\\infty}{x^{2(n-1)} e^{-a x^2} dx} = \\frac{(2n-1)!!}{2^{n+1}} \\sqrt{\\frac{\\pi}{a^{2n+1}}}";
            var testFormula2 = "\\int_a^b{f(x) dx} = (b - a) \\sum_{n = 1}^{\\infty}  {\\sum_{m = 1}^{2^n  - 1} { ( { - 1} )^{m + 1} } } 2^{ - n} f(a + m ( {b - a}  )2^{-n} )";
            var testFormula3 = @"L = \int_a^b \sqrt[4]{ \left| \sum_{i,j=1}^ng_{ij}\left(\gamma(t)\right) \left[\frac{d}{dt}x^i\circ\gamma(t) \right] \left{\frac{d}{dt}x^j\circ\gamma(t) \right} \right|}dt";

            this.inputTextBox.Text = testFormula3;
        }
        private string GenerateImage(string latex, string filename)
        {
            string fileName = System.AppDomain.CurrentDomain.BaseDirectory;

            fileName += filename;
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(latex);
            var pngBytes = formula.RenderToPng(100.0, 0.0, 0.0, "Times New Roman");

            File.WriteAllBytes(fileName, pngBytes);
            return(fileName);
        }
Beispiel #10
0
        private void Button01_Click(object sender, RoutedEventArgs e)
        {
            //const string latex = @"\left(x^2 + 2 \cdot x + 2\right) = 0 \frac{2+2}{2} \text{Русские ЛаТеХ}";
            const string latex = @"\frac{Wt}{m ^{\circ} C}";
            // \text{Русские ЛаТеХ}
            const string fileName = @"D:\ProjectsVS2017\WPFTests\latex_out";

            var parser  = new TexFormulaParser();
            var formula = parser.Parse(latex);
//            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Cambria Math");

            File.WriteAllBytes(fileName, pngBytes);
        }
Beispiel #11
0
            public CommandProcessingResult ProcessCommand(CommandContext context)
            {
                var source           = context.CommandSource;
                var position         = context.ArgumentsStartPosition;
                var underlineFormula = context.Parser.Parse(
                    TexFormulaParser.ReadElement(source, ref position),
                    context.Formula.TextStyle,
                    context.Environment);
                var start      = context.CommandNameStartPosition;
                var atomSource = source.Segment(start, position - start);
                var atom       = new UnderlinedAtom(atomSource, underlineFormula.RootAtom);

                return(new CommandProcessingResult(atom, position));
            }
Beispiel #12
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="Project" /> class.
 /// </summary>
 public Project()
 {
     TexFormulaParser.Initialize();
     this.filterData = new Dictionary <ChartType, FilterData> {
         { ChartType.YoverX, new FilterData() }
     };
     this.CalibrationData = new CalibrationData();
     this.CalibrationData.PropertyChanged += this.CalibrationDataPropertyChanged;
     this.ProcessingData = new ProcessingData();
     this.VideoData      = new VideoData {
         LastPoint = new Point[this.ProcessingData.NumberOfTrackedObjects]
     };
     this.CurrentFilterData = new FilterData();
     this.currentChartType  = ChartType.YoverX;
 }
Beispiel #13
0
 public CommandContext(
     TexFormulaParser parser,
     TexFormula formula,
     ICommandEnvironment environment,
     SourceSpan commandSource,
     int commandNameStartPosition,
     int argumentsStartPosition)
 {
     Parser                   = parser;
     Formula                  = formula;
     Environment              = environment;
     CommandSource            = commandSource;
     CommandNameStartPosition = commandNameStartPosition;
     ArgumentsStartPosition   = argumentsStartPosition;
 }
 private Image GetImage()
 {
     try
     {
         _textLabel.Text = null;
         TexFormulaParser parser  = new TexFormulaParser();
         TexFormula       formula = parser.Parse(Template.FullTemplate);
         Byte[]           png     = formula.RenderToPng(15.0, 0.0, 0.0, "Times New Roman");
         return(ImageUtils.FromBytes(png));
     }
     catch (Exception)
     {
         _textLabel.Text = Globals.Localization.Error;
         return(null);
     }
 }
Beispiel #15
0
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            // Choose file
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                Filter = "SVG Files (*.svg)|*.svg|PNG Files (*.png)|*.png"
            };
            var result = saveFileDialog.ShowDialog();

            if (result == false)
            {
                return;
            }

            // Open stream
            var filename = saveFileDialog.FileName;

            switch (saveFileDialog.FilterIndex)
            {
            case 1:
                var svgConv = new SVGConverter(formula.Formula, formula.Scale)
                {
                    SystemTextFontName = formula.SystemTextFontName
                };
                svgConv.SaveGeometry(filename);
                break;

            case 2:
                using (var stream = new FileStream(filename, FileMode.Create))
                {
                    TexFormulaParser formulaParser = new TexFormulaParser();
                    var texFormula = formulaParser.Parse(formula.Formula);
                    var renderer   = texFormula.GetRenderer(TexStyle.Display, formula.Scale, formula.SystemTextFontName);

                    var bitmap  = renderer.RenderToBitmap(0, 0);
                    var encoder = new PngBitmapEncoder
                    {
                        Frames = { BitmapFrame.Create(bitmap) }
                    };
                    encoder.Save(stream);
                }
                break;

            default:
                return;
            }
        }
Beispiel #16
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.formulaParser = new TexFormulaParser();

            var testFormula1 = "\\int_0^{\\infty}{x^{2n} e^{-a x^2} dx} = \\frac{2n-1}{2a} \\int_0^{\\infty}{x^{2(n-1)} e^{-a x^2} dx} = \\frac{(2n-1)!!}{2^{n+1}} \\sqrt{\\frac{\\pi}{a^{2n+1}}}";
            var testFormula2 = "\\int_a^b{f(x) dx} = (b - a) \\sum_{n = 1}^{\\infty}  {\\sum_{m = 1}^{2^n  - 1} { ( { - 1} )^{m + 1} } } 2^{ - n} f(a + m ( {b - a}  )2^{-n} )";
            var testFormula3 = @"L = \int_a^b \sqrt[4]{ \left| \sum_{i,j=1}^ng_{ij}\left(\gamma(t)\right) \left[\frac{d}{dt}x^i\circ\gamma(t) \right] \left{\frac{d}{dt}x^j\circ\gamma(t) \right} \right|}dt";
            //matrix examples
            var testFormula4  = @"\matrix{4&78&3 \\ 5 & 9  & 82 }";
            var testFormula5  = @"\cases{x,&if x > 0;\cr -x,& otherwise.}";
            var testFormula6  = @"\matrix{4&78&3\\ 57 & {\matrix{78 \\ 12}}  & 20782 }";
            var testFormula7  = @"\cases{y>78 & if12<=x<125 \\ y=0 & otherwise; }";
            var testFormula8  = @"f(x) = \cases{1/3 & if \thinspace 0\le x\le 1;\cr 2/3 & if \thinspace 3\le x \le 4; \cr 0 & elsewhere.\cr}";
            var testFormula9  = @"v \times w = \left( \matrix{v_2 w_3 - v_3 w_2 \\ v_3 w_1 - v_1 w_3 \\ v_1 w_2 - v_2 w_1} \right) where v= \left(\matrix{ v_1 \\ v_2 \\ v_3 }\right), w= \left( \matrix{w_1 \\ w_2  \\ w_3} \right)";
            var testFormula10 = @"\Gamma_{\mu \rho} ^{\sigma}= \pmatrix{\pmatrix{0 & 0 & 0 \\ 0 & -r & 0 \\ 0 & 0 & -r sin^2(\theta)} \\ \pmatrix{0 & \frac{1}{r} & 0 \\ \frac{1}{r} & 0 & 0 \\ 0 & 0 & -\sin(\theta) \cos(\theta)} \\ \pmatrix{0 & 0 & \frac{1}{r} \\ 0 & 0 & \frac{1}{\tan(\theta)} \\ \frac{1}{r} & \frac{1}{\tan(\theta)} & 0 }}";

            this.inputTextBox.Text = testFormula10;
        }
Beispiel #17
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.formulaParser = new TexFormulaParser();

            var testFormula1 = "\\int_0^{\\infty}{x^{2n} e^{-a x^2} dx} = \\frac{2n-1}{2a} \\int_0^{\\infty}{x^{2(n-1)} e^{-a x^2} dx} = \\frac{(2n-1)!!}{2^{n+1}} \\sqrt{\\frac{\\pi}{a^{2n+1}}}";
            var testFormula2 = "\\int_a^b{f(x) dx} = (b - a) \\sum_{n = 1}^{\\infty}  {\\sum_{m = 1}^{2^n  - 1} { ( { - 1} )^{m + 1} } } 2^{ - n} f(a + m ( {b - a}  )2^{-n} )";
            var testFormula3 = @"L = \int_a^b \sqrt[4]{ \left| \sum_{i,j=1}^ng_{ij}\left(\gamma(t)\right) \left[\frac{d}{dt}x^i\circ\gamma(t) \right] \left{\frac{d}{dt}x^j\circ\gamma(t) \right} \right|}dt";

            //matrices
            var tf8  = @"\matrix{4&78&3 \\ 5 & 9  & 82 }";
            var tf9  = @"\bmatrix{4 & 78 & 3 \cr 5 & 9  & 22 }";
            var tf10 = @"\cases{x,&if x \ge 0;\cr -x,& otherwise.}";
            var tf11 = @"\matrix{4&78&3\\57 & {\bmatrix{78 \\ 12}}  & 20782 }";
            var tf15 = @"R_2 = \left[ \amatrix{2 & 1 & 6 \\ 4 & 3 &14 \\ 2 & -2 & \alpha - 2}{0 \\ 4 \\ -\beta + 12} \right]";
            var tf17 = @"v \times w = \left( \matrix{v_2 w_3 - v_3 w_2 \\ v_3 w_1 - v_1 w_3 \\ v_1 w_2 - v_2 w_1} \right) where \medspace v= \left(\matrix{ v_1 \\ v_2 \\ v_3 }\right), w= \left( \matrix{w_1 \\ w_2  \\ w_3} \right)";

            this.inputTextBox.Text = tf17;
        }
Beispiel #18
0
        private static (string, byte[]) renderLatex(string latex, bool onlyReturnDpath = true)
        {
            var parser      = new TexFormulaParser();
            var formula     = parser.Parse(latex);
            var renderer    = formula.GetRenderer(TexStyle.Display, 20, "Arial");
            var pngBytes    = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
            var geometry    = renderer.RenderToGeometry(0, 0);
            var converter   = new SVGConverter();
            var svgPathText = converter.ConvertGeometry(geometry);

            if (!onlyReturnDpath)
            {
                return(AddSVGHeader(svgPathText), pngBytes);
            }
            var tmp1 = svgPathText.Split(new string[] { "d=\"" }, StringSplitOptions.None)[1];
            var tmp2 = tmp1.Split(new string[] { "\"" }, StringSplitOptions.None)[0];

            return(tmp2, pngBytes);
        }
Beispiel #19
0
        private void LaTeX_to_File(string latex, string fileName)
        {
            var parser   = new TexFormulaParser();
            var formula  = parser.Parse(latex);
            var renderer = formula.GetRenderer(TexStyle.Display, 25.0, "Cambria Math"); // Math
            //var renderer = formula.GetRenderer(TexStyle.Display, 25.0, "Arial"); // Math
            var bitmapSource = renderer.RenderToBitmap(0.0, 0.0);
            //Console.WriteLine($"Image width: {bitmapSource.Width}");
            //Console.WriteLine($"Image height: {bitmapSource.Height}");

            var encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            using (var target = new FileStream(fileName, FileMode.Create))
            {
                encoder.Save(target);
                //Console.WriteLine($"File saved to {fileName}");
            }
        }
Beispiel #20
0
            internal static Bitmap TexPrinter(string latex, double scale)
            {
                try
                {
                    if (latex == "")
                    {
                        return(null);
                    }
                    while (latex.EndsWith(" ") || latex.EndsWith(" "))
                    {
                        latex = latex.Remove(latex.Length - 1, 1);
                    }
                    Bitmap bitmap = null;

                    var parser  = new TexFormulaParser();
                    var formula = parser.Parse(latex);
                    formula.TextStyle = "{StaticResource ClearTypeFormula}";
                    var renderer = formula.GetRenderer(TexStyle.Display, scale, "Arial");
                    if (renderer.RenderSize.Width == 0 || renderer.RenderSize.Height == 0)
                    {
                        return(bitmap);
                    }
                    var bitmapsourse = renderer.RenderToBitmap(0, 0);
                    var encoder      = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmapsourse));
                    using (var ms = new MemoryStream())
                    {
                        encoder.Save(ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        using (var temp = new Bitmap(ms))
                        {
                            bitmap = new Bitmap(temp);
                        }
                    }
                    return(bitmap);
                }
                catch (Exception e) when(e is TexParseException || e is TexCharacterMappingNotFoundException)
                {
                    return(Graphicer("!!TexError!!"));
                }
            }
Beispiel #21
0
        public void SaveGeometry(string filename)
        {
            TexFormulaParser formulaParser = new TexFormulaParser();

            if (filename == null)
            {
                return;
            }

            // Create formula object from input text.
            TexFormula formula = null;

            try
            {
                formula = formulaParser.Parse(Formula);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while parsing the given input:" + Environment.NewLine +
                                Environment.NewLine + ex.Message, "WPF-Math Example", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            // Create formula object from input text.

            if (formula == null)
            {
                return;
            }
            var renderer = formula.GetRenderer(TexStyle.Display, Scale, SystemTextFontName);

            using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                var geometry = renderer.RenderToGeometry(0, 0);

                var svgPathText = ConvertGeometry(geometry);
                var svgText     = AddSVGHeader(svgPathText);
                using (var writer = new StreamWriter(fs))
                    writer.WriteLine(svgText);
            }
        }
Beispiel #22
0
            public override void Parse(SourceSpan source, XElement element)
            {
                var name = element.AttributeValue("name");
                var args = element.Elements("Argument");

                var argTypes  = GetArgumentTypes(args);
                var argValues = GetArgumentValues(this.TempFormulas, args);

                Debug.Assert(argValues.Length == 1 || argValues.Length == 0);
                TexFormula formula = null;

                if (argValues.Length == 1)
                {
                    var parser = new TexFormulaParser();
                    formula = parser.Parse((string)argValues[0]);
                }
                else
                {
                    formula = new TexFormula();
                }

                this.TempFormulas.Add(name, formula);
            }
Beispiel #23
0
        public MainWindow()
        {
            InitializeComponent();
            var a = Expr.Variable("a");
            var b = Expr.Variable("b");

            var diff = a.Differentiate(a);

            // string latex = Expr.Parse("a_1_2_3^a^3^b/b_1^3").ToLaTeX();
            var latex = Diff(a, a) + " = " + diff.ToLaTeX();


            string fileName = @"formula.png";


            var parser  = new TexFormulaParser();
            var formula = parser.Parse(latex);
            //var renderer = formula.GetRenderer(TexStyle.Display, 20.0, "Arial");
            //var bitmapSource = renderer.RenderToGeometry(0.0, 0.0);
            var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");

            File.WriteAllBytes(fileName, pngBytes);
        }
Beispiel #24
0
        public CommandProcessingResult ProcessCommand(CommandContext context)
        {
            var position = context.ArgumentsStartPosition;
            var source   = context.CommandSource;

            if (position == source.Length)
            {
                throw new TexParseException("illegal end!");
            }

            var cellsSource  = TexFormulaParser.ReadElement(source, ref position);
            var matrixSource = context.CommandSource.Segment(
                context.CommandNameStartPosition,
                position - context.CommandNameStartPosition);

            var cells  = ReadMatrixCells(context.Parser, context.Formula, cellsSource, context.Environment);
            var matrix = new MatrixAtom(matrixSource, cells, _cellAlignment);

            SymbolAtom GetDelimiter(string name) =>
            name == null
                    ? null
                    : TexFormulaParser.GetDelimiterSymbol(name, null) ??
            throw new TexParseException($"The delimiter {name} could not be found");

            var leftDelimiter  = GetDelimiter(_leftDelimiterSymbolName);
            var rightDelimiter = GetDelimiter(_rightDelimiterSymbolName);

            var atom = leftDelimiter == null && rightDelimiter == null
                ? (Atom)matrix
                : new FencedAtom(
                matrixSource,
                matrix,
                leftDelimiter,
                rightDelimiter);

            return(new CommandProcessingResult(atom, position));
        }
Beispiel #25
0
        protected void DoWriteLatex(string text, LatexOptions options)
        {
            options ??= new LatexOptions();

            var book = options.Book?.Document ?? Document;

            using (new UsingProcessor(() => book.BeginUpdate(), () => book.EndUpdate()))
            {
                DocumentPosition rangeStart = null, rangeEnd = null;

                var parser     = new TexFormulaParser();
                var formula    = parser.Parse(text);

                var renderer   = formula.GetRenderer(TexStyle.Text, options.FontSize, "Tahoma");

                var geometry   = renderer.RenderToGeometry(0, 0);
                var converter  = new SVGConverter();
                var svgPathText = converter.ConvertGeometry(geometry);
                var svgText    = AddSVGHeader(svgPathText);

                var imageLatex = PaintSVG(svgText, options.DPI);
                AddUserCommentsToImage(imageLatex, text);
                var image = book.Images.Append(imageLatex);

                image.ScaleX = options.Scale;
                image.ScaleY = options.Scale;

                var rangeImage = image.Range;
                if (rangeStart == null)
                {
                    rangeStart = rangeImage.Start;
                }

                if (!options.NoLineBreaks)
                {
                    rangeImage = book.AppendText(Environment.NewLine);
                }

                rangeEnd = rangeImage.End;

                if (rangeStart != null && rangeEnd != null)
                {
                    var range = book.CreateRange(rangeStart, rangeEnd.ToInt() - rangeStart.ToInt());

                    if (!string.IsNullOrWhiteSpace(options.ParagraphStyle))
                    {
                        var style = book.ParagraphStyles[options.ParagraphStyle] ?? throw new Exception($"Paragraph style '{options.ParagraphStyle}' does not exist.");
                        var pp    = book.BeginUpdateParagraphs(range);
                        try
                        {
                            pp.Style = style;
                        }
                        finally
                        {
                            book.EndUpdateParagraphs(pp);
                        }
                    }

                    Script.Book.SCBook.AddComments(book, range, options);

                    WriteRangeToConsole(book, range);
                }

                if (rangeEnd != null)
                {
                    book.CaretPosition = rangeEnd;
                    Script.Book.SCBook.ResetBookFormatting(book, rangeEnd);
                    ScrollToCaret();
                }
            }
Beispiel #26
0
 public FormulaControl()
 {
     _formulaParser = new TexFormulaParser();
 }
Beispiel #27
0
 public static string Escape(char s)
 {
     return(TexFormulaParser.IsParserReserved(s) ? "\\" + s : new string(s, 1));
 }
Beispiel #28
0
 public FormulaControl()
 {
     TexFormulaParser.Initialize();
     _formulaParser = new TexFormulaParser();
 }
Beispiel #29
0
        protected IRichEditDocumentServer AddLatex(ArgumentCollection arguments)
        {
            if (arguments.Count <= 0)
            {
                throw new Exception("'DOCVARIABLE LATEX' requires LaTeX as first argument.");
            }

            var latex = arguments[0].Value;

            float?scale = null, scaleX = null, scaleY = null;
            float dpi = 300, fontSize = 20;

            if (arguments.Count > 1)
            {
                var properties = Utils.SplitNameValueString(arguments[1].Value, ';');

                foreach (var prop in properties)
                {
                    if (string.IsNullOrWhiteSpace(prop.Key))
                    {
                        continue;
                    }

                    switch (prop.Key.ToLower())
                    {
                    case "dpi":
                        dpi = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "scale":
                        scale = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "scalex":
                        scaleX = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "scaley":
                        scaleY = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;

                    case "fontsize":
                        fontSize = float.Parse(prop.Value, CultureInfo.InvariantCulture);
                        break;
                    }
                }
            }

            var parser  = new TexFormulaParser();
            var formula = parser.Parse(latex);

            var renderer = formula.GetRenderer(TexStyle.Text, fontSize, "Tahoma");

            var geometry    = renderer.RenderToGeometry(0, 0);
            var converter   = new SVGConverter();
            var svgPathText = converter.ConvertGeometry(geometry);
            var svgText     = AddSVGHeader(svgPathText);

            var docSVG = new XmlDocument();

            docSVG.LoadXml(svgText);

            var image = PaintSVG(docSVG, Size.Empty, dpi);

            var server   = new RichEditDocumentServer();
            var document = server.Document;
            var docImage = document.Images.Append(image);

            if (scale.HasValue)
            {
                docImage.ScaleX = docImage.ScaleY = scale.Value;
            }
            else
            {
                if (scaleX.HasValue)
                {
                    docImage.ScaleX = scaleX.Value;
                }
                if (scaleY.HasValue)
                {
                    docImage.ScaleY = scaleY.Value;
                }
            }

            return(server);
    ///Returning: 0-Not found, 1-Symbol, 2-Command, 3-Font, 4-Misc
    static int FindPossibleEscape(string text, int pos, out int start, out int end)
    {
        start = 0;
        end   = 0;
        pos--;
        if (text.Length <= 0 || pos < 0 || pos >= text.Length)
        {
            return(0);
        }
        if (TexFormulaParser.IsParserReserved(text[pos]))
        {
            if (pos == 0 || text[pos - 1] != '\\')
            {
                if (pos == 0 || text[pos] != '\\')
                {
                    return(0);
                }
                else if (pos < text.Length - 1)
                {
                    pos++;
                }
                else
                {
                    start = pos - 1;
                    end   = pos;
                    return(4);
                }
            }
            else
            {
                start = pos - 1;
                end   = pos;
                return(4);
            }
        }
        end = pos;
        while (true)
        {
            if (char.IsLetter(text[pos]))
            {
                pos--;
                if (pos >= 0)
                {
                    continue;
                }
                else
                {
                    return(0);
                }
            }
            if (text[pos] == '\\')
            {
                if (pos == 0 || text[pos - 1] != '\\')
                {
                    start = pos;
                    break;
                }
            }
            return(0);
        }
        while (end < text.Length && char.IsLetter(text[end]))
        {
            end++;
        }
        end--;
        var s = text.Substring(start + 1, end - start);

        if (TEXPreference.main.GetFontIndexByID(s) >= 0)
        {
            return(3);
        }
        if (TexFormulaParser.isCommandRegistered(s))
        {
            return(2);
        }
        if (TEXPreference.main.GetChar(s) != null)
        {
            return(1);
        }
        return(4);
    }
Beispiel #31
0
    public override string ReplaceString(string original)
    {
        blocks.Clear();

        int line = 0;

        original = m_pattern.Replace(original, (match) =>
        {
            if (!match.Groups[5].Success && match.Length > 2)
            {
                // skip commands, fonts, big operators, delimiter
                var g = match.Groups[1];
                int s;
                var m = TEXPreference.main;
                if (!g.Success || TexFormulaParser.isCommandRegistered(g.Value) ||
                    m.GetFontIndexByID(g.Value) >= 0)
                {
                    return(match.Value);
                }
                else if ((s = m.symbols.GetValue(g.Value)) > 0 &&
                         (m.GetChar(s).nextLargerExist || m.GetChar(s).extensionExist))
                {
                    return(match.Value);
                }
                else if (match.Length > g.Length + 1)
                {
                    // extra spaces can't be tolerated
                    // alternate to custom logic
                    return(Group2WithSpaceElimination(match, g));
                }
            }

            var cmd   = "\\vlink[" + blocks.Count + "]";
            Block dyn = new Block()
            {
                index  = blocks.Count,
                start  = match.Index,
                length = match.Length,
                // see text input cursor
                lineSeparator = -1,
            };

            if (match.Value == "\n")
            {
                dyn.lineSeparator = line++;
                blocks.Add(dyn);
                return("\n" + cmd + "{}");
            }
            else if (match.Value == "\\")
            {
                blocks.Add(dyn);
                return(cmd + "{\\\\}");
            }
            else if (match.Groups[4].Success)
            {
                dyn.start++;
                dyn.length = 0;
                blocks.Add(dyn);
                return("{" + cmd + "{" + emptyPlaceholder + "}}");
            }
            else
            {
                blocks.Add(dyn);
                return(cmd + "{" + match.Value + "}");
            }
        });

        {
            // keep things stable by capturing words
            original = m_wrapholder.Replace(original, @"{$1}");
            // sanitize invalid scripts
            original = m_scriptEscape.Replace(original, @"{$1}$2");
        }
        return(original);
    }