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