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