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