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