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