]> git.lyx.org Git - lyx.git/blob - src/mathed/formulabase.C
streamlining interaction mathed <-> rest of the world
[lyx.git] / src / mathed / formulabase.C
1 /*
2 *  File:        formulabase.C
3 *  Purpose:     Implementation of common parts of the LyX  math insets
4 *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 *  Created:     January 1996
6 *
7 *  Copyright: 1996-1998 Alejandro Aguilar Sierra
8 *
9 *  Version: 0.4, Lyx project.
10 *
11 *   You are free to use and modify this code under the terms of
12 *   the GNU General Public Licence version 2 or later.
13 */
14
15 #include <config.h>
16 #include <fstream>
17
18 #include "Lsstream.h"
19 #include "support/LAssert.h"
20
21 #ifdef __GNUG__
22 #pragma implementation
23 #endif
24
25 #include "formula.h"
26 #include "formulamacro.h"
27 #include "lyxrc.h"
28 #include "funcrequest.h"
29 #include "BufferView.h"
30 #include "lyxtext.h"
31 #include "lyxfunc.h"
32 #include "gettext.h"
33 #include "LaTeXFeatures.h"
34 #include "debug.h"
35 #include "math_support.h"
36 #include "math_metricsinfo.h"
37 #include "support/lstrings.h"
38 #include "frontends/LyXView.h"
39 #include "frontends/font_metrics.h"
40 #include "frontends/mouse_state.h"
41 #include "Lsstream.h"
42 #include "math_arrayinset.h"
43 #include "math_charinset.h"
44 #include "math_deliminset.h"
45 #include "math_cursor.h"
46 #include "math_factory.h"
47 #include "math_fontinset.h"
48 #include "math_hullinset.h"
49 #include "math_iterator.h"
50 #include "math_macrotable.h"
51 #include "math_parser.h"
52 #include "math_pos.h"
53 #include "math_spaceinset.h"
54 #include "undo_funcs.h"
55 #include "textpainter.h"
56 #include "frontends/Dialogs.h"
57 #include "intl.h"
58 #include "insets/insetcommandparams.h"
59 #include "ref_inset.h"
60
61 using std::endl;
62 using std::ostream;
63 using std::vector;
64 using std::abs;
65
66 MathCursor * mathcursor = 0;
67
68
69 namespace {
70
71 // local global
72 int first_x;
73 int first_y;
74
75
76
77 bool openNewInset(BufferView * bv, UpdatableInset * new_inset)
78 {
79         if (!bv->insertInset(new_inset)) {
80                 delete new_inset;
81                 return false;
82         }
83         new_inset->edit(bv, true);
84         return true;
85 }
86
87
88 } // namespace anon
89
90
91
92 InsetFormulaBase::InsetFormulaBase()
93         : font_(), xo_(0), yo_(0)
94 {
95         // This is needed as long the math parser is not re-entrant
96         initMath();
97         //lyxerr << "sizeof MathInset: " << sizeof(MathInset) << "\n";
98         //lyxerr << "sizeof MathMetricsInfo: " << sizeof(MathMetricsInfo) << "\n";
99         //lyxerr << "sizeof MathCharInset: " << sizeof(MathCharInset) << "\n";
100         //lyxerr << "sizeof LyXFont: " << sizeof(LyXFont) << "\n";
101 }
102
103
104 // simply scrap this function if you want
105 void InsetFormulaBase::mutateToText()
106 {
107 #if 0
108         // translate to latex
109         ostringstream os;
110         latex(NULL, os, false, false);
111         string str = os.str();
112
113         // insert this text
114         LyXText * lt = view_->getLyXText();
115         string::const_iterator cit = str.begin();
116         string::const_iterator end = str.end();
117         for (; cit != end; ++cit)
118                 view_->owner()->getIntl()->getTransManager().TranslateAndInsert(*cit, lt);
119
120         // remove ourselves
121         //view_->owner()->dispatch(LFUN_ESCAPE);
122 #endif
123 }
124
125
126 void InsetFormulaBase::handleFont
127         (BufferView * bv, string const & arg, string const & font)
128 {
129         bv->lockedInsetStoreUndo(Undo::EDIT);
130         bool sel = mathcursor->selection();
131         if (sel)
132                 updateLocal(bv, true);
133         mathcursor->handleNest(createMathInset(font));
134         mathcursor->insert(arg);
135         if (!sel)
136                 updateLocal(bv, false);
137 }
138
139
140 // Check if uses AMS macros
141 void InsetFormulaBase::validate(LaTeXFeatures &) const
142 {}
143
144
145 void InsetFormulaBase::metrics(BufferView * bv, LyXFont const & f) const
146 {
147         font_ = f;
148         metrics(bv);
149 }
150
151
152 void InsetFormulaBase::metrics(BufferView * bv) const
153 {
154         if (bv)
155                 view_ = bv->owner()->view();
156         MathMetricsInfo mi;
157         mi.base.style = LM_ST_TEXT;
158         mi.base.font  = font_;
159         mi.base.font.setColor(LColor::math);
160         par()->metrics(mi);
161 }
162
163
164 string const InsetFormulaBase::editMessage() const
165 {
166         return _("Math editor mode");
167 }
168
169
170 void InsetFormulaBase::edit(BufferView * bv, int x, int y, mouse_button::state)
171 {
172         if (!bv->lockInset(this))
173                 lyxerr[Debug::MATHED] << "Cannot lock inset!!!" << endl;
174         releaseMathCursor(bv);
175         mathcursor = new MathCursor(this, true);
176         metrics(bv);
177         mathcursor->setPos(x, y);
178         //lyxerr << "setting pos to " << x << "," << y << "\n";
179
180         // if that is removed, we won't get the magenta box when entering an
181         // inset for the first time
182         bv->updateInset(this, false);
183 }
184
185
186 void InsetFormulaBase::edit(BufferView * bv, bool front)
187 {
188         if (!bv->lockInset(this))
189                 lyxerr << "Cannot lock math inset in edit call!\n";
190         releaseMathCursor(bv);
191         mathcursor = new MathCursor(this, front);
192         metrics(bv);
193         bv->updateInset(this, false);
194 }
195
196
197 void InsetFormulaBase::insetUnlock(BufferView * bv)
198 {
199         if (mathcursor) {
200                 if (mathcursor->inMacroMode()) {
201                         mathcursor->macroModeClose();
202                         updateLocal(bv, true);
203                 }
204                 releaseMathCursor(bv);
205         }
206         generatePreview();
207         bv->updateInset(this, false);
208 }
209
210
211 void InsetFormulaBase::getCursorPos(BufferView *, int & x, int & y) const
212 {
213         // calling metrics here destroys the cached xo,yo positions e.g. in
214         // MathParboxinset. And it would be too expensive anyway...
215         //metrics(bv);
216         mathcursor->getPos(x, y);
217         //x -= xo_;
218         y -= yo_;
219         //lyxerr << "getCursorPos: " << x << " " << y << "\n";
220 }
221
222
223 void InsetFormulaBase::toggleInsetCursor(BufferView * bv)
224 {
225         //lyxerr << "toggleInsetCursor: " << isCursorVisible() << "\n";
226         if (isCursorVisible())
227                 hideInsetCursor(bv);
228         else
229                 showInsetCursor(bv);
230 }
231
232
233 void InsetFormulaBase::showInsetCursor(BufferView * bv, bool)
234 {
235         if (isCursorVisible())
236                 return;
237         fitInsetCursor(bv);
238         int x, y, asc, des;
239         getCursorPos(bv, x, y);
240         math_font_max_dim(font_, asc, des);
241         bv->showLockedInsetCursor(x, y, asc, des);
242         setCursorVisible(true);
243         //lyxerr << "showInsetCursor: " << x << " " << y << "\n";
244 }
245
246
247 void InsetFormulaBase::hideInsetCursor(BufferView * bv)
248 {
249         if (!isCursorVisible())
250                 return;
251         bv->hideLockedInsetCursor();
252         setCursorVisible(false);
253         //lyxerr << "hideInsetCursor: \n";
254 }
255
256
257 void InsetFormulaBase::fitInsetCursor(BufferView * bv) const
258 {
259         if (!mathcursor)
260                 return;
261         int x, y, asc, des;
262         math_font_max_dim(font_, asc, des);
263         getCursorPos(bv, x, y);
264         //y += yo_;
265         //lyxerr << "fitInsetCursor: x: " << x << " y: " << y << " yo: " << yo_ << "\n";
266         bv->fitLockedInsetCursor(x, y, asc, des);
267 }
268
269
270 void InsetFormulaBase::toggleInsetSelection(BufferView * bv)
271 {
272         if (mathcursor)
273                 bv->updateInset(this, false);
274 }
275
276
277 vector<string> const InsetFormulaBase::getLabelList() const
278 {
279   return vector<string>();
280 }
281
282
283 void InsetFormulaBase::updateLocal(BufferView * bv, bool dirty)
284 {
285         bv->updateInset(this, dirty);
286 }
287
288
289 bool InsetFormulaBase::insetButtonRelease(BufferView * bv,
290         int x, int y, mouse_button::state button)
291 {
292         if (!mathcursor)
293                 return false;
294
295         //lyxerr << "insetButtonRelease: " << x << " " << y << "\n";
296         hideInsetCursor(bv);
297         showInsetCursor(bv);
298         bv->updateInset(this, false);
299
300         if (button == mouse_button::button3) {
301                 // try to dispatch to enclosed insets first
302                 if (mathcursor->dispatch(FuncRequest(bv, LFUN_MOUSE_RELEASE, x, y, 3)))
303                         return true;
304
305                 // launch math panel for right mouse button
306                 bv->owner()->getDialogs().showMathPanel();
307                 return true;
308         }
309
310         if (button == mouse_button::button1) {
311                 // try to dispatch to enclosed insets first
312                 if (mathcursor->dispatch(FuncRequest(bv, LFUN_MOUSE_RELEASE, x, y, 1)))
313                         return true;
314
315                 // try to set the cursor
316                 //delete mathcursor;
317                 //mathcursor = new MathCursor(this, x == 0);
318                 //metrics(bv);
319                 //mathcursor->setPos(x + xo_, y + yo_);
320                 return true;
321         }
322         return false;
323 }
324
325
326 void InsetFormulaBase::insetButtonPress(BufferView * bv,
327                                         int x, int y, mouse_button::state button)
328 {
329         //lyxerr << "insetButtonPress: "
330         //      << x << " " << y << " but: " << button << "\n";
331         //lyxerr << "formula: ";
332         //par()->dump();
333
334         releaseMathCursor(bv);
335         mathcursor = new MathCursor(this, x == 0);
336
337         if (button == mouse_button::button1) {
338                 // just set the cursor here
339                 //lyxerr << "setting cursor\n";
340                 metrics(bv);
341                 first_x = x;
342                 first_y = y;
343                 mathcursor->selClear();
344                 mathcursor->setPos(x + xo_, y + yo_);
345
346                 if (mathcursor->dispatch(FuncRequest(bv, LFUN_MOUSE_PRESS, x, y, 1))) {
347                         //delete mathcursor;
348                         return;
349                 }
350
351         }
352         if (button == mouse_button::button3) {
353                 if (mathcursor->dispatch(FuncRequest(bv, LFUN_MOUSE_PRESS, x, y, 3))) {
354                         //delete mathcursor;
355                         return;
356                 }
357         }
358         bv->updateInset(this, false);
359 }
360
361
362 void InsetFormulaBase::insetMotionNotify(BufferView * bv,
363         int x, int y, mouse_button::state button)
364 {
365         if (!mathcursor)
366                 return;
367
368         if (button == mouse_button::button1)
369                 if (mathcursor->dispatch(FuncRequest(bv, LFUN_MOUSE_MOTION, x, y, 1)))
370                         return;
371
372         if (button == mouse_button::button3)
373                 if (mathcursor->dispatch(FuncRequest(bv, LFUN_MOUSE_MOTION, x, y, 3)))
374                         return;
375
376         if (abs(x - first_x) < 2 && abs(y - first_y) < 2) {
377                 //lyxerr << "insetMotionNotify: ignored\n";
378                 return;
379         }
380         first_x = x;
381         first_y = y;
382
383         if (!mathcursor->selection())
384                 mathcursor->selStart();
385
386         //lyxerr << "insetMotionNotify: " << x + xo_ << ' ' << y + yo_
387         //      << ' ' << button << "\n";
388         hideInsetCursor(bv);
389         mathcursor->setPos(x + xo_, y + yo_);
390         showInsetCursor(bv);
391         bv->updateInset(this, false);
392 }
393
394
395 UpdatableInset::RESULT
396 InsetFormulaBase::localDispatch(FuncRequest const & ev)
397 {
398         //lyxerr << "InsetFormulaBase::localDispatch: act: " << action
399         //      << " arg: '" << arg
400         //      << "' cursor: " << mathcursor << "\n";
401
402         if (!mathcursor)
403                 return UNDISPATCHED;
404
405         BufferView * bv    = ev.view();
406         string argument    = ev.argument;
407         RESULT result      = DISPATCHED;
408         bool sel           = false;
409         bool was_macro     = mathcursor->inMacroMode();
410         bool was_selection = mathcursor->selection();
411
412         hideInsetCursor(bv);
413
414         mathcursor->normalize();
415         mathcursor->touch();
416
417         switch (ev.action) {
418
419         case LFUN_MATH_MUTATE:
420         case LFUN_MATH_DISPLAY:
421         case LFUN_MATH_HALIGN:
422         case LFUN_MATH_VALIGN:
423         case LFUN_MATH_ROW_INSERT:
424         case LFUN_MATH_ROW_DELETE:
425         case LFUN_MATH_COLUMN_INSERT:
426         case LFUN_MATH_COLUMN_DELETE:
427         case LFUN_MATH_NUMBER:
428         case LFUN_MATH_NONUMBER:
429         case LFUN_TABINSERT:
430         case LFUN_BREAKLINE:
431         case LFUN_DELETE_LINE_FORWARD:
432         case LFUN_INSERT_LABEL:
433         case LFUN_MATH_EXTERN:
434                 bv->lockedInsetStoreUndo(Undo::EDIT);
435                 mathcursor->dispatch(ev);
436                 updateLocal(bv, true);
437                 break;
438
439         case LFUN_WORDRIGHTSEL:
440         case LFUN_RIGHTSEL:
441                 sel = true; // fall through...
442         case LFUN_RIGHT:
443                 result = mathcursor->right(sel) ? DISPATCHED : FINISHED_RIGHT;
444                 //lyxerr << "calling scroll 20\n";
445                 //scroll(bv, 20);
446                 updateLocal(bv, false);
447                 // write something to the minibuffer
448                 //bv->owner()->message(mathcursor->info());
449                 break;
450
451         case LFUN_WORDLEFTSEL:
452         case LFUN_LEFTSEL:
453                 sel = true; // fall through
454         case LFUN_LEFT:
455                 result = mathcursor->left(sel) ? DISPATCHED : FINISHED;
456                 updateLocal(bv, false);
457                 break;
458
459         case LFUN_UPSEL:
460                 sel = true; // fall through
461         case LFUN_UP:
462                 result = mathcursor->up(sel) ? DISPATCHED : FINISHED_UP;
463                 updateLocal(bv, false);
464                 break;
465
466         case LFUN_DOWNSEL:
467                 sel = true; // fall through
468         case LFUN_DOWN:
469                 result = mathcursor->down(sel) ? DISPATCHED : FINISHED_DOWN;
470                 updateLocal(bv, false);
471                 break;
472
473         case LFUN_HOMESEL:
474                 sel = true; // fall through
475         case LFUN_HOME:
476                 result = mathcursor->home(sel) ? DISPATCHED : FINISHED;
477                 updateLocal(bv, false);
478                 break;
479
480         case LFUN_ENDSEL:
481                 sel = true; // fall through
482         case LFUN_END:
483                 result = mathcursor->end(sel) ? DISPATCHED : FINISHED_RIGHT;
484                 updateLocal(bv, false);
485                 break;
486
487         case LFUN_PRIORSEL:
488         case LFUN_PRIOR:
489                 result = FINISHED_UP;
490                 updateLocal(bv, false);
491                 break;
492
493         case LFUN_NEXTSEL:
494         case LFUN_NEXT:
495                 result = FINISHED_DOWN;
496                 updateLocal(bv, false);
497                 break;
498
499         case LFUN_TAB:
500                 mathcursor->idxNext();
501                 updateLocal(bv, false);
502                 break;
503
504         case LFUN_SHIFT_TAB:
505                 mathcursor->idxPrev();
506                 updateLocal(bv, false);
507                 break;
508
509         case LFUN_DELETE_WORD_BACKWARD:
510         case LFUN_BACKSPACE:
511                 bv->lockedInsetStoreUndo(Undo::DELETE);
512                 mathcursor->backspace();
513                 updateLocal(bv, true);
514                 break;
515
516         case LFUN_DELETE_WORD_FORWARD:
517         case LFUN_DELETE:
518                 bv->lockedInsetStoreUndo(Undo::DELETE);
519                 mathcursor->erase();
520                 bv->updateInset(this, true);
521                 break;
522
523         //    case LFUN_GETXY:
524         //      sprintf(dispatch_buffer, "%d %d",);
525         //      dispatch_result = dispatch_buffer;
526         //      break;
527         case LFUN_SETXY: {
528                 lyxerr << "LFUN_SETXY broken!\n";
529                 int x = 0;
530                 int y = 0;
531                 istringstream is(ev.argument.c_str());
532                 is >> x >> y;
533                 mathcursor->setPos(x, y);
534                 updateLocal(bv, false);
535                 break;
536         }
537
538 /*
539         case LFUN_PASTESELECTION: {
540                 string const clip = bv->getClipboard();
541                 if (!clip.empty())
542                         mathed_parse_normal(par_, clip);
543                 break;
544         }
545 */
546
547         case LFUN_PASTE:
548                 if (was_macro)
549                         mathcursor->macroModeClose();
550                 bv->lockedInsetStoreUndo(Undo::EDIT);
551                 mathcursor->selPaste();
552                 updateLocal(bv, true);
553                 break;
554
555         case LFUN_CUT:
556                 bv->lockedInsetStoreUndo(Undo::DELETE);
557                 mathcursor->selCut();
558                 updateLocal(bv, true);
559                 break;
560
561         case LFUN_COPY:
562                 mathcursor->selCopy();
563                 break;
564
565
566         // Special casing for superscript in case of LyX handling
567         // dead-keys:
568         case LFUN_CIRCUMFLEX:
569                 if (ev.argument.empty()) {
570                         // do superscript if LyX handles
571                         // deadkeys
572                         bv->lockedInsetStoreUndo(Undo::EDIT);
573                         mathcursor->script(true);
574                         updateLocal(bv, true);
575                 }
576                 break;
577
578         case LFUN_UMLAUT:
579         case LFUN_ACUTE:
580         case LFUN_GRAVE:
581         case LFUN_BREVE:
582         case LFUN_DOT:
583         case LFUN_MACRON:
584         case LFUN_CARON:
585         case LFUN_TILDE:
586         case LFUN_CEDILLA:
587         case LFUN_CIRCLE:
588         case LFUN_UNDERDOT:
589         case LFUN_TIE:
590         case LFUN_OGONEK:
591         case LFUN_HUNG_UMLAUT:
592                 break;
593
594         //  Math fonts
595         case LFUN_GREEK_TOGGLE: handleFont(bv, ev.argument, "lyxgreek"); break;
596         case LFUN_BOLD:         handleFont(bv, ev.argument, "textbf"); break;
597         case LFUN_SANS:         handleFont(bv, ev.argument, "textsf"); break;
598         case LFUN_EMPH:         handleFont(bv, ev.argument, "mathcal"); break;
599         case LFUN_ROMAN:        handleFont(bv, ev.argument, "mathrm"); break;
600         case LFUN_CODE:         handleFont(bv, ev.argument, "texttt"); break;
601         case LFUN_FRAK:         handleFont(bv, ev.argument, "mathfrak"); break;
602         case LFUN_ITAL:         handleFont(bv, ev.argument, "mathit"); break;
603         case LFUN_NOUN:         handleFont(bv, ev.argument, "mathbb"); break;
604         case LFUN_DEFAULT:      handleFont(bv, ev.argument, "textnormal"); break;
605         case LFUN_FREE:         handleFont(bv, ev.argument, "textrm"); break;
606
607         case LFUN_GREEK:
608                 handleFont(bv, ev.argument, "lyxgreek1");
609                 if (ev.argument.size())
610                         mathcursor->interpret(ev.argument);
611                 break;
612
613         case LFUN_MATH_MODE:
614                 if (mathcursor->currentMode()) {
615                         handleFont(bv, ev.argument, "textrm");
616                 } else {
617                         mathcursor->niceInsert(MathAtom(new MathHullInset("simple")));
618                         updateLocal(bv, true);
619                 }
620                 //bv->owner()->message(_("math text mode toggled"));
621                 break;
622
623         case LFUN_MATH_LIMITS:
624                 bv->lockedInsetStoreUndo(Undo::EDIT);
625                 if (mathcursor->toggleLimits())
626                         updateLocal(bv, true);
627                 break;
628
629         case LFUN_MATH_SIZE:
630 #if 0
631                 if (!arg.empty()) {
632                         bv->lockedInsetStoreUndo(Undo::EDIT);
633                         mathcursor->setSize(arg);
634                         updateLocal(bv, true);
635                 }
636 #endif
637                 break;
638
639         case LFUN_INSERT_MATRIX:
640                 if (!ev.argument.empty()) {
641                         bv->lockedInsetStoreUndo(Undo::EDIT);
642                         mathcursor->interpret("matrix " + ev.argument);
643                         updateLocal(bv, true);
644                 }
645                 break;
646
647         case LFUN_SUPERSCRIPT:
648         case LFUN_SUBSCRIPT:
649         {
650                 bv->lockedInsetStoreUndo(Undo::EDIT);
651                 mathcursor->script(ev.action == LFUN_SUPERSCRIPT);
652                 updateLocal(bv, true);
653                 break;
654         }
655
656         case LFUN_MATH_DELIM:
657         {
658                 //lyxerr << "formulabase::LFUN_MATH_DELIM, arg: '" << arg << "'\n";
659                 string ls;
660                 string rs = split(ev.argument, ls, ' ');
661                 // Reasonable default values
662                 if (ls.empty())
663                         ls = '(';
664                 if (rs.empty())
665                         rs = ')';
666
667                 bv->lockedInsetStoreUndo(Undo::EDIT);
668                 mathcursor->handleNest(MathAtom(new MathDelimInset(ls, rs)));
669                 updateLocal(bv, true);
670                 break;
671         }
672
673         case LFUN_PROTECTEDSPACE:
674         case LFUN_MATH_SPACE:
675                 bv->lockedInsetStoreUndo(Undo::EDIT);
676                 mathcursor->insert(MathAtom(new MathSpaceInset(",")));
677                 updateLocal(bv, true);
678                 break;
679
680         case LFUN_UNDO:
681                 bv->owner()->message(_("Invalid action in math mode!"));
682                 break;
683
684
685         case LFUN_EXEC_COMMAND:
686                 result = UNDISPATCHED;
687                 break;
688
689         case LFUN_INSET_ERT:
690                 // interpret this as if a backslash was typed
691                 bv->lockedInsetStoreUndo(Undo::EDIT);
692                 mathcursor->interpret('\\');
693                 updateLocal(bv, true);
694                 break;
695
696         case LFUN_BREAKPARAGRAPH:
697         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
698         case LFUN_BREAKPARAGRAPH_SKIP:
699                 argument = "\n";
700                 // fall through
701
702         case -1:
703         case LFUN_INSERT_MATH:
704         case LFUN_SELFINSERT:
705                 if (!argument.empty()) {
706                         bv->lockedInsetStoreUndo(Undo::EDIT);
707                         if (argument.size() == 1)
708                                 result = mathcursor->interpret(argument[0]) ? DISPATCHED : FINISHED_RIGHT;
709                         else
710                                 result = mathcursor->interpret(argument) ? DISPATCHED : FINISHED_RIGHT;
711                         updateLocal(bv, true);
712                 }
713                 break;
714
715         case LFUN_MATH_PANEL:
716                 result = UNDISPATCHED;
717                 break;
718
719         case LFUN_ESCAPE:
720                 if (mathcursor->selection())
721                         mathcursor->selClear();
722                 else
723                         result = UNDISPATCHED;
724                 break;
725
726         case LFUN_INSET_TOGGLE:
727                 mathcursor->insetToggle();
728                 updateLocal(bv, true);
729                 break;
730
731         case LFUN_REF_INSERT:
732                 //if (argument.empty()) {
733                 //      InsetCommandParams p("ref");
734                 //      owner_->getDialogs().createRef(p.getAsString());
735                 //} else {
736                 //      InsetCommandParams p;
737                 //      p.setFromString(argument);
738
739                 //      InsetRef * inset = new InsetRef(p, *buffer_);
740                 //      if (!insertInset(inset))
741                 //              delete inset;
742                 //      else
743                 //              updateInset(inset, true);
744                 //}
745                 //
746                 if (ev.argument.empty()) {
747                         InsetCommandParams p("ref");
748                         bv->owner()->getDialogs().createRef(p.getAsString());
749                 } else {
750                         //mathcursor->handleNest(new InsetRef2);
751                         //mathcursor->insert(arg);
752                         mathcursor->insert(MathAtom(new RefInset(ev.argument)));
753                 }
754                 updateLocal(bv, true);
755                 break;
756
757         default:
758                 result = UNDISPATCHED;
759         }
760
761         mathcursor->normalize();
762         mathcursor->touch();
763
764         lyx::Assert(mathcursor);
765
766         if (mathcursor->selection() || was_selection)
767                 toggleInsetSelection(bv);
768
769         if (result == DISPATCHED || result == DISPATCHED_NOUPDATE ||
770             result == UNDISPATCHED) {
771                 fitInsetCursor(bv);
772                 showInsetCursor(bv);
773                 revealCodes(bv);
774         } else {
775                 releaseMathCursor(bv);
776                 bv->unlockInset(this);
777         }
778
779         return result;  // original version
780 }
781
782
783 void InsetFormulaBase::revealCodes(BufferView * bv) const
784 {
785         if (!mathcursor)
786                 return;
787         bv->owner()->message(mathcursor->info());
788
789 #if 0
790         // write something to the minibuffer
791         // translate to latex
792         mathcursor->markInsert();
793         ostringstream os;
794         write(NULL, os);
795         string str = os.str();
796         mathcursor->markErase();
797         string::size_type pos = 0;
798         string res;
799         for (string::iterator it = str.begin(); it != str.end(); ++it) {
800                 if (*it == '\n')
801                         res += ' ';
802                 else if (*it == '\0') {
803                         res += "  -X-  ";
804                         pos = it - str.begin();
805                 }
806                 else
807                         res += *it;
808         }
809         if (pos > 30)
810                 res = res.substr(pos - 30);
811         if (res.size() > 60)
812                 res = res.substr(0, 60);
813         bv->owner()->message(res);
814 #endif
815 }
816
817
818 Inset::Code InsetFormulaBase::lyxCode() const
819 {
820         return Inset::MATH_CODE;
821 }
822
823
824 int InsetFormulaBase::ylow() const
825 {
826         return yo_ - ascent(view(), font_);
827 }
828
829
830 int InsetFormulaBase::yhigh() const
831 {
832         return yo_ + descent(view(), font_);
833 }
834
835
836 int InsetFormulaBase::xlow() const
837 {
838         return xo_;
839 }
840
841
842 int InsetFormulaBase::xhigh() const
843 {
844         return xo_ + width(view(), font_);
845 }
846
847
848 /////////////////////////////////////////////////////////////////////
849
850
851 bool InsetFormulaBase::searchForward(BufferView * bv, string const & str,
852                                      bool, bool)
853 {
854 #ifdef WITH_WARNINGS
855 #warning pretty ugly
856 #endif
857         static InsetFormulaBase * lastformula = 0;
858         static MathIterator current = MathIterator(ibegin(par().nucleus()));
859         static MathArray ar;
860         static string laststr;
861
862         if (lastformula != this || laststr != str) {
863                 //lyxerr << "reset lastformula to " << this << "\n";
864                 lastformula = this;
865                 laststr = str;
866                 current = ibegin(par().nucleus());
867                 ar.clear();
868                 mathed_parse_cell(ar, str);
869         } else {
870                 ++current;
871         }
872         //lyxerr << "searching '" << str << "' in " << this << ar << endl;
873
874         for (MathIterator it = current; it != iend(par().nucleus()); ++it) {
875                 if (it.cell().matchpart(ar, it.back().pos_)) {
876                         bv->unlockInset(bv->theLockingInset());
877                         if (!bv->lockInset(this)) {
878                                 lyxerr << "Cannot lock inset" << endl;
879                                 return false;
880                         }
881                         delete mathcursor;
882                         mathcursor = new MathCursor(this, true);
883                         metrics(bv);
884                         mathcursor->setSelection(it, ar.size());
885                         current = it;
886                         it.jump(ar.size());
887                         updateLocal(bv, false);
888                         return true;
889                 }
890         }
891
892         //lyxerr << "not found!\n";
893         lastformula = 0;
894         return false;
895 }
896
897
898 bool InsetFormulaBase::searchBackward(BufferView * bv, string const & what,
899                                       bool a, bool b)
900 {
901         lyxerr[Debug::MATHED] << "searching backward not implemented in mathed\n";
902         return searchForward(bv, what, a, b);
903 }
904
905
906 bool InsetFormulaBase::display() const
907 {
908         return par()->asHullInset() && par()->asHullInset()->display();
909 }
910
911
912 /////////////////////////////////////////////////////////////////////
913
914
915 void mathDispatchCreation(FuncRequest const & cmd, bool display)
916 {
917         BufferView * bv = cmd.view();
918         // use selection if available..
919         //string sel;
920         //if (action == LFUN_MATH_IMPORT_SELECTION)
921         //      sel = "";
922         //else
923
924         string sel = bv->getLyXText()->selectionAsString(bv->buffer(), false);
925
926         if (sel.empty()) {
927                 InsetFormula * f = new InsetFormula(bv);
928                 if (openNewInset(bv, f)) {
929                         bv->theLockingInset()->
930                                 localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
931                         // don't do that also for LFUN_MATH_MODE unless you want end up with
932                         // always changing to mathrm when opening an inlined inset
933                         // -- I really hate "LyXfunc overloading"...
934                         if (display)
935                                 f->localDispatch(FuncRequest(bv, LFUN_MATH_DISPLAY));
936                         f->localDispatch(FuncRequest(bv, LFUN_INSERT_MATH, cmd.argument));
937                 }
938         } else {
939                 // create a macro if we see "\\newcommand" somewhere, and an ordinary
940                 // formula otherwise
941                 InsetFormulaBase * f;
942                 if (sel.find("\\newcommand") == string::npos &&
943                                 sel.find("\\def") == string::npos)
944                         f = new InsetFormula(sel);
945                 else
946                         f = new InsetFormulaMacro(sel);
947                 bv->getLyXText()->cutSelection(bv);
948                 openNewInset(bv, f);
949         }
950         bv->owner()->getLyXFunc().setMessage(N_("Math editor mode"));
951 }
952
953
954 void mathDispatch(FuncRequest const & cmd)
955 {
956         BufferView * bv = cmd.view();
957         if (!bv->available())
958                 return;
959
960         switch (cmd.action) {
961
962                 case LFUN_MATH_DISPLAY:
963                         mathDispatchCreation(cmd, true);
964                         break;
965
966                 case LFUN_MATH_MODE:
967                         mathDispatchCreation(cmd, false);
968                         break;
969
970                 case LFUN_MATH_IMPORT_SELECTION:
971                         mathDispatchCreation(cmd, false);
972                         break;
973
974                 case LFUN_MATH_MACRO:
975                         if (cmd.argument.empty())
976                                 bv->owner()->getLyXFunc().setErrorMessage(N_("Missing argument"));
977                         else {
978                                 string s = cmd.argument;
979                                 string const s1 = token(s, ' ', 1);
980                                 int const na = s1.empty() ? 0 : lyx::atoi(s1);
981                                 openNewInset(bv, new InsetFormulaMacro(token(s, ' ', 0), na));
982                         }
983                         break;
984
985                 case LFUN_GREEK: 
986                 case LFUN_INSERT_MATH: 
987                 case LFUN_INSERT_MATRIX: 
988                 case LFUN_MATH_DELIM: {
989                         InsetFormula * f = new InsetFormula(bv);
990                         if (openNewInset(bv, f)) {
991                                 bv->theLockingInset()-> 
992                                         localDispatch(FuncRequest(bv, LFUN_MATH_MUTATE, "simple"));
993                                 bv->theLockingInset()->localDispatch(cmd);
994                         }
995                         break;
996                 }
997                 default:
998                         break;
999         }
1000 }