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