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