]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
Andreas' patch to prevent crash on click on previewd inset
[lyx.git] / src / mathed / math_nestinset.C
1 /**
2  * \file math_nestinset.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "math_nestinset.h"
14
15 #include "math_arrayinset.h"
16 #include "math_boxinset.h"
17 #include "math_braceinset.h"
18 #include "math_colorinset.h"
19 #include "math_commentinset.h"
20 #include "math_data.h"
21 #include "math_deliminset.h"
22 #include "math_factory.h"
23 #include "math_hullinset.h"
24 #include "math_mathmlstream.h"
25 #include "math_macroarg.h"
26 //#include "math_mboxinset.h"
27 #include "math_parser.h"
28 #include "math_scriptinset.h"
29 #include "math_spaceinset.h"
30 #include "math_symbolinset.h"
31 #include "math_support.h"
32 #include "math_unknowninset.h"
33
34 #include "BufferView.h"
35 #include "CutAndPaste.h"
36 #include "FuncStatus.h"
37 #include "LColor.h"
38 #include "bufferview_funcs.h"
39 #include "coordcache.h"
40 #include "cursor.h"
41 #include "debug.h"
42 #include "dispatchresult.h"
43 #include "funcrequest.h"
44 #include "gettext.h"
45 #include "outputparams.h"
46 #include "undo.h"
47
48 #include "support/lstrings.h"
49
50 #include "frontends/Dialogs.h"
51 #include "frontends/LyXView.h"
52 #include "frontends/Painter.h"
53
54 #include <sstream>
55
56 using lyx::cap::copySelection;
57 using lyx::cap::grabAndEraseSelection;
58 using lyx::cap::cutSelection;
59 using lyx::cap::pasteSelection;
60 using lyx::cap::replaceSelection;
61 using lyx::cap::selClearOrDel;
62
63 using std::endl;
64 using std::string;
65 using std::istringstream;
66
67
68 MathNestInset::MathNestInset(idx_type nargs)
69         : cells_(nargs), lock_(false)
70 {}
71
72
73 MathInset::idx_type MathNestInset::nargs() const
74 {
75         return cells_.size();
76 }
77
78
79 MathArray & MathNestInset::cell(idx_type i)
80 {
81         return cells_[i];
82 }
83
84
85 MathArray const & MathNestInset::cell(idx_type i) const
86 {
87         return cells_[i];
88 }
89
90
91 void MathNestInset::cursorPos(CursorSlice const & sl, bool boundary,
92         int & x, int & y) const
93 {
94 // FIXME: This is a hack. Ideally, the coord cache should not store
95 // absolute positions, but relative ones. This would mean to call
96 // setXY() not in MathArray::draw(), but in the parent insets' draw()
97 // with the correctly adjusted x,y values. But this means that we'd have
98 // to touch all (math)inset's draw() methods. Right now, we'll store
99 // absolute value, and make them here relative, only to make them
100 // absolute again when actually drawing the cursor. What a mess.
101         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
102         MathArray const & ar = sl.cell();
103         if (!theCoords.getArrays().has(&ar)) {
104                 // this can (semi-)legally happen if we just created this cell
105                 // and it never has been drawn before. So don't ASSERT.
106                 //lyxerr << "no cached data for array " << &ar << endl;
107                 x = 0;
108                 y = 0;
109                 return;
110         }
111         Point const pt = theCoords.getArrays().xy(&ar);
112         if (!theCoords.getInsets().has(this)) {
113                 // same as above
114                 //lyxerr << "no cached data for inset " << this << endl;
115                 x = 0;
116                 y = 0;
117                 return;
118         }
119         Point const pt2 = theCoords.getInsets().xy(this);
120         //lyxerr << "retrieving position cache for MathArray "
121         //      << pt.x_ << ' ' << pt.y_ << std::endl;
122         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
123         y = pt.y_ - pt2.y_;
124 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
125 //              << " asc: " << ascent() << "  des: " << descent()
126 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
127         // move cursor visually into empty cells ("blue rectangles");
128         if (ar.empty())
129                 x += 2;
130 }
131
132
133 void MathNestInset::metrics(MetricsInfo const & mi) const
134 {
135         MetricsInfo m = mi;
136         for (idx_type i = 0, n = nargs(); i != n; ++i)
137                 cell(i).metrics(m);
138 }
139
140
141 bool MathNestInset::idxNext(LCursor & cur) const
142 {
143         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
144         if (cur.idx() == cur.lastidx())
145                 return false;
146         ++cur.idx();
147         cur.pos() = 0;
148         return true;
149 }
150
151
152 bool MathNestInset::idxRight(LCursor & cur) const
153 {
154         return idxNext(cur);
155 }
156
157
158 bool MathNestInset::idxPrev(LCursor & cur) const
159 {
160         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
161         if (cur.idx() == 0)
162                 return false;
163         --cur.idx();
164         cur.pos() = cur.lastpos();
165         return true;
166 }
167
168
169 bool MathNestInset::idxLeft(LCursor & cur) const
170 {
171         return idxPrev(cur);
172 }
173
174
175 bool MathNestInset::idxFirst(LCursor & cur) const
176 {
177         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
178         if (nargs() == 0)
179                 return false;
180         cur.idx() = 0;
181         cur.pos() = 0;
182         return true;
183 }
184
185
186 bool MathNestInset::idxLast(LCursor & cur) const
187 {
188         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
189         if (nargs() == 0)
190                 return false;
191         cur.idx() = cur.lastidx();
192         cur.pos() = cur.lastpos();
193         return true;
194 }
195
196
197 void MathNestInset::dump() const
198 {
199         WriteStream os(lyxerr);
200         os << "---------------------------------------------\n";
201         write(os);
202         os << "\n";
203         for (idx_type i = 0, n = nargs(); i != n; ++i)
204                 os << cell(i) << "\n";
205         os << "---------------------------------------------\n";
206 }
207
208
209 void MathNestInset::draw(PainterInfo & pi, int x, int y) const
210 {
211 #if 0
212         if (lock_)
213                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
214                                         LColor::mathlockbg);
215 #endif
216         setPosCache(pi, x, y);
217 }
218
219
220 void MathNestInset::drawSelection(PainterInfo & pi, int x, int y) const
221 {
222         // FIXME: hack to get position cache warm
223         draw(pi, x, y);
224
225         // this should use the x/y values given, not the cached values
226         LCursor & cur = pi.base.bv->cursor();
227         if (!cur.selection())
228                 return;
229         if (!ptr_cmp(&cur.inset(), this))
230                 return;
231
232         CursorSlice s1 = cur.selBegin();
233         CursorSlice s2 = cur.selEnd();
234         //lyxerr << "MathNestInset::drawing selection: "
235         //      << " s1: " << s1 << " s2: " << s2 << endl;
236         if (s1.idx() == s2.idx()) {
237                 MathArray const & c = cell(s1.idx());
238                 int x1 = c.xo() + c.pos2x(s1.pos());
239                 int y1 = c.yo() - c.ascent();
240                 int x2 = c.xo() + c.pos2x(s2.pos());
241                 int y2 = c.yo() + c.descent();
242                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
243         //lyxerr << "MathNestInset::drawing selection 3: "
244         //      << " x1: " << x1 << " x2: " << x2
245         //      << " y1: " << y1 << " y2: " << y2 << endl;
246         } else {
247                 for (idx_type i = 0; i < nargs(); ++i) {
248                         if (idxBetween(i, s1.idx(), s2.idx())) {
249                                 MathArray const & c = cell(i);
250                                 int x1 = c.xo();
251                                 int y1 = c.yo() - c.ascent();
252                                 int x2 = c.xo() + c.width();
253                                 int y2 = c.yo() + c.descent();
254                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
255                         }
256                 }
257         }
258 }
259
260
261 void MathNestInset::validate(LaTeXFeatures & features) const
262 {
263         for (idx_type i = 0; i < nargs(); ++i)
264                 cell(i).validate(features);
265 }
266
267
268 void MathNestInset::replace(ReplaceData & rep)
269 {
270         for (idx_type i = 0; i < nargs(); ++i)
271                 cell(i).replace(rep);
272 }
273
274
275 bool MathNestInset::contains(MathArray const & ar) const
276 {
277         for (idx_type i = 0; i < nargs(); ++i)
278                 if (cell(i).contains(ar))
279                         return true;
280         return false;
281 }
282
283
284 bool MathNestInset::lock() const
285 {
286         return lock_;
287 }
288
289
290 void MathNestInset::lock(bool l)
291 {
292         lock_ = l;
293 }
294
295
296 bool MathNestInset::isActive() const
297 {
298         return nargs() > 0;
299 }
300
301
302 MathArray MathNestInset::glue() const
303 {
304         MathArray ar;
305         for (size_t i = 0; i < nargs(); ++i)
306                 ar.append(cell(i));
307         return ar;
308 }
309
310
311 void MathNestInset::write(WriteStream & os) const
312 {
313         os << '\\' << name().c_str();
314         for (size_t i = 0; i < nargs(); ++i)
315                 os << '{' << cell(i) << '}';
316         if (nargs() == 0)
317                 os.pendingSpace(true);
318         if (lock_ && !os.latex()) {
319                 os << "\\lyxlock";
320                 os.pendingSpace(true);
321         }
322 }
323
324
325 void MathNestInset::normalize(NormalStream & os) const
326 {
327         os << '[' << name().c_str();
328         for (size_t i = 0; i < nargs(); ++i)
329                 os << ' ' << cell(i);
330         os << ']';
331 }
332
333
334 int MathNestInset::latex(Buffer const &, std::ostream & os,
335                         OutputParams const & runparams) const
336 {
337         WriteStream wi(os, runparams.moving_arg, true);
338         write(wi);
339         return wi.line();
340 }
341
342
343 void MathNestInset::notifyCursorLeaves(LCursor & /*cur*/)
344 {
345 #ifdef WITH_WARNINGS
346 #warning look here
347 #endif
348 #if 0
349         MathArray & ar = cur.cell();
350         // remove base-only "scripts"
351         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
352                 MathScriptInset * p = operator[](i).nucleus()->asScriptInset();
353                 if (p && p->nargs() == 1) {
354                         MathArray ar = p->nuc();
355                         erase(i);
356                         insert(i, ar);
357                         cur.adjust(i, ar.size() - 1);
358                 }
359         }
360
361         // glue adjacent font insets of the same kind
362         for (pos_type i = 0; i + 1 < size(); ++i) {
363                 MathFontInset * p = operator[](i).nucleus()->asFontInset();
364                 MathFontInset const * q = operator[](i + 1)->asFontInset();
365                 if (p && q && p->name() == q->name()) {
366                         p->cell(0).append(q->cell(0));
367                         erase(i + 1);
368                         cur.adjust(i, -1);
369                 }
370         }
371 #endif
372 }
373
374
375 void MathNestInset::handleFont
376         (LCursor & cur, string const & arg, string const & font)
377 {
378         // this whole function is a hack and won't work for incremental font
379         // changes...
380         recordUndo(cur, Undo::ATOMIC);
381
382         if (cur.inset().asMathInset()->name() == font)
383                 cur.handleFont(font);
384         else {
385                 cur.handleNest(createMathInset(font));
386                 cur.insert(arg);
387         }
388 }
389
390
391 void MathNestInset::handleFont2(LCursor & cur, string const & arg)
392 {
393         recordUndo(cur, Undo::ATOMIC);
394         LyXFont font;
395         bool b;
396         bv_funcs::string2font(arg, font, b);
397         if (font.color() != LColor::inherit) {
398                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
399                 cur.handleNest(at, 0);
400         }
401 }
402
403
404 void MathNestInset::doDispatch(LCursor & cur, FuncRequest & cmd)
405 {
406         //lyxerr << "MathNestInset: request: " << cmd << std::endl;
407         //CursorSlice sl = cur.current();
408
409         switch (cmd.action) {
410
411         case LFUN_PASTE: {
412                 recordUndo(cur);
413                 cur.message(_("Paste"));
414                 replaceSelection(cur);
415                 size_t n = 0;
416                 istringstream is(cmd.argument);
417                 is >> n;
418                 pasteSelection(cur, n);
419                 cur.clearSelection(); // bug 393
420                 cur.bv().switchKeyMap();
421                 finishUndo();
422                 break;
423         }
424
425         case LFUN_CUT:
426                 cutSelection(cur, true, true);
427                 cur.message(_("Cut"));
428                 break;
429
430         case LFUN_COPY:
431                 copySelection(cur);
432                 cur.message(_("Copy"));
433                 break;
434
435         case LFUN_MOUSE_PRESS:
436                 lfunMousePress(cur, cmd);
437                 break;
438
439         case LFUN_MOUSE_MOTION:
440                 lfunMouseMotion(cur, cmd);
441                 break;
442
443         case LFUN_MOUSE_RELEASE:
444                 lfunMouseRelease(cur, cmd);
445                 break;
446
447         case LFUN_FINISHED_LEFT:
448                 cur.bv().cursor() = cur;
449                 break;
450
451         case LFUN_FINISHED_RIGHT:
452                 ++cur.pos();
453                 cur.bv().cursor() = cur;
454                 break;
455
456         case LFUN_FINISHED_UP:
457                 cur.bv().cursor() = cur;
458                 break;
459
460         case LFUN_FINISHED_DOWN:
461                 ++cur.pos();
462                 cur.bv().cursor() = cur;
463                 break;
464
465         case LFUN_RIGHTSEL:
466         case LFUN_RIGHT:
467                 cur.selHandle(cmd.action == LFUN_RIGHTSEL);
468                 cur.autocorrect() = false;
469                 cur.clearTargetX();
470                 cur.macroModeClose();
471                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
472                         cur.pushLeft(*cur.nextAtom().nucleus());
473                         cur.inset().idxFirst(cur);
474                 } else if (cur.posRight() || idxRight(cur)
475                         || cur.popRight() || cur.selection())
476                         ;
477                 else {
478                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
479                         cur.undispatched();
480                 }
481                 break;
482
483         case LFUN_LEFTSEL:
484         case LFUN_LEFT:
485                 cur.selHandle(cmd.action == LFUN_LEFTSEL);
486                 cur.autocorrect() = false;
487                 cur.clearTargetX();
488                 cur.macroModeClose();
489                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
490                         cur.posLeft();
491                         cur.push(*cur.nextAtom().nucleus());
492                         cur.inset().idxLast(cur);
493                 } else if (cur.posLeft() || idxLeft(cur)
494                         || cur.popLeft() || cur.selection())
495                         ;
496                 else {
497                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
498                         cur.undispatched();
499                 }
500                 break;
501
502         case LFUN_UPSEL:
503         case LFUN_UP:
504                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
505                 if (cur.inMacroMode()) {
506                         // Make Helge happy
507                         cur.macroModeClose();
508                         break;
509                 }
510                 cur.selHandle(cmd.action == LFUN_UPSEL);
511                 if (!cur.up()) {
512                         cmd = FuncRequest(LFUN_FINISHED_UP);
513                         cur.undispatched();
514                 }
515                 // fixes bug 1598. Please check!
516                 cur.normalize();
517                 break;
518
519         case LFUN_DOWNSEL:
520         case LFUN_DOWN:
521                 if (cur.inMacroMode()) {
522                         cur.macroModeClose();
523                         break;
524                 }
525                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
526                 if (!cur.down()) {
527                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
528                         cur.undispatched();
529                 }
530                 // fixes bug 1598. Please check!
531                 cur.normalize();
532                 break;
533
534         case LFUN_MOUSE_DOUBLE:
535         case LFUN_MOUSE_TRIPLE:
536         case LFUN_WORDSEL:
537                 cur.pos() = 0;
538                 cur.idx() = 0;
539                 cur.resetAnchor();
540                 cur.selection() = true;
541                 cur.pos() = cur.lastpos();
542                 cur.idx() = cur.lastidx();
543                 break;
544
545         case LFUN_UP_PARAGRAPHSEL:
546         case LFUN_UP_PARAGRAPH:
547         case LFUN_DOWN_PARAGRAPHSEL:
548         case LFUN_DOWN_PARAGRAPH:
549                 break;
550
551         case LFUN_HOMESEL:
552         case LFUN_HOME:
553         case LFUN_WORDLEFTSEL:
554         case LFUN_WORDLEFT:
555                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
556                 cur.macroModeClose();
557                 if (cur.pos() != 0) {
558                         cur.pos() = 0;
559                 } else if (cur.col() != 0) {
560                         cur.idx() -= cur.col();
561                         cur.pos() = 0;
562                 } else if (cur.idx() != 0) {
563                         cur.idx() = 0;
564                         cur.pos() = 0;
565                 } else {
566                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
567                         cur.undispatched();
568                 }
569                 break;
570
571         case LFUN_WORDRIGHTSEL:
572         case LFUN_WORDRIGHT:
573         case LFUN_ENDSEL:
574         case LFUN_END:
575                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
576                 cur.macroModeClose();
577                 cur.clearTargetX();
578                 if (cur.pos() != cur.lastpos()) {
579                         cur.pos() = cur.lastpos();
580                 } else if (ncols() && (cur.col() != cur.lastcol())) {
581                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
582                         cur.pos() = cur.lastpos();
583                 } else if (cur.idx() != cur.lastidx()) {
584                         cur.idx() = cur.lastidx();
585                         cur.pos() = cur.lastpos();
586                 } else {
587                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
588                         cur.undispatched();
589                 }
590                 break;
591
592         case LFUN_PRIORSEL:
593         case LFUN_PRIOR:
594                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
595                 cur.undispatched();
596                 break;
597
598         case LFUN_NEXTSEL:
599         case LFUN_NEXT:
600                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
601                 cur.undispatched();
602                 break;
603
604         case LFUN_CELL_FORWARD:
605                 cur.inset().idxNext(cur);
606                 break;
607
608         case LFUN_CELL_BACKWARD:
609                 cur.inset().idxPrev(cur);
610                 break;
611
612         case LFUN_DELETE_WORD_BACKWARD:
613         case LFUN_BACKSPACE:
614                 recordUndo(cur, Undo::ATOMIC);
615                 cur.backspace();
616                 break;
617
618         case LFUN_DELETE_WORD_FORWARD:
619         case LFUN_DELETE:
620                 recordUndo(cur);
621                 cur.erase();
622                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
623                 cur.undispatched();
624                 break;
625
626         case LFUN_ESCAPE:
627                 if (cur.selection())
628                         cur.clearSelection();
629                 else  {
630                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
631                         cur.undispatched();
632                 }
633                 break;
634
635         case LFUN_INSET_TOGGLE:
636                 recordUndo(cur);
637                 //lockToggle();
638                 if (cur.pos() != cur.lastpos()) {
639                         // toggle previous inset ...
640                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
641                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
642                         // ... or enclosing inset if we are in the last inset position
643                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
644                         ++cur.pos();
645                 }
646                 break;
647
648         case LFUN_SELFINSERT:
649                 recordUndo(cur);
650                 if (cmd.argument.size() != 1) {
651                         cur.insert(cmd.argument);
652                         break;
653                 }
654                 if (!interpret(cur, cmd.argument[0])) {
655                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
656                         cur.undispatched();
657                 }
658                 break;
659
660         //case LFUN_GETXY:
661         //      sprintf(dispatch_buffer, "%d %d",);
662         //      break;
663
664         case LFUN_SETXY: {
665                 lyxerr << "LFUN_SETXY broken!" << endl;
666                 int x = 0;
667                 int y = 0;
668                 istringstream is(cmd.argument);
669                 is >> x >> y;
670                 cur.setScreenPos(x, y);
671                 break;
672         }
673
674         // Special casing for superscript in case of LyX handling
675         // dead-keys:
676         case LFUN_CIRCUMFLEX:
677                 if (cmd.argument.empty()) {
678                         // do superscript if LyX handles
679                         // deadkeys
680                         recordUndo(cur, Undo::ATOMIC);
681                         script(cur, true);
682                 }
683                 break;
684
685         case LFUN_UMLAUT:
686         case LFUN_ACUTE:
687         case LFUN_GRAVE:
688         case LFUN_BREVE:
689         case LFUN_DOT:
690         case LFUN_MACRON:
691         case LFUN_CARON:
692         case LFUN_TILDE:
693         case LFUN_CEDILLA:
694         case LFUN_CIRCLE:
695         case LFUN_UNDERDOT:
696         case LFUN_TIE:
697         case LFUN_OGONEK:
698         case LFUN_HUNG_UMLAUT:
699                 break;
700
701         //  Math fonts
702         case LFUN_FREEFONT_APPLY:
703         case LFUN_FREEFONT_UPDATE:
704                 handleFont2(cur, cmd.argument);
705                 break;
706
707         case LFUN_BOLD:
708                 if (currentMode() == TEXT_MODE)
709                         handleFont(cur, cmd.argument, "textbf");
710                 else
711                         handleFont(cur, cmd.argument, "mathbf");
712                 break;
713         case LFUN_SANS:
714                 if (currentMode() == TEXT_MODE)
715                         handleFont(cur, cmd.argument, "textsf");
716                 else
717                         handleFont(cur, cmd.argument, "mathsf");
718                 break;
719         case LFUN_EMPH:
720                 if (currentMode() == TEXT_MODE)
721                         handleFont(cur, cmd.argument, "emph");
722                 else
723                         handleFont(cur, cmd.argument, "mathcal");
724                 break;
725         case LFUN_ROMAN:
726                 if (currentMode() == TEXT_MODE)
727                         handleFont(cur, cmd.argument, "textrm");
728                 else
729                         handleFont(cur, cmd.argument, "mathrm");
730                 break;
731         case LFUN_CODE:
732                 if (currentMode() == TEXT_MODE)
733                         handleFont(cur, cmd.argument, "texttt");
734                 else
735                         handleFont(cur, cmd.argument, "mathtt");
736                 break;
737         case LFUN_FRAK:
738                 handleFont(cur, cmd.argument, "mathfrak");
739                 break;
740         case LFUN_ITAL:
741                 if (currentMode() == TEXT_MODE)
742                         handleFont(cur, cmd.argument, "textit");
743                 else
744                         handleFont(cur, cmd.argument, "mathit");
745                 break;
746         case LFUN_NOUN:
747                 if (currentMode() == TEXT_MODE)
748                         // FIXME: should be "noun"
749                         handleFont(cur, cmd.argument, "textsc");
750                 else
751                         handleFont(cur, cmd.argument, "mathbb");
752                 break;
753         //case LFUN_FREEFONT_APPLY:
754                 handleFont(cur, cmd.argument, "textrm");
755                 break;
756         case LFUN_DEFAULT:
757                 handleFont(cur, cmd.argument, "textnormal");
758                 break;
759
760         case LFUN_MATH_MODE:
761 #if 1
762                 // ignore math-mode on when already in math mode
763                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
764                         break;
765                 cur.macroModeClose();
766                 selClearOrDel(cur);
767                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
768                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
769                 cur.posLeft();
770                 cur.pushLeft(*cur.nextInset());
771 #else
772                 if (currentMode() == InsetBase::TEXT_MODE) {
773                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
774                         cur.message(_("create new math text environment ($...$)"));
775                 } else {
776                         handleFont(cur, cmd.argument, "textrm");
777                         cur.message(_("entered math text mode (textrm)"));
778                 }
779 #endif
780                 break;
781
782         case LFUN_MATH_SIZE:
783 #if 0
784                 recordUndo(cur);
785                 cur.setSize(arg);
786 #endif
787                 break;
788
789         case LFUN_INSERT_MATRIX: {
790                 recordUndo(cur, Undo::ATOMIC);
791                 unsigned int m = 1;
792                 unsigned int n = 1;
793                 string v_align;
794                 string h_align;
795                 istringstream is(cmd.argument);
796                 is >> m >> n >> v_align >> h_align;
797                 if (m < 1)
798                         m = 1;
799                 if (n < 1)
800                         n = 1;
801                 v_align += 'c';
802                 cur.niceInsert(
803                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
804                 break;
805         }
806
807         case LFUN_MATH_DELIM: {
808                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
809                 string ls;
810                 string rs = lyx::support::split(cmd.argument, ls, ' ');
811                 // Reasonable default values
812                 if (ls.empty())
813                         ls = '(';
814                 if (rs.empty())
815                         rs = ')';
816                 recordUndo(cur, Undo::ATOMIC);
817                 cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
818                 break;
819         }
820
821         case LFUN_SPACE_INSERT:
822         case LFUN_MATH_SPACE:
823                 recordUndo(cur, Undo::ATOMIC);
824                 cur.insert(MathAtom(new MathSpaceInset(",")));
825                 break;
826
827         case LFUN_INSET_ERT:
828                 // interpret this as if a backslash was typed
829                 recordUndo(cur, Undo::ATOMIC);
830                 interpret(cur, '\\');
831                 break;
832
833         case LFUN_SUBSCRIPT:
834                 // interpret this as if a _ was typed
835                 recordUndo(cur, Undo::ATOMIC);
836                 interpret(cur, '_');
837                 break;
838
839         case LFUN_SUPERSCRIPT:
840                 // interpret this as if a ^ was typed
841                 recordUndo(cur, Undo::ATOMIC);
842                 interpret(cur, '^');
843                 break;
844
845 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
846 // handling such that "self-insert" works on "arbitrary stuff" too, and
847 // math-insert only handles special math things like "matrix".
848         case LFUN_INSERT_MATH: {
849                 recordUndo(cur, Undo::ATOMIC);
850                 MathArray ar;
851                 asArray(cmd.argument, ar);
852                 int cell(0);
853                 if (cmd.argument == "\\root")
854                         cell = 1;
855                 if (ar.size() == 1 && (ar[0].nucleus()->asNestInset())) {
856                         cur.handleNest(ar[0], cell);
857                 } else
858                         cur.niceInsert(cmd.argument);
859                 break;
860                 }
861
862         case LFUN_DIALOG_SHOW_NEW_INSET: {
863                 string const & name = cmd.argument;
864                 string data;
865 #if 0
866                 if (name == "ref") {
867                         RefInset tmp(name);
868                         data = tmp.createDialogStr(name);
869                 }
870 #endif
871                 cur.bv().owner()->getDialogs().show(name, data, 0);
872                 break;
873         }
874
875         case LFUN_INSET_APPLY: {
876                 string const name = cmd.getArg(0);
877                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
878
879                 if (base) {
880                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
881                         base->dispatch(cur, fr);
882                         break;
883                 }
884                 MathArray ar;
885                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
886                         cur.insert(ar);
887                         break;
888                 }
889                 cur.undispatched();
890                 break;
891         }
892
893         default:
894                 MathDimInset::doDispatch(cur, cmd);
895                 break;
896         }
897 }
898
899
900 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
901                 FuncStatus & flag) const
902 {
903         // the font related toggles
904         //string tc = "mathnormal";
905         bool ret = true;
906         string const arg = cmd.argument;
907         switch (cmd.action) {
908         case LFUN_TABULAR_FEATURE:
909                 flag.enabled(false);
910                 break;
911 #if 0
912         case LFUN_TABULAR_FEATURE:
913                 // FIXME: check temporarily disabled
914                 // valign code
915                 char align = mathcursor::valign();
916                 if (align == '\0') {
917                         enable = false;
918                         break;
919                 }
920                 if (cmd.argument.empty()) {
921                         flag.clear();
922                         break;
923                 }
924                 if (!contains("tcb", cmd.argument[0])) {
925                         enable = false;
926                         break;
927                 }
928                 flag.setOnOff(cmd.argument[0] == align);
929                 break;
930 #endif
931         /// We have to handle them since 1.4 blocks all unhandled actions
932         case LFUN_ITAL:
933         case LFUN_BOLD:
934         case LFUN_SANS:
935         case LFUN_EMPH:
936         case LFUN_CODE:
937         case LFUN_NOUN:
938         case LFUN_ROMAN:
939         case LFUN_DEFAULT:
940                 flag.enabled(true);
941                 break;
942         case LFUN_MATH_MUTATE:
943                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
944                 flag.setOnOff(false);
945                 break;
946
947         // we just need to be in math mode to enable that
948         case LFUN_MATH_SIZE:
949         case LFUN_MATH_SPACE:
950         case LFUN_MATH_LIMITS:
951         case LFUN_MATH_NONUMBER:
952         case LFUN_MATH_NUMBER:
953         case LFUN_MATH_EXTERN:
954                 flag.enabled(true);
955                 break;
956
957         case LFUN_FRAK:
958                 flag.enabled(currentMode() != TEXT_MODE);
959                 break;
960
961         case LFUN_INSERT_MATH: {
962                 bool const textarg =
963                         arg == "\\textbf"   || arg == "\\textsf" ||
964                         arg == "\\textrm"   || arg == "\\textmd" ||
965                         arg == "\\textit"   || arg == "\\textsc" ||
966                         arg == "\\textsl"   || arg == "\\textup" ||
967                         arg == "\\texttt"   || arg == "\\textbb" ||
968                         arg == "\\textnormal";
969                 flag.enabled(currentMode() != TEXT_MODE || textarg);
970                 break;
971         }
972
973         case LFUN_INSERT_MATRIX:
974                 flag.enabled(currentMode() == MATH_MODE);
975                 break;
976         default:
977                 ret = false;
978                 break;
979         }
980         return ret;
981 }
982
983
984 void MathNestInset::edit(LCursor & cur, bool left)
985 {
986         cur.push(*this);
987         cur.idx() = left ? 0 : cur.lastidx();
988         cur.pos() = left ? 0 : cur.lastpos();
989         cur.resetAnchor();
990         //lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
991 }
992
993
994 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y)
995 {
996         int idx_min = 0;
997         int dist_min = 1000000;
998         for (idx_type i = 0, n = nargs(); i != n; ++i) {
999                 int const d = cell(i).dist(x, y);
1000                 if (d < dist_min) {
1001                         dist_min = d;
1002                         idx_min = i;
1003                 }
1004         }
1005         MathArray & ar = cell(idx_min);
1006         cur.push(*this);
1007         cur.idx() = idx_min;
1008         cur.pos() = ar.x2pos(x - ar.xo());
1009         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1010         if (dist_min == 0) {
1011                 // hit inside cell
1012                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1013                         if (ar[i]->covers(x, y))
1014                                 return ar[i].nucleus()->editXY(cur, x, y);
1015         }
1016         return this;
1017 }
1018
1019
1020 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1021 {
1022         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1023         if (cmd.button() == mouse_button::button1) {
1024                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1025                 cur.resetAnchor();
1026                 cur.bv().cursor() = cur;
1027         }
1028
1029         if (cmd.button() == mouse_button::button2) {
1030                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
1031         }
1032 }
1033
1034
1035 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1036 {
1037         // only select with button 1
1038         if (cmd.button() == mouse_button::button1) {
1039                 LCursor & bvcur = cur.bv().cursor();
1040                 if (bvcur.anchor_.hasPart(cur)) {
1041                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1042                         bvcur.setCursor(cur);
1043                         bvcur.selection() = true;
1044                         //lyxerr << "MOTION " << bvcur << endl;
1045                 }
1046                 else {
1047                         cur.undispatched();
1048                 }
1049         }
1050 }
1051
1052
1053 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1054 {
1055         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1056
1057         if (cmd.button() == mouse_button::button1) {
1058                 //cur.bv().stuffClipboard(cur.grabSelection());
1059                 return;
1060         }
1061
1062         if (cmd.button() == mouse_button::button2) {
1063                 MathArray ar;
1064                 asArray(cur.bv().getClipboard(), ar);
1065                 cur.clearSelection();
1066                 cur.setScreenPos(cmd.x, cmd.y);
1067                 cur.insert(ar);
1068                 cur.bv().update();
1069                 return;
1070         }
1071
1072         if (cmd.button() == mouse_button::button3) {
1073                 // try to dispatch to enclosed insets first
1074                 cur.bv().owner()->getDialogs().show("mathpanel");
1075                 return;
1076         }
1077
1078         cur.undispatched();
1079 }
1080
1081
1082 bool MathNestInset::interpret(LCursor & cur, char c)
1083 {
1084         //lyxerr << "interpret 2: '" << c << "'" << endl;
1085         cur.clearTargetX();
1086
1087         // handle macroMode
1088         if (cur.inMacroMode()) {
1089                 string name = cur.macroName();
1090
1091                 /// are we currently typing '#1' or '#2' or...?
1092                 if (name == "\\#") {
1093                         cur.backspace();
1094                         int n = c - '0';
1095                         if (n >= 1 && n <= 9)
1096                                 cur.insert(new MathMacroArgument(n));
1097                         return true;
1098                 }
1099
1100                 if (isalpha(c)) {
1101                         cur.activeMacro()->setName(name + c);
1102                         return true;
1103                 }
1104
1105                 // handle 'special char' macros
1106                 if (name == "\\") {
1107                         // remove the '\\'
1108                         if (c == '\\') {
1109                                 cur.backspace();
1110                                 if (currentMode() == MathInset::TEXT_MODE)
1111                                         cur.niceInsert(createMathInset("textbackslash"));
1112                                 else
1113                                         cur.niceInsert(createMathInset("backslash"));
1114                         } else if (c == '{') {
1115                                 cur.backspace();
1116                                 cur.niceInsert(MathAtom(new MathBraceInset));
1117                         } else if (c == '%') {
1118                                 cur.backspace();
1119                                 cur.niceInsert(MathAtom(new MathCommentInset));
1120                         } else if (c == '#') {
1121                                 BOOST_ASSERT(cur.activeMacro());
1122                                 cur.activeMacro()->setName(name + c);
1123                         } else {
1124                                 cur.backspace();
1125                                 cur.niceInsert(createMathInset(string(1, c)));
1126                         }
1127                         return true;
1128                 }
1129
1130                 // leave macro mode and try again if necessary
1131                 cur.macroModeClose();
1132                 if (c == '{')
1133                         cur.niceInsert(MathAtom(new MathBraceInset));
1134                 else if (c != ' ')
1135                         interpret(cur, c);
1136                 return true;
1137         }
1138
1139         // This is annoying as one has to press <space> far too often.
1140         // Disable it.
1141
1142 #if 0
1143                 // leave autocorrect mode if necessary
1144                 if (autocorrect() && c == ' ') {
1145                         autocorrect() = false;
1146                         return true;
1147                 }
1148 #endif
1149
1150         // just clear selection on pressing the space bar
1151         if (cur.selection() && c == ' ') {
1152                 cur.selection() = false;
1153                 return true;
1154         }
1155
1156         selClearOrDel(cur);
1157
1158         if (c == '\\') {
1159                 //lyxerr << "starting with macro" << endl;
1160                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1161                 return true;
1162         }
1163
1164         if (c == '\n') {
1165                 if (currentMode() == MathInset::TEXT_MODE)
1166                         cur.insert(c);
1167                 return true;
1168         }
1169
1170         if (c == ' ') {
1171                 if (currentMode() == MathInset::TEXT_MODE) {
1172                         // insert spaces in text mode,
1173                         // but suppress direct insertion of two spaces in a row
1174                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1175                         // it is better than nothing...
1176                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1177                                 cur.insert(c);
1178                         return true;
1179                 }
1180                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1181                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1182                         return true;
1183                 }
1184                 if (cur.popRight())
1185                         return true;
1186                 // if are at the very end, leave the formula
1187                 return cur.pos() != cur.lastpos();
1188         }
1189
1190         // These shouldn't work in text mode:
1191         if (currentMode() != MathInset::TEXT_MODE) {
1192                 if (c == '_') {
1193                         script(cur, false);
1194                         return true;
1195                 }
1196                 if (c == '^') {
1197                         script(cur, true);
1198                         return true;
1199                 }
1200                 if (c == '~') {
1201                         cur.niceInsert(createMathInset("sim"));
1202                         return true;
1203                 }
1204         }
1205
1206         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%'
1207       || c == '_' || c == '^') {
1208                 cur.niceInsert(createMathInset(string(1, c)));
1209                 return true;
1210         }
1211
1212
1213         // try auto-correction
1214         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1215         //      return true;
1216
1217         // no special circumstances, so insert the character without any fuss
1218         cur.insert(c);
1219         cur.autocorrect() = true;
1220         return true;
1221 }
1222
1223
1224 bool MathNestInset::script(LCursor & cur, bool up)
1225 {
1226         // Hack to get \^ and \_ working
1227         lyxerr << "handling script: up: " << up << endl;
1228         if (cur.inMacroMode() && cur.macroName() == "\\") {
1229                 if (up)
1230                         cur.niceInsert(createMathInset("mathcircumflex"));
1231                 else
1232                         interpret(cur, '_');
1233                 return true;
1234         }
1235
1236         cur.macroModeClose();
1237         string safe = grabAndEraseSelection(cur);
1238         if (asScriptInset() && cur.idx() == 0) {
1239                 // we are in a nucleus of a script inset, move to _our_ script
1240                 MathScriptInset * inset = asScriptInset();
1241                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1242                 inset->ensure(up);
1243                 cur.idx() = inset->idxOfScript(up);
1244                 cur.pos() = 0;
1245         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1246                 --cur.pos();
1247                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1248                 cur.push(*inset);
1249                 cur.idx() = inset->idxOfScript(up);
1250                 cur.pos() = cur.lastpos();
1251         } else {
1252                 // convert the thing to our left to a scriptinset or create a new
1253                 // one if in the very first position of the array
1254                 if (cur.pos() == 0) {
1255                         //lyxerr << "new scriptinset" << endl;
1256                         cur.insert(new MathScriptInset(up));
1257                 } else {
1258                         //lyxerr << "converting prev atom " << endl;
1259                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1260                 }
1261                 --cur.pos();
1262                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1263                 cur.push(*inset);
1264                 cur.idx() = 1;
1265                 cur.pos() = 0;
1266         }
1267         //lyxerr << "pasting 1: safe:\n" << safe << endl;
1268         cur.paste(safe);
1269         cur.resetAnchor();
1270         //lyxerr << "pasting 2: safe:\n" << safe << endl;
1271         return true;
1272 }