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