]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
fix bug 2060
[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                 recordUndo(cur);
427                 cutSelection(cur, true, true);
428                 cur.message(_("Cut"));
429                 // Prevent stale position >= size crash
430                 cur.normalize();
431                 break;
432
433         case LFUN_COPY:
434                 copySelection(cur);
435                 cur.message(_("Copy"));
436                 break;
437
438         case LFUN_MOUSE_PRESS:
439                 lfunMousePress(cur, cmd);
440                 break;
441
442         case LFUN_MOUSE_MOTION:
443                 lfunMouseMotion(cur, cmd);
444                 break;
445
446         case LFUN_MOUSE_RELEASE:
447                 lfunMouseRelease(cur, cmd);
448                 break;
449
450         case LFUN_FINISHED_LEFT:
451                 cur.bv().cursor() = cur;
452                 break;
453
454         case LFUN_FINISHED_RIGHT:
455                 ++cur.pos();
456                 cur.bv().cursor() = cur;
457                 break;
458
459         case LFUN_FINISHED_UP:
460                 cur.bv().cursor() = cur;
461                 break;
462
463         case LFUN_FINISHED_DOWN:
464                 ++cur.pos();
465                 cur.bv().cursor() = cur;
466                 break;
467
468         case LFUN_RIGHTSEL:
469         case LFUN_RIGHT:
470                 cur.selHandle(cmd.action == LFUN_RIGHTSEL);
471                 cur.autocorrect() = false;
472                 cur.clearTargetX();
473                 cur.macroModeClose();
474                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
475                         cur.pushLeft(*cur.nextAtom().nucleus());
476                         cur.inset().idxFirst(cur);
477                 } else if (cur.posRight() || idxRight(cur)
478                         || cur.popRight() || cur.selection())
479                         ;
480                 else {
481                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
482                         cur.undispatched();
483                 }
484                 break;
485
486         case LFUN_LEFTSEL:
487         case LFUN_LEFT:
488                 cur.selHandle(cmd.action == LFUN_LEFTSEL);
489                 cur.autocorrect() = false;
490                 cur.clearTargetX();
491                 cur.macroModeClose();
492                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
493                         cur.posLeft();
494                         cur.push(*cur.nextAtom().nucleus());
495                         cur.inset().idxLast(cur);
496                 } else if (cur.posLeft() || idxLeft(cur)
497                         || cur.popLeft() || cur.selection())
498                         ;
499                 else {
500                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
501                         cur.undispatched();
502                 }
503                 break;
504
505         case LFUN_UPSEL:
506         case LFUN_UP:
507                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
508                 if (cur.inMacroMode()) {
509                         // Make Helge happy
510                         cur.macroModeClose();
511                         break;
512                 }
513                 cur.selHandle(cmd.action == LFUN_UPSEL);
514                 if (!cur.up()) {
515                         cmd = FuncRequest(LFUN_FINISHED_UP);
516                         cur.undispatched();
517                 }
518                 // fixes bug 1598. Please check!
519                 cur.normalize();
520                 break;
521
522         case LFUN_DOWNSEL:
523         case LFUN_DOWN:
524                 if (cur.inMacroMode()) {
525                         cur.macroModeClose();
526                         break;
527                 }
528                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
529                 if (!cur.down()) {
530                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
531                         cur.undispatched();
532                 }
533                 // fixes bug 1598. Please check!
534                 cur.normalize();
535                 break;
536
537         case LFUN_MOUSE_DOUBLE:
538         case LFUN_MOUSE_TRIPLE:
539         case LFUN_WORDSEL:
540                 cur.pos() = 0;
541                 cur.idx() = 0;
542                 cur.resetAnchor();
543                 cur.selection() = true;
544                 cur.pos() = cur.lastpos();
545                 cur.idx() = cur.lastidx();
546                 break;
547
548         case LFUN_UP_PARAGRAPHSEL:
549         case LFUN_UP_PARAGRAPH:
550         case LFUN_DOWN_PARAGRAPHSEL:
551         case LFUN_DOWN_PARAGRAPH:
552                 break;
553
554         case LFUN_HOMESEL:
555         case LFUN_HOME:
556         case LFUN_WORDLEFTSEL:
557         case LFUN_WORDLEFT:
558                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
559                 cur.macroModeClose();
560                 if (cur.pos() != 0) {
561                         cur.pos() = 0;
562                 } else if (cur.col() != 0) {
563                         cur.idx() -= cur.col();
564                         cur.pos() = 0;
565                 } else if (cur.idx() != 0) {
566                         cur.idx() = 0;
567                         cur.pos() = 0;
568                 } else {
569                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
570                         cur.undispatched();
571                 }
572                 break;
573
574         case LFUN_WORDRIGHTSEL:
575         case LFUN_WORDRIGHT:
576         case LFUN_ENDSEL:
577         case LFUN_END:
578                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
579                 cur.macroModeClose();
580                 cur.clearTargetX();
581                 if (cur.pos() != cur.lastpos()) {
582                         cur.pos() = cur.lastpos();
583                 } else if (ncols() && (cur.col() != cur.lastcol())) {
584                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
585                         cur.pos() = cur.lastpos();
586                 } else if (cur.idx() != cur.lastidx()) {
587                         cur.idx() = cur.lastidx();
588                         cur.pos() = cur.lastpos();
589                 } else {
590                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
591                         cur.undispatched();
592                 }
593                 break;
594
595         case LFUN_PRIORSEL:
596         case LFUN_PRIOR:
597                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
598                 cur.undispatched();
599                 break;
600
601         case LFUN_NEXTSEL:
602         case LFUN_NEXT:
603                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
604                 cur.undispatched();
605                 break;
606
607         case LFUN_CELL_FORWARD:
608                 cur.inset().idxNext(cur);
609                 break;
610
611         case LFUN_CELL_BACKWARD:
612                 cur.inset().idxPrev(cur);
613                 break;
614
615         case LFUN_DELETE_WORD_BACKWARD:
616         case LFUN_BACKSPACE:
617                 if (cur.pos() == 0)
618                         // delete whole cell
619                         recordUndoInset(cur, Undo::ATOMIC);
620                 else
621                         recordUndo(cur, Undo::ATOMIC);
622                 cur.backspace();
623                 break;
624
625         case LFUN_DELETE_WORD_FORWARD:
626         case LFUN_DELETE:
627                 recordUndo(cur);
628                 cur.erase();
629                 break;
630
631         case LFUN_ESCAPE:
632                 if (cur.selection())
633                         cur.clearSelection();
634                 else  {
635                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
636                         cur.undispatched();
637                 }
638                 break;
639
640         case LFUN_INSET_TOGGLE:
641                 recordUndo(cur);
642                 //lockToggle();
643                 if (cur.pos() != cur.lastpos()) {
644                         // toggle previous inset ...
645                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
646                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
647                         // ... or enclosing inset if we are in the last inset position
648                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
649                         ++cur.pos();
650                 }
651                 break;
652
653         case LFUN_SELFINSERT:
654                 recordUndo(cur);
655                 if (cmd.argument.size() != 1) {
656                         cur.insert(cmd.argument);
657                         break;
658                 }
659                 if (!interpret(cur, cmd.argument[0])) {
660                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
661                         cur.undispatched();
662                 }
663                 break;
664
665         //case LFUN_GETXY:
666         //      sprintf(dispatch_buffer, "%d %d",);
667         //      break;
668
669         case LFUN_SETXY: {
670                 lyxerr << "LFUN_SETXY broken!" << endl;
671                 int x = 0;
672                 int y = 0;
673                 istringstream is(cmd.argument);
674                 is >> x >> y;
675                 cur.setScreenPos(x, y);
676                 break;
677         }
678
679         // Special casing for superscript in case of LyX handling
680         // dead-keys:
681         case LFUN_CIRCUMFLEX:
682                 if (cmd.argument.empty()) {
683                         // do superscript if LyX handles
684                         // deadkeys
685                         recordUndo(cur, Undo::ATOMIC);
686                         script(cur, true);
687                 }
688                 break;
689
690         case LFUN_UMLAUT:
691         case LFUN_ACUTE:
692         case LFUN_GRAVE:
693         case LFUN_BREVE:
694         case LFUN_DOT:
695         case LFUN_MACRON:
696         case LFUN_CARON:
697         case LFUN_TILDE:
698         case LFUN_CEDILLA:
699         case LFUN_CIRCLE:
700         case LFUN_UNDERDOT:
701         case LFUN_TIE:
702         case LFUN_OGONEK:
703         case LFUN_HUNG_UMLAUT:
704                 break;
705
706         //  Math fonts
707         case LFUN_FREEFONT_APPLY:
708         case LFUN_FREEFONT_UPDATE:
709                 handleFont2(cur, cmd.argument);
710                 break;
711
712         case LFUN_BOLD:
713                 if (currentMode() == TEXT_MODE)
714                         handleFont(cur, cmd.argument, "textbf");
715                 else
716                         handleFont(cur, cmd.argument, "mathbf");
717                 break;
718         case LFUN_SANS:
719                 if (currentMode() == TEXT_MODE)
720                         handleFont(cur, cmd.argument, "textsf");
721                 else
722                         handleFont(cur, cmd.argument, "mathsf");
723                 break;
724         case LFUN_EMPH:
725                 if (currentMode() == TEXT_MODE)
726                         handleFont(cur, cmd.argument, "emph");
727                 else
728                         handleFont(cur, cmd.argument, "mathcal");
729                 break;
730         case LFUN_ROMAN:
731                 if (currentMode() == TEXT_MODE)
732                         handleFont(cur, cmd.argument, "textrm");
733                 else
734                         handleFont(cur, cmd.argument, "mathrm");
735                 break;
736         case LFUN_CODE:
737                 if (currentMode() == TEXT_MODE)
738                         handleFont(cur, cmd.argument, "texttt");
739                 else
740                         handleFont(cur, cmd.argument, "mathtt");
741                 break;
742         case LFUN_FRAK:
743                 handleFont(cur, cmd.argument, "mathfrak");
744                 break;
745         case LFUN_ITAL:
746                 if (currentMode() == TEXT_MODE)
747                         handleFont(cur, cmd.argument, "textit");
748                 else
749                         handleFont(cur, cmd.argument, "mathit");
750                 break;
751         case LFUN_NOUN:
752                 if (currentMode() == TEXT_MODE)
753                         // FIXME: should be "noun"
754                         handleFont(cur, cmd.argument, "textsc");
755                 else
756                         handleFont(cur, cmd.argument, "mathbb");
757                 break;
758         //case LFUN_FREEFONT_APPLY:
759                 handleFont(cur, cmd.argument, "textrm");
760                 break;
761         case LFUN_DEFAULT:
762                 handleFont(cur, cmd.argument, "textnormal");
763                 break;
764
765         case LFUN_MATH_MODE:
766 #if 1
767                 // ignore math-mode on when already in math mode
768                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
769                         break;
770                 cur.macroModeClose();
771                 selClearOrDel(cur);
772                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
773                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
774                 cur.posLeft();
775                 cur.pushLeft(*cur.nextInset());
776 #else
777                 if (currentMode() == InsetBase::TEXT_MODE) {
778                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
779                         cur.message(_("create new math text environment ($...$)"));
780                 } else {
781                         handleFont(cur, cmd.argument, "textrm");
782                         cur.message(_("entered math text mode (textrm)"));
783                 }
784 #endif
785                 break;
786
787         case LFUN_MATH_SIZE:
788 #if 0
789                 recordUndo(cur);
790                 cur.setSize(arg);
791 #endif
792                 break;
793
794         case LFUN_INSERT_MATRIX: {
795                 recordUndo(cur, Undo::ATOMIC);
796                 unsigned int m = 1;
797                 unsigned int n = 1;
798                 string v_align;
799                 string h_align;
800                 istringstream is(cmd.argument);
801                 is >> m >> n >> v_align >> h_align;
802                 if (m < 1)
803                         m = 1;
804                 if (n < 1)
805                         n = 1;
806                 v_align += 'c';
807                 cur.niceInsert(
808                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
809                 break;
810         }
811
812         case LFUN_MATH_DELIM: {
813                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
814                 string ls;
815                 string rs = lyx::support::split(cmd.argument, ls, ' ');
816                 // Reasonable default values
817                 if (ls.empty())
818                         ls = '(';
819                 if (rs.empty())
820                         rs = ')';
821                 recordUndo(cur, Undo::ATOMIC);
822                 // Don't do this with multi-cell selections
823                 if (cur.selBegin().idx() == cur.selEnd().idx())
824                         cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
825                 break;
826         }
827
828         case LFUN_SPACE_INSERT:
829         case LFUN_MATH_SPACE:
830                 recordUndo(cur, Undo::ATOMIC);
831                 cur.insert(MathAtom(new MathSpaceInset(",")));
832                 break;
833
834         case LFUN_INSET_ERT:
835                 // interpret this as if a backslash was typed
836                 recordUndo(cur, Undo::ATOMIC);
837                 interpret(cur, '\\');
838                 break;
839
840         case LFUN_SUBSCRIPT:
841                 // interpret this as if a _ was typed
842                 recordUndo(cur, Undo::ATOMIC);
843                 interpret(cur, '_');
844                 break;
845
846         case LFUN_SUPERSCRIPT:
847                 // interpret this as if a ^ was typed
848                 recordUndo(cur, Undo::ATOMIC);
849                 interpret(cur, '^');
850                 break;
851
852 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
853 // handling such that "self-insert" works on "arbitrary stuff" too, and
854 // math-insert only handles special math things like "matrix".
855         case LFUN_INSERT_MATH: {
856                 recordUndo(cur, Undo::ATOMIC);
857                 MathArray ar;
858                 asArray(cmd.argument, ar);
859                 int cell(0);
860                 if (cmd.argument == "\\root")
861                         cell = 1;
862                 // math macros are nest insets and may have 0 cells.
863                 // handleNest would crash in this case.
864                 if (ar.size() == 1 && (ar[0].nucleus()->asNestInset()) &&
865                     ar[0].nucleus()->nargs() > cell) {
866                         cur.handleNest(ar[0], cell);
867                 } else
868                         cur.niceInsert(cmd.argument);
869                 break;
870                 }
871
872         case LFUN_DIALOG_SHOW_NEW_INSET: {
873                 string const & name = cmd.argument;
874                 string data;
875 #if 0
876                 if (name == "ref") {
877                         RefInset tmp(name);
878                         data = tmp.createDialogStr(name);
879                 }
880 #endif
881                 cur.bv().owner()->getDialogs().show(name, data, 0);
882                 break;
883         }
884
885         case LFUN_INSET_APPLY: {
886                 string const name = cmd.getArg(0);
887                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
888
889                 if (base) {
890                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
891                         base->dispatch(cur, fr);
892                         break;
893                 }
894                 MathArray ar;
895                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
896                         cur.insert(ar);
897                         break;
898                 }
899                 cur.undispatched();
900                 break;
901         }
902
903         default:
904                 MathDimInset::doDispatch(cur, cmd);
905                 break;
906         }
907 }
908
909
910 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
911                 FuncStatus & flag) const
912 {
913         // the font related toggles
914         //string tc = "mathnormal";
915         bool ret = true;
916         string const arg = cmd.argument;
917         switch (cmd.action) {
918         case LFUN_TABULAR_FEATURE:
919                 flag.enabled(false);
920                 break;
921 #if 0
922         case LFUN_TABULAR_FEATURE:
923                 // FIXME: check temporarily disabled
924                 // valign code
925                 char align = mathcursor::valign();
926                 if (align == '\0') {
927                         enable = false;
928                         break;
929                 }
930                 if (cmd.argument.empty()) {
931                         flag.clear();
932                         break;
933                 }
934                 if (!contains("tcb", cmd.argument[0])) {
935                         enable = false;
936                         break;
937                 }
938                 flag.setOnOff(cmd.argument[0] == align);
939                 break;
940 #endif
941         /// We have to handle them since 1.4 blocks all unhandled actions
942         case LFUN_ITAL:
943         case LFUN_BOLD:
944         case LFUN_SANS:
945         case LFUN_EMPH:
946         case LFUN_CODE:
947         case LFUN_NOUN:
948         case LFUN_ROMAN:
949         case LFUN_DEFAULT:
950                 flag.enabled(true);
951                 break;
952         case LFUN_MATH_MUTATE:
953                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
954                 flag.setOnOff(false);
955                 break;
956
957         // we just need to be in math mode to enable that
958         case LFUN_MATH_SIZE:
959         case LFUN_MATH_SPACE:
960         case LFUN_MATH_LIMITS:
961         case LFUN_MATH_NONUMBER:
962         case LFUN_MATH_NUMBER:
963         case LFUN_MATH_EXTERN:
964                 flag.enabled(true);
965                 break;
966
967         case LFUN_FRAK:
968                 flag.enabled(currentMode() != TEXT_MODE);
969                 break;
970
971         case LFUN_INSERT_MATH: {
972                 bool const textarg =
973                         arg == "\\textbf"   || arg == "\\textsf" ||
974                         arg == "\\textrm"   || arg == "\\textmd" ||
975                         arg == "\\textit"   || arg == "\\textsc" ||
976                         arg == "\\textsl"   || arg == "\\textup" ||
977                         arg == "\\texttt"   || arg == "\\textbb" ||
978                         arg == "\\textnormal";
979                 flag.enabled(currentMode() != TEXT_MODE || textarg);
980                 break;
981         }
982
983         case LFUN_INSERT_MATRIX:
984                 flag.enabled(currentMode() == MATH_MODE);
985                 break;
986         default:
987                 ret = false;
988                 break;
989         }
990         return ret;
991 }
992
993
994 void MathNestInset::edit(LCursor & cur, bool left)
995 {
996         cur.push(*this);
997         cur.idx() = left ? 0 : cur.lastidx();
998         cur.pos() = left ? 0 : cur.lastpos();
999         cur.resetAnchor();
1000         //lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
1001 }
1002
1003
1004 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y)
1005 {
1006         int idx_min = 0;
1007         int dist_min = 1000000;
1008         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1009                 int const d = cell(i).dist(x, y);
1010                 if (d < dist_min) {
1011                         dist_min = d;
1012                         idx_min = i;
1013                 }
1014         }
1015         MathArray & ar = cell(idx_min);
1016         cur.push(*this);
1017         cur.idx() = idx_min;
1018         cur.pos() = ar.x2pos(x - ar.xo());
1019         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1020         if (dist_min == 0) {
1021                 // hit inside cell
1022                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1023                         if (ar[i]->covers(x, y))
1024                                 return ar[i].nucleus()->editXY(cur, x, y);
1025         }
1026         return this;
1027 }
1028
1029
1030 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1031 {
1032         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1033         if (cmd.button() == mouse_button::button1) {
1034                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1035                 cur.resetAnchor();
1036                 cur.bv().cursor() = cur;
1037         }
1038
1039         if (cmd.button() == mouse_button::button2) {
1040                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
1041         }
1042 }
1043
1044
1045 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1046 {
1047         // only select with button 1
1048         if (cmd.button() == mouse_button::button1) {
1049                 LCursor & bvcur = cur.bv().cursor();
1050                 if (bvcur.anchor_.hasPart(cur)) {
1051                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1052                         bvcur.setCursor(cur);
1053                         bvcur.selection() = true;
1054                         //lyxerr << "MOTION " << bvcur << endl;
1055                 }
1056                 else {
1057                         cur.undispatched();
1058                 }
1059         }
1060 }
1061
1062
1063 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1064 {
1065         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1066
1067         if (cmd.button() == mouse_button::button1) {
1068                 //cur.bv().stuffClipboard(cur.grabSelection());
1069                 return;
1070         }
1071
1072         if (cmd.button() == mouse_button::button2) {
1073                 MathArray ar;
1074                 asArray(cur.bv().getClipboard(), ar);
1075                 cur.clearSelection();
1076                 cur.setScreenPos(cmd.x, cmd.y);
1077                 cur.insert(ar);
1078                 cur.bv().update();
1079                 return;
1080         }
1081
1082         if (cmd.button() == mouse_button::button3) {
1083                 // try to dispatch to enclosed insets first
1084                 cur.bv().owner()->getDialogs().show("mathpanel");
1085                 return;
1086         }
1087
1088         cur.undispatched();
1089 }
1090
1091
1092 bool MathNestInset::interpret(LCursor & cur, char c)
1093 {
1094         //lyxerr << "interpret 2: '" << c << "'" << endl;
1095         cur.clearTargetX();
1096
1097         // handle macroMode
1098         if (cur.inMacroMode()) {
1099                 string name = cur.macroName();
1100
1101                 /// are we currently typing '#1' or '#2' or...?
1102                 if (name == "\\#") {
1103                         cur.backspace();
1104                         int n = c - '0';
1105                         if (n >= 1 && n <= 9)
1106                                 cur.insert(new MathMacroArgument(n));
1107                         return true;
1108                 }
1109
1110                 if (isalpha(c)) {
1111                         cur.activeMacro()->setName(name + c);
1112                         return true;
1113                 }
1114
1115                 // handle 'special char' macros
1116                 if (name == "\\") {
1117                         // remove the '\\'
1118                         if (c == '\\') {
1119                                 cur.backspace();
1120                                 if (currentMode() == MathInset::TEXT_MODE)
1121                                         cur.niceInsert(createMathInset("textbackslash"));
1122                                 else
1123                                         cur.niceInsert(createMathInset("backslash"));
1124                         } else if (c == '{') {
1125                                 cur.backspace();
1126                                 cur.niceInsert(MathAtom(new MathBraceInset));
1127                         } else if (c == '%') {
1128                                 cur.backspace();
1129                                 cur.niceInsert(MathAtom(new MathCommentInset));
1130                         } else if (c == '#') {
1131                                 BOOST_ASSERT(cur.activeMacro());
1132                                 cur.activeMacro()->setName(name + c);
1133                         } else {
1134                                 cur.backspace();
1135                                 cur.niceInsert(createMathInset(string(1, c)));
1136                         }
1137                         return true;
1138                 }
1139
1140                 // leave macro mode and try again if necessary
1141                 cur.macroModeClose();
1142                 if (c == '{')
1143                         cur.niceInsert(MathAtom(new MathBraceInset));
1144                 else if (c != ' ')
1145                         interpret(cur, c);
1146                 return true;
1147         }
1148
1149         // This is annoying as one has to press <space> far too often.
1150         // Disable it.
1151
1152 #if 0
1153                 // leave autocorrect mode if necessary
1154                 if (autocorrect() && c == ' ') {
1155                         autocorrect() = false;
1156                         return true;
1157                 }
1158 #endif
1159
1160         // just clear selection on pressing the space bar
1161         if (cur.selection() && c == ' ') {
1162                 cur.selection() = false;
1163                 return true;
1164         }
1165
1166         selClearOrDel(cur);
1167
1168         if (c == '\\') {
1169                 //lyxerr << "starting with macro" << endl;
1170                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1171                 return true;
1172         }
1173
1174         if (c == '\n') {
1175                 if (currentMode() == MathInset::TEXT_MODE)
1176                         cur.insert(c);
1177                 return true;
1178         }
1179
1180         if (c == ' ') {
1181                 if (currentMode() == MathInset::TEXT_MODE) {
1182                         // insert spaces in text mode,
1183                         // but suppress direct insertion of two spaces in a row
1184                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1185                         // it is better than nothing...
1186                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1187                                 cur.insert(c);
1188                         return true;
1189                 }
1190                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1191                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1192                         return true;
1193                 }
1194                 if (cur.popRight())
1195                         return true;
1196                 // if are at the very end, leave the formula
1197                 return cur.pos() != cur.lastpos();
1198         }
1199
1200         // These shouldn't work in text mode:
1201         if (currentMode() != MathInset::TEXT_MODE) {
1202                 if (c == '_') {
1203                         script(cur, false);
1204                         return true;
1205                 }
1206                 if (c == '^') {
1207                         script(cur, true);
1208                         return true;
1209                 }
1210                 if (c == '~') {
1211                         cur.niceInsert(createMathInset("sim"));
1212                         return true;
1213                 }
1214         }
1215
1216         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%'
1217       || c == '_' || c == '^') {
1218                 cur.niceInsert(createMathInset(string(1, c)));
1219                 return true;
1220         }
1221
1222
1223         // try auto-correction
1224         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1225         //      return true;
1226
1227         // no special circumstances, so insert the character without any fuss
1228         cur.insert(c);
1229         cur.autocorrect() = true;
1230         return true;
1231 }
1232
1233
1234 bool MathNestInset::script(LCursor & cur, bool up)
1235 {
1236         // Hack to get \^ and \_ working
1237         lyxerr << "handling script: up: " << up << endl;
1238         if (cur.inMacroMode() && cur.macroName() == "\\") {
1239                 if (up)
1240                         cur.niceInsert(createMathInset("mathcircumflex"));
1241                 else
1242                         interpret(cur, '_');
1243                 return true;
1244         }
1245
1246         cur.macroModeClose();
1247         string safe = grabAndEraseSelection(cur);
1248         if (asScriptInset() && cur.idx() == 0) {
1249                 // we are in a nucleus of a script inset, move to _our_ script
1250                 MathScriptInset * inset = asScriptInset();
1251                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1252                 inset->ensure(up);
1253                 cur.idx() = inset->idxOfScript(up);
1254                 cur.pos() = 0;
1255         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1256                 --cur.pos();
1257                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1258                 cur.push(*inset);
1259                 cur.idx() = inset->idxOfScript(up);
1260                 cur.pos() = cur.lastpos();
1261         } else {
1262                 // convert the thing to our left to a scriptinset or create a new
1263                 // one if in the very first position of the array
1264                 if (cur.pos() == 0) {
1265                         //lyxerr << "new scriptinset" << endl;
1266                         cur.insert(new MathScriptInset(up));
1267                 } else {
1268                         //lyxerr << "converting prev atom " << endl;
1269                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1270                 }
1271                 --cur.pos();
1272                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1273                 cur.push(*inset);
1274                 cur.idx() = 1;
1275                 cur.pos() = 0;
1276         }
1277         //lyxerr << "pasting 1: safe:\n" << safe << endl;
1278         cur.paste(safe);
1279         cur.resetAnchor();
1280         //lyxerr << "pasting 2: safe:\n" << safe << endl;
1281         return true;
1282 }