]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
cosmetics: rename support.[Ch] into math_support.[Ch]
[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_matrixinset.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                 // replace spurious \\noalign{\\medskip} in table 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();
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);
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] == '*')
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();
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);
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 & arg, MathArray const & ar)
211         {
212                 string lang;
213                 string extra;
214                 istringstream iss(arg.c_str());
215                 iss >> lang >> extra;
216                 if (extra.empty())
217                         extra = "noextra";      
218
219                 if (lang == "octave")
220                         return pipeThroughOctave(extra, ar);
221
222                 if (lang == "maple")
223                         return pipeThroughMaple(extra, ar);
224
225                 // create normalized expression
226                 ostringstream os;
227                 NormalStream ns(os);
228                 os << "[" << extra << ' ';
229                 ar.writeNormal(ns); 
230                 os << "]";
231                 string data = os.str().c_str();
232
233                 // search external script
234                 string file = LibFileSearch("mathed", "extern_" + lang);
235                 if (file.empty()) {
236                         lyxerr << "converter to '" << lang << "' not found\n";
237                         return MathArray();
238                 }
239                 
240                 // run external sript
241                 string out = captureOutput(file, data);
242                 MathArray res;
243                 mathed_parse_cell(res, out);
244                 return res;
245         }
246
247 }
248
249
250 InsetFormula::InsetFormula()
251         : par_(MathAtom(new MathMatrixInset))
252 {}
253
254
255 InsetFormula::InsetFormula(MathInsetTypes t)
256         : par_(MathAtom(new MathMatrixInset(t)))
257 {}
258
259
260 InsetFormula::InsetFormula(string const & s) 
261 {
262         if (s.size()) {
263                 bool res = mathed_parse_normal(par_, s);
264
265                 if (!res)
266                         res = mathed_parse_normal(par_, "$" + s + "$");
267
268                 if (!res) {
269                         lyxerr << "cannot interpret '" << s << "' as math\n";
270                         par_ = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
271                 }
272         }
273         metrics();
274 }
275
276
277 Inset * InsetFormula::clone(Buffer const &, bool) const
278 {
279         return new InsetFormula(*this);
280 }
281
282
283 void InsetFormula::write(Buffer const * buf, ostream & os) const
284 {
285         os << "Formula ";
286         latex(buf, os, false, false);
287 }
288
289
290 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
291         const
292 {
293         MathWriteInfo wi(buf, os, fragil);
294         par_->write(wi);
295         return 1;
296 }
297
298
299 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
300 {
301         MathWriteInfo wi(buf, os, false);
302         par_->write(wi);
303         return 1;
304 }
305
306
307 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
308 {
309         return docbook(buf, os);
310 }
311
312
313 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
314 {
315         MathMLStream ms(os);
316         ms << MTag("equation") << MTag("alt");
317         int res = ascii(buf, ms.os_, 0);
318         ms << ETag("alt") << MTag("math");
319         ms << par_.nucleus();
320         ms << ETag("math") << ETag("equation");
321         return ms.line_ + res;
322 }
323
324
325 void InsetFormula::read(Buffer const *, LyXLex & lex)
326 {
327         mathed_parse_normal(par_, lex);
328         metrics();
329 }
330
331
332 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
333                         int y, float & xx, bool) const
334 {
335         int x = int(xx) - 1;
336         y -= 2;
337
338         Painter & pain = bv->painter();
339
340         metrics(bv, font);
341         int w = par_->width();
342         int h = par_->height();
343         int a = par_->ascent();
344         pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
345
346         if (mathcursor && mathcursor->formula() == this) {
347                 mathcursor->drawSelection(pain);
348                 pain.rectangle(x, y - a, w, h, LColor::mathframe);
349         }
350
351         par_->draw(pain, x, y);
352         xx += par_->width();
353         xo_ = x;
354         yo_ = y;
355
356         setCursorVisible(false);
357 }
358
359
360 vector<string> const InsetFormula::getLabelList() const
361 {
362         return mat()->getLabelList();
363 }
364
365
366 UpdatableInset::RESULT
367 InsetFormula::localDispatch(BufferView * bv, kb_action action,
368          string const & arg)
369 {
370         RESULT result = DISPATCHED;
371
372         switch (action) {
373
374                 case LFUN_BREAKLINE: 
375                         bv->lockedInsetStoreUndo(Undo::INSERT);
376                         mathcursor->breakLine();
377                         mathcursor->normalize();
378                         updateLocal(bv, true);
379                         break;
380
381                 case LFUN_MATH_NUMBER:
382                 {
383                         //lyxerr << "toggling all numbers\n";
384                         if (display()) {
385                                 bv->lockedInsetStoreUndo(Undo::INSERT);
386                                 bool old = mat()->numberedType();
387                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
388                                         mat()->numbered(row, !old);
389                                 bv->owner()->message(old ? _("No number") : _("Number"));
390                                 updateLocal(bv, true);
391                         }
392                         break;
393                 }
394
395                 case LFUN_MATH_NONUMBER:
396                 {
397                         //lyxerr << "toggling line number\n";
398                         if (display()) {
399                                 bv->lockedInsetStoreUndo(Undo::INSERT);
400                                 MathCursor::row_type row = mathcursor->row();
401                                 bool old = mat()->numbered(row);
402                                 bv->owner()->message(old ? _("No number") : _("Number"));
403                                 mat()->numbered(row, !old);
404                                 updateLocal(bv, true);
405                         }
406                         break;
407                 }
408
409                 case LFUN_INSERT_LABEL:
410                 {
411                         bv->lockedInsetStoreUndo(Undo::INSERT);
412
413                         MathCursor::row_type row = mathcursor->row();
414                         string old_label = mat()->label(row);
415                         string new_label = arg;
416
417                         if (new_label.empty()) {
418                                 string const default_label =
419                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
420                                 pair<bool, string> const res = old_label.empty()
421                                         ? askForText(_("Enter new label to insert:"), default_label)
422                                         : askForText(_("Enter label:"), old_label);
423                                 
424                                 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
425                                 if (!res.first)
426                                         break;
427                                 new_label = frontStrip(strip(res.second));
428                         }
429
430                         //if (new_label == old_label)
431                         //      break;  // Nothing to do
432
433                         if (!new_label.empty()) {
434                                 lyxerr << "setting label to '" << new_label << "'\n";
435                                 mat()->numbered(row, true);
436                         }
437
438                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
439                                 bv->redraw();
440
441                         mat()->label(row, new_label);
442
443                         updateLocal(bv, true);
444                         break;
445                 }
446
447                 case LFUN_MATH_MUTATE:
448                 {
449                         bv->lockedInsetStoreUndo(Undo::EDIT);
450                         int x;
451                         int y;
452                         mathcursor->getPos(x, y);
453                         mat()->mutate(arg);
454                         mathcursor->setPos(x, y);
455                         mathcursor->normalize();
456                         updateLocal(bv, true);
457                         break;
458                 }
459
460                 case LFUN_MATH_EXTERN:
461                 {
462                         bv->lockedInsetStoreUndo(Undo::EDIT);
463                         handleExtern(arg);
464                         // re-compute inset dimension
465                         metrics(bv);
466                         updateLocal(bv, true);
467                         break;
468                 }
469
470                 case LFUN_MATH_DISPLAY:
471                 {
472                         int x;
473                         int y;
474                         mathcursor->getPos(x, y);
475                         if (mat()->getType() == LM_OT_SIMPLE)
476                                 mat()->mutate(LM_OT_EQUATION);
477                         else
478                                 mat()->mutate(LM_OT_SIMPLE);
479                         mathcursor->setPos(x, y);
480                         mathcursor->normalize();
481                         updateLocal(bv, true);
482                         break;
483                 }
484                 
485                 case LFUN_PASTESELECTION:
486                 {
487                         string const clip = bv->getClipboard();
488                 if (!clip.empty())
489                                 mathed_parse_normal(par_, clip);
490                         break;
491                 }
492
493                 case LFUN_MATH_COLUMN_INSERT:
494                 {
495                         if (mat()->getType() == LM_OT_ALIGN)
496                                 mat()->mutate(LM_OT_ALIGNAT);
497                         mat()->addCol(mat()->ncols());
498                         mathcursor->normalize();
499                         updateLocal(bv, true);
500                 }
501
502                 default:
503                         result = InsetFormulaBase::localDispatch(bv, action, arg);
504         }
505
506         return result;
507 }
508
509
510 void InsetFormula::handleExtern(const string & arg)
511 {
512         // where are we?
513         if (!mathcursor)
514                 return; 
515
516         bool selected = mathcursor->selection();
517
518         MathArray ar;
519         if (selected) {
520                 mathcursor->selGet(ar);
521                 //lyxerr << "use selection: " << ar << "\n";
522         } else {
523                 mathcursor->end();
524                 mathcursor->stripFromLastEqualSign();
525                 ar = mathcursor->cursor().cell();
526                 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
527                 //lyxerr << "use whole cell: " << ar << "\n";
528         }
529
530         mathcursor->insert(pipeThroughExtern(arg, ar));
531 }
532
533
534 bool InsetFormula::display() const
535 {
536         return mat()->getType() != LM_OT_SIMPLE;
537 }
538
539
540 MathMatrixInset const * InsetFormula::mat() const
541 {
542         lyx::Assert(par_->asMatrixInset());
543         return par_->asMatrixInset();
544 }
545
546
547 MathMatrixInset * InsetFormula::mat()
548 {
549         lyx::Assert(par_->asMatrixInset());
550         return par_->asMatrixInset();
551 }
552
553
554 Inset::Code InsetFormula::lyxCode() const
555 {
556         return Inset::MATH_CODE;
557 }
558
559
560 void InsetFormula::validate(LaTeXFeatures & features) const
561 {
562         par_->validate(features);
563 }
564
565
566 bool InsetFormula::insetAllowed(Inset::Code code) const
567 {
568         return code == Inset::LABEL_CODE && display(); 
569 }
570
571
572 int InsetFormula::ascent(BufferView *, LyXFont const &) const
573 {
574         return par_->ascent() + 2;
575 }
576
577
578 int InsetFormula::descent(BufferView *, LyXFont const &) const
579 {
580         return par_->descent() - 2;
581 }
582
583
584 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
585 {
586         metrics(bv, font);
587         return par_->width();
588 }
589
590
591 MathInsetTypes InsetFormula::getType() const
592 {
593         return mat()->getType();
594 }