]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
fonts as insets
[lyx.git] / src / mathed / formula.C
1 /*
2 *  File:        formula.C
3 *  Purpose:     Implementation of formula inset
4 *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 *  Created:     January 1996
6 *  Description: Allows the edition of math paragraphs inside Lyx.
7 *
8 *  Copyright: 1996-1998 Alejandro Aguilar Sierra
9 *
10 *  Version: 0.4, Lyx project.
11 *
12 *   You are free to use and modify this code under the terms of
13 *   the GNU General Public Licence version 2 or later.
14 */
15
16 #ifdef __GNUG__
17 #pragma implementation
18 #endif
19
20 #include <config.h>
21
22 #include "formula.h"
23 #include "commandtags.h"
24 #include "math_cursor.h"
25 #include "math_parser.h"
26 #include "math_charinset.h"
27 #include "math_arrayinset.h"
28 #include "math_deliminset.h"
29 #include "lyx_main.h"
30 #include "BufferView.h"
31 #include "gettext.h"
32 #include "debug.h"
33 #include "frontends/Alert.h"
34 #include "support/LOstream.h"
35 #include "support/LAssert.h"
36 #include "support/systemcall.h"
37 #include "support/filetools.h" // LibFileSearch
38 #include "frontends/LyXView.h"
39 #include "frontends/Painter.h"
40 #include "lyxrc.h"
41 #include "math_hullinset.h"
42 #include "math_support.h"
43 #include "math_mathmlstream.h"
44 #include "textpainter.h"
45 #include "preview.h"
46
47 using std::ostream;
48 using std::ifstream;
49 using std::istream;
50 using std::pair;
51 using std::endl;
52 using std::vector;
53 using std::getline;
54
55
56 namespace {
57
58         string captureOutput(string const & cmd, string const & data)
59         {
60                 string outfile = lyx::tempName(string(), "mathextern");
61                 string full =  "echo '" + data + "' | (" + cmd + ") > " + outfile;
62                 lyxerr << "calling: " << full << "\n";
63                 Systemcall dummy;
64                 dummy.startscript(Systemcall::Wait, full);
65                 string out = GetFileContents(outfile);
66                 lyx::unlink(outfile);
67                 lyxerr << "result: '" << out << "'\n";
68                 return out;
69         }
70
71
72         MathArray pipeThroughMaple(string const & extra, MathArray const & ar)
73         {
74                 string header = "readlib(latex):\n";
75
76                 // remove the \\it for variable names
77                 //"#`latex/csname_font` := `\\it `:"
78                 header +=
79                         "`latex/csname_font` := ``:\n";
80
81                 // export matrices in (...) instead of [...]
82                 header +=
83                         "`latex/latex/matrix` := "
84                                 "subs(`[`=`(`, `]`=`)`,"
85                                         "eval(`latex/latex/matrix`)):\n";
86
87                 // replace \\cdots with proper '*'
88                 header +=
89                         "`latex/latex/*` := "
90                                 "subs(`\\,`=`\\cdot `,"
91                                         "eval(`latex/latex/*`)):\n";
92
93                 // remove spurious \\noalign{\\medskip} in matrix output
94                 header +=
95                         "`latex/latex/matrix`:= "
96                                 "subs(`\\\\\\\\\\\\noalign{\\\\medskip}` = `\\\\\\\\`,"
97                                         "eval(`latex/latex/matrix`)):\n";
98
99                 //"#`latex/latex/symbol` "
100                 //      " := subs((\\'_\\' = \\'`\\_`\\',eval(`latex/latex/symbol`)): ";
101
102                 string trailer = "quit;";
103                 ostringstream os;
104                 MapleStream ms(os);
105                 ms << ar;
106                 string expr = os.str().c_str();
107
108                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
109                         // try to fix missing '*' the hard way by using mint
110                         //
111                         // ... > echo "1A;" | mint -i 1 -S -s -q
112                         // on line     1: 1A;
113                         //                 ^ syntax error -
114                         //                   Probably missing an operator such as * p
115                         //
116                         lyxerr << "checking expr: '" << expr << "'\n";
117                         string out = captureOutput("mint -i 1 -S -s -q -q", expr + ";");
118                         if (out.empty())
119                                 break; // expression syntax is ok
120                         istringstream is(out.c_str());
121                         string line;
122                         getline(is, line);
123                         if (line.find("on line") != 0)
124                                 break; // error message not identified
125                         getline(is, line);
126                         string::size_type pos = line.find('^');
127                         if (pos == string::npos || pos < 15)
128                                 break; // caret position not found
129                         pos -= 15; // skip the "on line ..." part
130                         if (expr[pos] == '*' || (pos > 0 && expr[pos - 1] == '*'))
131                                 break; // two '*' in a row are definitely bad
132                         expr.insert(pos,  "*");
133                 }
134
135                 string full = "latex(" +  extra + '(' + expr + "));";
136                 string out = captureOutput("maple -q", header + full + trailer);
137
138                 // change \_ into _
139
140                 //
141                 MathArray res;
142                 mathed_parse_cell(res, out);
143                 return res;
144         }
145
146
147         MathArray pipeThroughOctave(string const &, MathArray const & ar)
148         {
149                 ostringstream os;
150                 OctaveStream vs(os);
151                 vs << ar;
152                 string expr = os.str().c_str();
153                 string out;
154
155                 for (int i = 0; i < 100; ++i) { // at most 100 attempts
156                         //
157                         // try to fix missing '*' the hard way
158                         // parse error:
159                         // >>> ([[1 2 3 ];[2 3 1 ];[3 1 2 ]])([[1 2 3 ];[2 3 1 ];[3 1 2 ]])
160                         //                                   ^
161                         //
162                         lyxerr << "checking expr: '" << expr << "'\n";
163                         out = captureOutput("octave -q 2>&1", expr);
164                         lyxerr << "checking out: '" << out << "'\n";
165
166                         // leave loop if expression syntax is probably ok
167                         if (out.find("parse error:") == string::npos)
168                                 break;
169
170                         // search line with single caret
171                         istringstream is(out.c_str());
172                         string line;
173                         while (is) {
174                                 getline(is, line);
175                                 lyxerr << "skipping line: '" << line << "'\n";
176                                 if (line.find(">>> ") != string::npos)
177                                         break;
178                         }
179
180                         // found line with error, next line is the one with caret
181                         getline(is, line);
182                         string::size_type pos = line.find('^');
183                         lyxerr << "caret line: '" << line << "'\n";
184                         lyxerr << "found caret at pos: '" << pos << "'\n";
185                         if (pos == string::npos || pos < 4)
186                                 break; // caret position not found
187                         pos -= 4; // skip the ">>> " part
188                         if (expr[pos] == '*')
189                                 break; // two '*' in a row are definitely bad
190                         expr.insert(pos,  "*");
191                 }
192
193                 if (out.size() < 6)
194                         return MathArray();
195
196                 // remove 'ans = '
197                 out = out.substr(6);
198
199                 // parse output as matrix or single number
200                 MathAtom at(new MathArrayInset("array", out));
201                 MathArrayInset const * mat = at.nucleus()->asArrayInset();
202                 MathArray res;
203                 if (mat->ncols() == 1 && mat->nrows() == 1)
204                         res.push_back(mat->cell(0));
205                 else {
206                         res.push_back(MathAtom(new MathDelimInset("(", ")")));
207                         res.back()->cell(0).push_back(at);
208                 }
209                 return res;
210         }
211
212
213         MathArray pipeThroughExtern(string const & lang, string const & extra,
214                 MathArray const & ar)
215         {
216                 if (lang == "octave")
217                         return pipeThroughOctave(extra, ar);
218
219                 if (lang == "maple")
220                         return pipeThroughMaple(extra, ar);
221
222                 // create normalized expression
223                 ostringstream os;
224                 NormalStream ns(os);
225                 os << "[" << extra << ' ';
226                 ns << ar;
227                 os << "]";
228                 string data = os.str().c_str();
229
230                 // search external script
231                 string file = LibFileSearch("mathed", "extern_" + lang);
232                 if (file.empty()) {
233                         lyxerr << "converter to '" << lang << "' not found\n";
234                         return MathArray();
235                 }
236
237                 // run external sript
238                 string out = captureOutput(file, data);
239                 MathArray res;
240                 mathed_parse_cell(res, out);
241                 return res;
242         }
243
244 }
245
246
247 InsetFormula::InsetFormula()
248         : par_(MathAtom(new MathHullInset))
249 {}
250
251
252 InsetFormula::InsetFormula(MathInsetTypes t)
253         : par_(MathAtom(new MathHullInset(t)))
254 {}
255
256
257 InsetFormula::InsetFormula(string const & s)
258 {
259         if (s.size()) {
260                 bool res = mathed_parse_normal(par_, s);
261
262                 if (!res)
263                         res = mathed_parse_normal(par_, "$" + s + "$");
264
265                 if (!res) {
266                         lyxerr << "cannot interpret '" << s << "' as math\n";
267                         par_ = MathAtom(new MathHullInset(LM_OT_SIMPLE));
268                 }
269         }
270         metrics();
271 }
272
273
274 Inset * InsetFormula::clone(Buffer const &, bool) const
275 {
276         return new InsetFormula(*this);
277 }
278
279
280 void InsetFormula::write(Buffer const *, ostream & os) const
281 {
282         os << "Formula ";
283         WriteStream wi(os, false, false);
284         par_->write(wi);
285 }
286
287
288 int InsetFormula::latex(Buffer const *, ostream & os, bool fragile, bool) const
289 {
290         WriteStream wi(os, fragile, true);
291         par_->write(wi);
292         return wi.line();
293 }
294
295
296 int InsetFormula::ascii(Buffer const *, ostream & os, int) const
297 {
298 #if 0
299         TextMetricsInfo mi;
300         par()->metricsT(mi);
301         TextPainter tpain(par()->width(), par()->height());
302         par()->drawT(tpain, 0, par()->ascent());
303         tpain.show(os);
304         // reset metrics cache to "real" values
305         metrics();
306         return tpain.textheight();
307 #else
308         WriteStream wi(os, false, true);
309         par_->write(wi);
310         return wi.line();
311 #endif
312 }
313
314
315 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
316 {
317         return docbook(buf, os);
318 }
319
320
321 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
322 {
323         MathMLStream ms(os);
324         ms << MTag("equation") << MTag("alt");
325         int res = ascii(buf, ms.os(), 0);
326         ms << ETag("alt") << MTag("math");
327         ms << par_.nucleus();
328         ms << ETag("math") << ETag("equation");
329         return ms.line() + res;
330 }
331
332
333 void InsetFormula::read(Buffer const *, LyXLex & lex)
334 {
335         mathed_parse_normal(par_, lex);
336         metrics();
337 }
338
339
340 //ostream & operator<<(ostream & os, LyXCursor const & c)
341 //{
342 //      os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
343 //      return os;
344 //}
345
346
347 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
348                         int y, float & xx, bool) const
349 {
350         metrics(bv, font);
351
352         int x = int(xx);
353         int w = par_->width();
354         int h = par_->height();
355         int a = par_->ascent();
356
357         MathPainterInfo pi(bv->painter());
358         pi.base.font  = font;
359         pi.base.font.setColor(LColor::math);
360         pi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
361
362         if (lcolor.getX11Name(LColor::mathbg)!=lcolor.getX11Name(LColor::background))
363                 pi.pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
364
365         if (mathcursor &&
366                         const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
367         {
368                 mathcursor->drawSelection(pi);
369                 pi.pain.rectangle(x, y - a, w, h, LColor::mathframe);
370         }
371
372         par_->draw(pi, x, y);
373
374         // preview stuff
375 #if 0
376         ostringstream os;
377         WriteStream wi(os, false, false);
378         par_->write(wi);
379         if (grfx::ImagePtr image = preview(os.str()))
380                 pain.image(x, y, w, h, *image);
381 #endif
382         
383         xx += par_->width();
384         xo_ = x;
385         yo_ = y;
386
387         setCursorVisible(false);
388 }
389
390
391 vector<string> const InsetFormula::getLabelList() const
392 {
393         return hull()->getLabelList();
394 }
395
396
397 UpdatableInset::RESULT
398 InsetFormula::localDispatch(BufferView * bv, kb_action action,
399          string const & arg)
400 {
401         RESULT result = DISPATCHED;
402
403         switch (action) {
404
405                 case LFUN_BREAKLINE:
406                         bv->lockedInsetStoreUndo(Undo::INSERT);
407                         mathcursor->breakLine();
408                         mathcursor->normalize();
409                         updateLocal(bv, true);
410                         break;
411
412                 case LFUN_MATH_NUMBER:
413                 {
414                         //lyxerr << "toggling all numbers\n";
415                         if (display()) {
416                                 bv->lockedInsetStoreUndo(Undo::INSERT);
417                                 bool old = hull()->numberedType();
418                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
419                                         hull()->numbered(row, !old);
420                                 bv->owner()->message(old ? _("No number") : _("Number"));
421                                 updateLocal(bv, true);
422                         }
423                         break;
424                 }
425
426                 case LFUN_MATH_NONUMBER:
427                 {
428                         //lyxerr << "toggling line number\n";
429                         if (display()) {
430                                 bv->lockedInsetStoreUndo(Undo::INSERT);
431                                 MathCursor::row_type row = mathcursor->hullRow();
432                                 bool old = hull()->numbered(row);
433                                 bv->owner()->message(old ? _("No number") : _("Number"));
434                                 hull()->numbered(row, !old);
435                                 updateLocal(bv, true);
436                         }
437                         break;
438                 }
439
440                 case LFUN_INSERT_LABEL:
441                 {
442                         bv->lockedInsetStoreUndo(Undo::INSERT);
443
444                         MathCursor::row_type row = mathcursor->hullRow();
445                         string old_label = hull()->label(row);
446                         string new_label = arg;
447
448                         if (new_label.empty()) {
449                                 string const default_label =
450                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
451                                 pair<bool, string> const res = old_label.empty()
452                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
453                                         : Alert::askForText(_("Enter label:"), old_label);
454                                 if (!res.first)
455                                         break;
456                                 new_label = frontStrip(strip(res.second));
457                         }
458
459                         //if (new_label == old_label)
460                         //      break;  // Nothing to do
461
462                         if (!new_label.empty()) {
463                                 lyxerr << "setting label to '" << new_label << "'\n";
464                                 hull()->numbered(row, true);
465                         }
466
467                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
468                                 bv->redraw();
469
470                         hull()->label(row, new_label);
471
472                         updateLocal(bv, true);
473                         break;
474                 }
475
476                 case LFUN_MATH_MUTATE:
477                 {
478                         bv->lockedInsetStoreUndo(Undo::EDIT);
479                         int x;
480                         int y;
481                         mathcursor->getPos(x, y);
482                         hull()->mutate(arg);
483                         mathcursor->setPos(x, y);
484                         mathcursor->normalize();
485                         updateLocal(bv, true);
486                         break;
487                 }
488
489                 case LFUN_MATH_EXTERN:
490                 {
491                         bv->lockedInsetStoreUndo(Undo::EDIT);
492                         handleExtern(arg);
493                         // re-compute inset dimension
494                         metrics(bv);
495                         updateLocal(bv, true);
496                         break;
497                 }
498
499                 case LFUN_MATH_DISPLAY:
500                 {
501                         int x = 0;
502                         int y = 0;
503                         mathcursor->getPos(x, y);
504                         if (hull()->getType() == LM_OT_SIMPLE)
505                                 hull()->mutate(LM_OT_EQUATION);
506                         else
507                                 hull()->mutate(LM_OT_SIMPLE);
508                         mathcursor->setPos(x, y);
509                         mathcursor->normalize();
510                         updateLocal(bv, true);
511                         break;
512                 }
513
514                 case LFUN_PASTESELECTION:
515                 {
516                         string const clip = bv->getClipboard();
517                 if (!clip.empty())
518                                 mathed_parse_normal(par_, clip);
519                         break;
520                 }
521
522                 default:
523                         result = InsetFormulaBase::localDispatch(bv, action, arg);
524         }
525
526         return result;
527 }
528
529
530 bool needEqnArray(string const & extra)
531 {
532         return extra == "dsolve";
533 }
534
535
536 void InsetFormula::handleExtern(const string & arg)
537 {
538         // where are we?
539         if (!mathcursor)
540                 return;
541
542         string lang;
543         string extra;
544         istringstream iss(arg.c_str());
545         iss >> lang >> extra;
546         if (extra.empty())
547                 extra = "noextra";
548
549         bool selected = mathcursor->selection();
550
551         MathArray ar;
552         if (needEqnArray(extra)) {
553                 mathcursor->last();
554                 //mathcursor->readLine(ar);
555                 mathcursor->breakLine();
556         } else if (selected) {
557                 mathcursor->selGet(ar);
558                 //lyxerr << "use selection: " << ar << "\n";
559         } else {
560                 mathcursor->last();
561                 mathcursor->stripFromLastEqualSign();
562                 ar = mathcursor->cursor().cell();
563                 mathcursor->insert('=');
564                 //lyxerr << "use whole cell: " << ar << "\n";
565         }
566
567         mathcursor->insert(pipeThroughExtern(lang, extra, ar));
568 }
569
570
571 bool InsetFormula::display() const
572 {
573         return hull()->getType() != LM_OT_SIMPLE;
574 }
575
576
577 MathHullInset const * InsetFormula::hull() const
578 {
579         lyx::Assert(par_->asHullInset());
580         return par_->asHullInset();
581 }
582
583
584 MathHullInset * InsetFormula::hull()
585 {
586         lyx::Assert(par_->asHullInset());
587         return par_->asHullInset();
588 }
589
590
591 Inset::Code InsetFormula::lyxCode() const
592 {
593         return Inset::MATH_CODE;
594 }
595
596
597 void InsetFormula::validate(LaTeXFeatures & features) const
598 {
599         par_->validate(features);
600 }
601
602
603 bool InsetFormula::insetAllowed(Inset::Code code) const
604 {
605         return
606                 (code == Inset::LABEL_CODE && display())
607                 || code == Inset::ERT_CODE;
608 }
609
610
611 int InsetFormula::ascent(BufferView *, LyXFont const &) const
612 {
613         return par_->ascent() + 1;
614 }
615
616
617 int InsetFormula::descent(BufferView *, LyXFont const &) const
618 {
619         return par_->descent() + 1;
620 }
621
622
623 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
624 {
625         metrics(bv, font);
626         return par_->width();
627 }
628
629
630 MathInsetTypes InsetFormula::getType() const
631 {
632         return hull()->getType();
633 }