]> git.lyx.org Git - lyx.git/blob - src/mathed/formula.C
a3cb00613fe9ff7acb32b93a9ec38222089c2822
[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                         expr.insert(pos - 15,  "*");
103                 }
104
105                 string full = "latex(" +  extra + '(' + expr + "));";
106                 string out = captureOutput("maple -q", header + full + trailer);
107
108                 // change \_ into _
109
110                 //
111                 MathArray res;
112                 mathed_parse_cell(res, out);
113                 return res;
114         }
115                 
116         
117         MathArray pipeThroughOctave(string const &, MathArray const & ar)
118         {
119                 string out = captureOutput("octave -q", ar.octavize());
120                 if (out.size() > 6) // remove 'ans = '
121                         out = out.substr(6);
122
123                 // parse output as matrix or single number
124                 MathAtom at(new MathArrayInset(out));
125                 MathArrayInset const * mat = at.nucleus()->asArrayInset();
126                 MathArray res;
127                 if (mat->ncols() == 1 && mat->nrows() == 1)
128                         res.push_back(mat->cell(0));
129                 else {
130                         res.push_back(MathAtom(new MathDelimInset("(", ")")));
131                         res.back()->cell(0).push_back(at);
132                 }
133                 return res;
134         }
135
136
137         MathArray pipeThroughExtern(string const & arg, MathArray const & ar)
138         {
139                 string lang;
140                 string extra;
141                 istringstream iss(arg.c_str());
142                 iss >> lang >> extra;
143                 if (extra.empty())
144                         extra = "noextra";      
145
146                 if (lang == "octave")
147                         return pipeThroughOctave(extra, ar);
148
149                 if (lang == "maple")
150                         return pipeThroughMaple(extra, ar);
151
152                 // create normalized expression
153                 ostringstream os;
154                 os << "[" << extra << ' ';
155                 ar.writeNormal(os); 
156                 os << "]";
157                 string data = os.str().c_str();
158
159                 // search external script
160                 string file = LibFileSearch("mathed", "extern_" + lang);
161                 if (file.empty()) {
162                         lyxerr << "converter to '" << lang << "' not found\n";
163                         return MathArray();
164                 }
165                 
166                 // run external sript
167                 string out = captureOutput(file, data);
168                 MathArray res;
169                 mathed_parse_cell(res, out);
170                 return res;
171         }
172
173 }
174
175
176 InsetFormula::InsetFormula()
177         : par_(MathAtom(new MathMatrixInset))
178 {}
179
180
181 InsetFormula::InsetFormula(MathInsetTypes t)
182         : par_(MathAtom(new MathMatrixInset(t)))
183 {}
184
185
186 InsetFormula::InsetFormula(string const & s) 
187 {
188         if (s.size()) {
189                 bool res = mathed_parse_normal(par_, s);
190
191                 if (!res)
192                         res = mathed_parse_normal(par_, "$" + s + "$");
193
194                 if (!res) {
195                         lyxerr << "cannot interpret '" << s << "' as math\n";
196                         par_ = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
197                 }
198         }
199         metrics();
200 }
201
202
203 Inset * InsetFormula::clone(Buffer const &, bool) const
204 {
205         return new InsetFormula(*this);
206 }
207
208
209 void InsetFormula::write(Buffer const * buf, ostream & os) const
210 {
211         os << "Formula ";
212         latex(buf, os, false, false);
213 }
214
215
216 int InsetFormula::latex(Buffer const * buf, ostream & os, bool fragil, bool)
217         const
218 {
219         MathWriteInfo wi(buf, os, fragil);
220         par_->write(wi);
221         return 1;
222 }
223
224
225 int InsetFormula::ascii(Buffer const * buf, ostream & os, int) const
226 {
227         MathWriteInfo wi(buf, os, false);
228         par_->write(wi);
229         return 1;
230 }
231
232
233 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
234 {
235         return ascii(buf, os, 0);
236 }
237
238
239 int InsetFormula::docbook(Buffer const * buf, ostream & os) const
240 {
241         return ascii(buf, os, 0);
242 }
243
244
245 void InsetFormula::read(Buffer const *, LyXLex & lex)
246 {
247         mathed_parse_normal(par_, lex);
248         metrics();
249 }
250
251
252 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
253                         int y, float & xx, bool) const
254 {
255         int x = int(xx) - 1;
256         y -= 2;
257
258         Painter & pain = bv->painter();
259
260         metrics(bv, font);
261         int w = par_->width();
262         int h = par_->height();
263         int a = par_->ascent();
264         pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
265
266         if (mathcursor && mathcursor->formula() == this) {
267                 mathcursor->drawSelection(pain);
268                 pain.rectangle(x, y - a, w, h, LColor::mathframe);
269         }
270
271         par_->draw(pain, x, y);
272         xx += par_->width();
273         xo_ = x;
274         yo_ = y;
275
276         setCursorVisible(false);
277 }
278
279
280 vector<string> const InsetFormula::getLabelList() const
281 {
282         return mat()->getLabelList();
283 }
284
285
286 UpdatableInset::RESULT
287 InsetFormula::localDispatch(BufferView * bv, kb_action action,
288          string const & arg)
289 {
290         RESULT result = DISPATCHED;
291
292         switch (action) {
293
294                 case LFUN_BREAKLINE: 
295                         bv->lockedInsetStoreUndo(Undo::INSERT);
296                         mathcursor->breakLine();
297                         mathcursor->normalize();
298                         updateLocal(bv, true);
299                         break;
300
301                 case LFUN_MATH_NUMBER:
302                 {
303                         //lyxerr << "toggling all numbers\n";
304                         if (display()) {
305                                 bv->lockedInsetStoreUndo(Undo::INSERT);
306                                 bool old = mat()->numberedType();
307                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
308                                         mat()->numbered(row, !old);
309                                 bv->owner()->message(old ? _("No number") : _("Number"));
310                                 updateLocal(bv, true);
311                         }
312                         break;
313                 }
314
315                 case LFUN_MATH_NONUMBER:
316                 {
317                         //lyxerr << "toggling line number\n";
318                         if (display()) {
319                                 bv->lockedInsetStoreUndo(Undo::INSERT);
320                                 MathCursor::row_type row = mathcursor->row();
321                                 bool old = mat()->numbered(row);
322                                 bv->owner()->message(old ? _("No number") : _("Number"));
323                                 mat()->numbered(row, !old);
324                                 updateLocal(bv, true);
325                         }
326                         break;
327                 }
328
329                 case LFUN_INSERT_LABEL:
330                 {
331                         bv->lockedInsetStoreUndo(Undo::INSERT);
332
333                         MathCursor::row_type row = mathcursor->row();
334                         string old_label = mat()->label(row);
335                         string new_label = arg;
336
337                         if (new_label.empty()) {
338                                 string const default_label =
339                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
340                                 pair<bool, string> const res = old_label.empty()
341                                         ? askForText(_("Enter new label to insert:"), default_label)
342                                         : askForText(_("Enter label:"), old_label);
343                                 
344                                 lyxerr << "res: " << res.first << " - '" << res.second << "'\n";
345                                 if (!res.first)
346                                         break;
347                                 new_label = frontStrip(strip(res.second));
348                         }
349
350                         //if (new_label == old_label)
351                         //      break;  // Nothing to do
352
353                         if (!new_label.empty()) {
354                                 lyxerr << "setting label to '" << new_label << "'\n";
355                                 mat()->numbered(row, true);
356                         }
357
358                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
359                                 bv->redraw();
360
361                         mat()->label(row, new_label);
362
363                         updateLocal(bv, true);
364                         break;
365                 }
366
367                 case LFUN_MATH_MUTATE:
368                 {
369                         bv->lockedInsetStoreUndo(Undo::EDIT);
370                         int x;
371                         int y;
372                         mathcursor->getPos(x, y);
373                         mat()->mutate(arg);
374                         mathcursor->setPos(x, y);
375                         mathcursor->normalize();
376                         updateLocal(bv, true);
377                         break;
378                 }
379
380                 case LFUN_MATH_EXTERN:
381                 {
382                         bv->lockedInsetStoreUndo(Undo::EDIT);
383                         handleExtern(arg);
384                         // re-compute inset dimension
385                         metrics(bv);
386                         updateLocal(bv, true);
387                         break;
388                 }
389
390                 case LFUN_MATH_DISPLAY:
391                 {
392                         int x;
393                         int y;
394                         mathcursor->getPos(x, y);
395                         if (mat()->getType() == LM_OT_SIMPLE)
396                                 mat()->mutate(LM_OT_EQUATION);
397                         else
398                                 mat()->mutate(LM_OT_SIMPLE);
399                         mathcursor->setPos(x, y);
400                         mathcursor->normalize();
401                         updateLocal(bv, true);
402                         break;
403                 }
404                 
405                 case LFUN_PASTESELECTION:
406                 {
407                         string const clip = bv->getClipboard();
408                 if (!clip.empty())
409                                 mathed_parse_normal(par_, clip);
410                         break;
411                 }
412
413                 case LFUN_MATH_COLUMN_INSERT:
414                 {
415                         if (mat()->getType() == LM_OT_ALIGN)
416                                 mat()->mutate(LM_OT_ALIGNAT);
417                         mat()->addCol(mat()->ncols());
418                         mathcursor->normalize();
419                         updateLocal(bv, true);
420                 }
421
422                 default:
423                         result = InsetFormulaBase::localDispatch(bv, action, arg);
424         }
425
426         return result;
427 }
428
429
430 void InsetFormula::handleExtern(const string & arg)
431 {
432         // where are we?
433         if (!mathcursor)
434                 return; 
435
436         bool selected = mathcursor->selection();
437
438         MathArray ar;
439         if (selected) {
440                 mathcursor->selGet(ar);
441                 lyxerr << "use selection: " << ar << "\n";
442         } else {
443                 mathcursor->end();
444                 mathcursor->stripFromLastEqualSign();
445                 ar = mathcursor->cursor().cell();
446                 mathcursor->insert(MathAtom(new MathCharInset('=', LM_TC_VAR)));
447                 //lyxerr << "use whole cell: " << ar << "\n";
448         }
449
450         mathcursor->insert(pipeThroughExtern(arg, ar));
451 }
452
453
454 bool InsetFormula::display() const
455 {
456         return mat()->getType() != LM_OT_SIMPLE;
457 }
458
459
460 MathMatrixInset const * InsetFormula::mat() const
461 {
462         lyx::Assert(par_->asMatrixInset());
463         return par_->asMatrixInset();
464 }
465
466
467 MathMatrixInset * InsetFormula::mat()
468 {
469         lyx::Assert(par_->asMatrixInset());
470         return par_->asMatrixInset();
471 }
472
473
474 Inset::Code InsetFormula::lyxCode() const
475 {
476         return Inset::MATH_CODE;
477 }
478
479
480 void InsetFormula::validate(LaTeXFeatures & features) const
481 {
482         par_->validate(features);
483 }
484
485
486 bool InsetFormula::insetAllowed(Inset::Code code) const
487 {
488         return code == Inset::LABEL_CODE && display(); 
489 }
490
491
492 int InsetFormula::ascent(BufferView *, LyXFont const &) const
493 {
494         return par_->ascent() + 2;
495 }
496
497
498 int InsetFormula::descent(BufferView *, LyXFont const &) const
499 {
500         return par_->descent() - 2;
501 }
502
503
504 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
505 {
506         metrics(bv, font);
507         return par_->width();
508 }
509
510
511 MathInsetTypes InsetFormula::getType() const
512 {
513         return mat()->getType();
514 }