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