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