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