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