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