]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.C
* InsetMathNest.C (handleFont): avoid crash on undo when
[features.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
405         if (cur.inset().asInsetMath()->name() == font) {
406                 recordUndoInset(cur, Undo::ATOMIC);
407                 cur.handleFont(to_utf8(font));
408         } else {
409                 recordUndo(cur, Undo::ATOMIC);
410                 cur.handleNest(createInsetMath(font));
411                 cur.insert(arg);
412         }
413 }
414
415
416 void InsetMathNest::handleFont2(LCursor & cur, docstring const & arg)
417 {
418         recordUndo(cur, Undo::ATOMIC);
419         LyXFont font;
420         bool b;
421         bv_funcs::string2font(to_utf8(arg), font, b);
422         if (font.color() != LColor::inherit) {
423                 MathAtom at = MathAtom(new InsetMathColor(true, font.color()));
424                 cur.handleNest(at, 0);
425         }
426 }
427
428
429 void InsetMathNest::doDispatch(LCursor & cur, FuncRequest & cmd)
430 {
431         //lyxerr << "InsetMathNest: request: " << cmd << std::endl;
432         //CursorSlice sl = cur.current();
433
434         switch (cmd.action) {
435
436         case LFUN_PASTE: {
437                 recordUndo(cur);
438                 cur.message(_("Paste"));
439                 replaceSelection(cur);
440                 size_t n = 0;
441                 istringstream is(to_utf8(cmd.argument()));
442                 is >> n;
443                 docstring const selection = cap::getSelection(cur.buffer(), n);
444                 cur.niceInsert(selection);
445                 cur.clearSelection(); // bug 393
446                 cur.bv().switchKeyMap();
447                 finishUndo();
448                 break;
449         }
450
451         case LFUN_CUT:
452                 recordUndo(cur);
453                 cutSelection(cur, true, true);
454                 cur.message(_("Cut"));
455                 // Prevent stale position >= size crash
456                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
457                 cur.normalize();
458                 break;
459
460         case LFUN_COPY:
461                 copySelection(cur);
462                 // FIXME UNICODE
463                 cur.message(_("Copy"));
464                 break;
465
466         case LFUN_MOUSE_PRESS:
467                 lfunMousePress(cur, cmd);
468                 break;
469
470         case LFUN_MOUSE_MOTION:
471                 lfunMouseMotion(cur, cmd);
472                 break;
473
474         case LFUN_MOUSE_RELEASE:
475                 lfunMouseRelease(cur, cmd);
476                 break;
477
478         case LFUN_FINISHED_LEFT:
479                 cur.bv().cursor() = cur;
480                 break;
481
482         case LFUN_FINISHED_RIGHT:
483                 ++cur.pos();
484                 cur.bv().cursor() = cur;
485                 break;
486
487         case LFUN_FINISHED_UP:
488                 cur.bv().cursor() = cur;
489                 break;
490
491         case LFUN_FINISHED_DOWN:
492                 ++cur.pos();
493                 cur.bv().cursor() = cur;
494                 break;
495
496         case LFUN_CHAR_FORWARD:
497                 // FIXME: we have to enable full redraw here because of the
498                 // visual box corners that define the inset. If we know for
499                 // sure that we stay within the same cell we can optimize for
500                 // that using:
501                 //cur.updateFlags(Update::FitCursor);
502         case LFUN_CHAR_FORWARD_SELECT:
503                 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
504                 cur.autocorrect() = false;
505                 cur.clearTargetX();
506                 cur.macroModeClose();
507                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
508                         cur.pushLeft(*cur.nextAtom().nucleus());
509                         cur.inset().idxFirst(cur);
510                 } else if (cur.posRight() || idxRight(cur)
511                         || cur.popRight() || cur.selection())
512                         ;
513                 else {
514                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
515                         cur.undispatched();
516                 }
517                 break;
518
519         case LFUN_CHAR_BACKWARD:
520                 // FIXME: we have to enable full redraw here because of the
521                 // visual box corners that define the inset. If we know for
522                 // sure that we stay within the same cell we can optimize for
523                 // that using:
524                 //cur.updateFlags(Update::FitCursor);
525         case LFUN_CHAR_BACKWARD_SELECT:
526                 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
527                 cur.autocorrect() = false;
528                 cur.clearTargetX();
529                 cur.macroModeClose();
530                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
531                         cur.posLeft();
532                         cur.push(*cur.nextAtom().nucleus());
533                         cur.inset().idxLast(cur);
534                 } else if (cur.posLeft() || idxLeft(cur)
535                         || cur.popLeft() || cur.selection())
536                         ;
537                 else {
538                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
539                         cur.undispatched();
540                 }
541                 break;
542
543         case LFUN_UP:
544                 // FIXME: we have to enable full redraw here because of the
545                 // visual box corners that define the inset. If we know for
546                 // sure that we stay within the same cell we can optimize for
547                 // that using:
548                 //cur.updateFlags(Update::FitCursor);
549         case LFUN_UP_SELECT:
550                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
551                 if (cur.inMacroMode()) {
552                         // Make Helge happy
553                         cur.macroModeClose();
554                         break;
555                 }
556                 cur.selHandle(cmd.action == LFUN_UP_SELECT);
557                 if (!cur.up()) {
558                         cmd = FuncRequest(LFUN_FINISHED_UP);
559                         cur.undispatched();
560                 }
561                 // fixes bug 1598. Please check!
562                 cur.normalize();
563                 break;
564
565         case LFUN_DOWN:
566                 // FIXME: we have to enable full redraw here because of the
567                 // visual box corners that define the inset. If we know for
568                 // sure that we stay within the same cell we can optimize for
569                 // that using:
570                 //cur.updateFlags(Update::FitCursor);
571         case LFUN_DOWN_SELECT:
572                 if (cur.inMacroMode()) {
573                         cur.macroModeClose();
574                         break;
575                 }
576                 cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
577                 if (!cur.down()) {
578                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
579                         cur.undispatched();
580                 }
581                 // fixes bug 1598. Please check!
582                 cur.normalize();
583                 break;
584
585         case LFUN_MOUSE_DOUBLE:
586         case LFUN_MOUSE_TRIPLE:
587         case LFUN_WORD_SELECT:
588                 cur.pos() = 0;
589                 cur.idx() = 0;
590                 cur.resetAnchor();
591                 cur.selection() = true;
592                 cur.pos() = cur.lastpos();
593                 cur.idx() = cur.lastidx();
594                 break;
595
596         case LFUN_PARAGRAPH_UP:
597         case LFUN_PARAGRAPH_DOWN:
598                 // FIXME: we have to enable full redraw here because of the
599                 // visual box corners that define the inset. If we know for
600                 // sure that we stay within the same cell we can optimize for
601                 // that using:
602                 //cur.updateFlags(Update::FitCursor);
603         case LFUN_PARAGRAPH_UP_SELECT:
604         case LFUN_PARAGRAPH_DOWN_SELECT:
605                 break;
606
607         case LFUN_LINE_BEGIN:
608         case LFUN_WORD_BACKWARD:
609                 // FIXME: we have to enable full redraw here because of the
610                 // visual box corners that define the inset. If we know for
611                 // sure that we stay within the same cell we can optimize for
612                 // that using:
613                 //cur.updateFlags(Update::FitCursor);
614         case LFUN_LINE_BEGIN_SELECT:
615         case LFUN_WORD_BACKWARD_SELECT:
616                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
617                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
618                 cur.macroModeClose();
619                 if (cur.pos() != 0) {
620                         cur.pos() = 0;
621                 } else if (cur.col() != 0) {
622                         cur.idx() -= cur.col();
623                         cur.pos() = 0;
624                 } else if (cur.idx() != 0) {
625                         cur.idx() = 0;
626                         cur.pos() = 0;
627                 } else {
628                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
629                         cur.undispatched();
630                 }
631                 break;
632
633         case LFUN_WORD_FORWARD:
634         case LFUN_LINE_END:
635                 // FIXME: we have to enable full redraw here because of the
636                 // visual box corners that define the inset. If we know for
637                 // sure that we stay within the same cell we can optimize for
638                 // that using:
639                 //cur.updateFlags(Update::FitCursor);
640         case LFUN_WORD_FORWARD_SELECT:
641         case LFUN_LINE_END_SELECT:
642                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
643                                 cmd.action == LFUN_LINE_END_SELECT);
644                 cur.macroModeClose();
645                 cur.clearTargetX();
646                 if (cur.pos() != cur.lastpos()) {
647                         cur.pos() = cur.lastpos();
648                 } else if (ncols() && (cur.col() != cur.lastcol())) {
649                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
650                         cur.pos() = cur.lastpos();
651                 } else if (cur.idx() != cur.lastidx()) {
652                         cur.idx() = cur.lastidx();
653                         cur.pos() = cur.lastpos();
654                 } else {
655                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
656                         cur.undispatched();
657                 }
658                 break;
659
660         case LFUN_SCREEN_UP_SELECT:
661         case LFUN_SCREEN_UP:
662                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
663                 cur.undispatched();
664                 break;
665
666         case LFUN_SCREEN_DOWN_SELECT:
667         case LFUN_SCREEN_DOWN:
668                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
669                 cur.undispatched();
670                 break;
671
672         case LFUN_CELL_FORWARD:
673                 // FIXME: we have to enable full redraw here because of the
674                 // visual box corners that define the inset. If we know for
675                 // sure that we stay within the same cell we can optimize for
676                 // that using:
677                 //cur.updateFlags(Update::FitCursor);
678                 cur.inset().idxNext(cur);
679                 break;
680
681         case LFUN_CELL_BACKWARD:
682                 // FIXME: we have to enable full redraw here because of the
683                 // visual box corners that define the inset. If we know for
684                 // sure that we stay within the same cell we can optimize for
685                 // that using:
686                 //cur.updateFlags(Update::FitCursor);
687                 cur.inset().idxPrev(cur);
688                 break;
689
690         case LFUN_WORD_DELETE_BACKWARD:
691         case LFUN_CHAR_DELETE_BACKWARD:
692                 if (cur.pos() == 0)
693                         // May affect external cell:
694                         recordUndoInset(cur, Undo::ATOMIC);
695                 else
696                         recordUndo(cur, Undo::ATOMIC);
697                 // if the inset can not be removed from within, delete it
698                 if (!cur.backspace()) {
699                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
700                         cur.bv().getLyXText()->dispatch(cur, cmd);
701                 }
702                 break;
703
704         case LFUN_WORD_DELETE_FORWARD:
705         case LFUN_CHAR_DELETE_FORWARD:
706                 if (cur.pos() == cur.lastpos())
707                         // May affect external cell:
708                         recordUndoInset(cur, Undo::ATOMIC);
709                 else
710                         recordUndo(cur, Undo::ATOMIC);
711                 // if the inset can not be removed from within, delete it
712                 if (!cur.erase()) {
713                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
714                         cur.bv().getLyXText()->dispatch(cur, cmd);
715                 }
716                 break;
717
718         case LFUN_ESCAPE:
719                 if (cur.selection())
720                         cur.clearSelection();
721                 else  {
722                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
723                         cur.undispatched();
724                 }
725                 break;
726
727         case LFUN_INSET_TOGGLE:
728                 recordUndo(cur);
729                 lock(!lock());
730                 cur.popRight();
731                 break;
732
733         case LFUN_SELF_INSERT:
734                 if (cmd.argument().size() != 1) {
735                         recordUndo(cur);
736                         docstring const arg = cmd.argument();
737                         if (!interpretString(cur, arg))
738                                 cur.insert(arg);
739                         break;
740                 }
741                 // Don't record undo steps if we are in macro mode and
742                 // cmd.argument is the next character of the macro name.
743                 // Otherwise we'll get an invalid cursor if we undo after
744                 // the macro was finished and the macro is a known command,
745                 // e.g. sqrt. LCursor::macroModeClose replaces in this case
746                 // the InsetMathUnknown with name "frac" by an empty
747                 // InsetMathFrac -> a pos value > 0 is invalid.
748                 // A side effect is that an undo before the macro is finished
749                 // undoes the complete macro, not only the last character.
750                 if (!cur.inMacroMode())
751                         recordUndo(cur);
752
753                 // spacial handling of space. If we insert an inset
754                 // via macro mode, we want to put the cursor inside it
755                 // if relevant. Think typing "\frac<space>".
756                 if (cmd.argument()[0] == ' '
757                     && cur.inMacroMode() && cur.macroName() != "\\"
758                     && cur.macroModeClose()) {
759                         MathAtom const atom = cur.prevAtom();
760                         if (atom->asNestInset() && atom->nargs() > 0) {
761                                 cur.posLeft();
762                                 cur.pushLeft(*cur.nextInset());
763                         }
764                 } else if (!interpretChar(cur, cmd.argument()[0])) {
765                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
766                         cur.undispatched();
767                 }
768                 break;
769
770         //case LFUN_SERVER_GET_XY:
771         //      sprintf(dispatch_buffer, "%d %d",);
772         //      break;
773
774         case LFUN_SERVER_SET_XY: {
775                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
776                 int x = 0;
777                 int y = 0;
778                 istringstream is(to_utf8(cmd.argument()));
779                 is >> x >> y;
780                 cur.setScreenPos(x, y);
781                 break;
782         }
783
784         // Special casing for superscript in case of LyX handling
785         // dead-keys:
786         case LFUN_ACCENT_CIRCUMFLEX:
787                 if (cmd.argument().empty()) {
788                         // do superscript if LyX handles
789                         // deadkeys
790                         recordUndo(cur, Undo::ATOMIC);
791                         script(cur, true, grabAndEraseSelection(cur));
792                 }
793                 break;
794
795         case LFUN_ACCENT_UMLAUT:
796         case LFUN_ACCENT_ACUTE:
797         case LFUN_ACCENT_GRAVE:
798         case LFUN_ACCENT_BREVE:
799         case LFUN_ACCENT_DOT:
800         case LFUN_ACCENT_MACRON:
801         case LFUN_ACCENT_CARON:
802         case LFUN_ACCENT_TILDE:
803         case LFUN_ACCENT_CEDILLA:
804         case LFUN_ACCENT_CIRCLE:
805         case LFUN_ACCENT_UNDERDOT:
806         case LFUN_ACCENT_TIE:
807         case LFUN_ACCENT_OGONEK:
808         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
809                 break;
810
811         //  Math fonts
812         case LFUN_FONT_FREE_APPLY:
813         case LFUN_FONT_FREE_UPDATE:
814                 handleFont2(cur, cmd.argument());
815                 break;
816
817         case LFUN_FONT_BOLD:
818                 if (currentMode() == TEXT_MODE)
819                         handleFont(cur, cmd.argument(), "textbf");
820                 else
821                         handleFont(cur, cmd.argument(), "mathbf");
822                 break;
823         case LFUN_FONT_SANS:
824                 if (currentMode() == TEXT_MODE)
825                         handleFont(cur, cmd.argument(), "textsf");
826                 else
827                         handleFont(cur, cmd.argument(), "mathsf");
828                 break;
829         case LFUN_FONT_EMPH:
830                 if (currentMode() == TEXT_MODE)
831                         handleFont(cur, cmd.argument(), "emph");
832                 else
833                         handleFont(cur, cmd.argument(), "mathcal");
834                 break;
835         case LFUN_FONT_ROMAN:
836                 if (currentMode() == TEXT_MODE)
837                         handleFont(cur, cmd.argument(), "textrm");
838                 else
839                         handleFont(cur, cmd.argument(), "mathrm");
840                 break;
841         case LFUN_FONT_CODE:
842                 if (currentMode() == TEXT_MODE)
843                         handleFont(cur, cmd.argument(), "texttt");
844                 else
845                         handleFont(cur, cmd.argument(), "mathtt");
846                 break;
847         case LFUN_FONT_FRAK:
848                 handleFont(cur, cmd.argument(), "mathfrak");
849                 break;
850         case LFUN_FONT_ITAL:
851                 if (currentMode() == TEXT_MODE)
852                         handleFont(cur, cmd.argument(), "textit");
853                 else
854                         handleFont(cur, cmd.argument(), "mathit");
855                 break;
856         case LFUN_FONT_NOUN:
857                 if (currentMode() == TEXT_MODE)
858                         // FIXME: should be "noun"
859                         handleFont(cur, cmd.argument(), "textsc");
860                 else
861                         handleFont(cur, cmd.argument(), "mathbb");
862                 break;
863         //case LFUN_FONT_FREE_APPLY:
864                 handleFont(cur, cmd.argument(), "textrm");
865                 break;
866         case LFUN_FONT_DEFAULT:
867                 handleFont(cur, cmd.argument(), "textnormal");
868                 break;
869
870         case LFUN_MATH_MODE: {
871 #if 1
872                 // ignore math-mode on when already in math mode
873                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument() == "on")
874                         break;
875                 cur.macroModeClose();
876                 docstring const save_selection = grabAndEraseSelection(cur);
877                 selClearOrDel(cur);
878                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
879                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
880                 cur.posLeft();
881                 cur.pushLeft(*cur.nextInset());
882                 cur.niceInsert(save_selection);
883 #else
884                 if (currentMode() == InsetBase::TEXT_MODE) {
885                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
886                         cur.message(_("create new math text environment ($...$)"));
887                 } else {
888                         handleFont(cur, cmd.argument(), "textrm");
889                         cur.message(_("entered math text mode (textrm)"));
890                 }
891 #endif
892                 break;
893         }
894
895         case LFUN_MATH_SIZE:
896 #if 0
897                 recordUndo(cur);
898                 cur.setSize(arg);
899 #endif
900                 break;
901
902         case LFUN_MATH_MATRIX: {
903                 recordUndo(cur, Undo::ATOMIC);
904                 unsigned int m = 1;
905                 unsigned int n = 1;
906                 docstring v_align;
907                 docstring h_align;
908                 idocstringstream is(cmd.argument());
909                 is >> m >> n >> v_align >> h_align;
910                 if (m < 1)
911                         m = 1;
912                 if (n < 1)
913                         n = 1;
914                 v_align += 'c';
915                 cur.niceInsert(
916                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
917                 break;
918         }
919
920         case LFUN_MATH_DELIM: {
921                 docstring ls;
922                 docstring rs = support::split(cmd.argument(), ls, ' ');
923                 // Reasonable default values
924                 if (ls.empty())
925                         ls = '(';
926                 if (rs.empty())
927                         rs = ')';
928                 recordUndo(cur, Undo::ATOMIC);
929                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
930                 break;
931         }
932
933         case LFUN_MATH_BIGDELIM: {
934                 docstring const lname  = from_utf8(cmd.getArg(0));
935                 docstring const ldelim = from_utf8(cmd.getArg(1));
936                 docstring const rname  = from_utf8(cmd.getArg(2));
937                 docstring const rdelim = from_utf8(cmd.getArg(3));
938                 latexkeys const * l = in_word_set(lname);
939                 bool const have_l = l && l->inset == "big" &&
940                                     InsetMathBig::isBigInsetDelim(ldelim);
941                 l = in_word_set(rname);
942                 bool const have_r = l && l->inset == "big" &&
943                                     InsetMathBig::isBigInsetDelim(rdelim);
944                 // We mimic LFUN_MATH_DELIM in case we have an empty left
945                 // or right delimiter.
946                 if (have_l || have_r) {
947                         recordUndo(cur, Undo::ATOMIC);
948                         docstring const selection = grabAndEraseSelection(cur);
949                         selClearOrDel(cur);
950                         if (have_l)
951                                 cur.insert(MathAtom(new InsetMathBig(lname,
952                                                                 ldelim)));
953                         cur.niceInsert(selection);
954                         if (have_r)
955                                 cur.insert(MathAtom(new InsetMathBig(rname,
956                                                                 rdelim)));
957                 }
958                 // Don't call cur.undispatched() if we did nothing, this would
959                 // lead to infinite recursion via LyXText::dispatch().
960                 break;
961         }
962
963         case LFUN_SPACE_INSERT:
964         case LFUN_MATH_SPACE:
965                 recordUndo(cur, Undo::ATOMIC);
966                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
967                 break;
968
969         case LFUN_ERT_INSERT:
970                 // interpret this as if a backslash was typed
971                 recordUndo(cur, Undo::ATOMIC);
972                 interpretChar(cur, '\\');
973                 break;
974
975         case LFUN_MATH_SUBSCRIPT:
976                 // interpret this as if a _ was typed
977                 recordUndo(cur, Undo::ATOMIC);
978                 interpretChar(cur, '_');
979                 break;
980
981         case LFUN_MATH_SUPERSCRIPT:
982                 // interpret this as if a ^ was typed
983                 recordUndo(cur, Undo::ATOMIC);
984                 interpretChar(cur, '^');
985                 break;
986
987         case LFUN_QUOTE_INSERT:
988                 // interpret this as if a straight " was typed
989                 recordUndo(cur, Undo::ATOMIC);
990                 interpretChar(cur, '\"');
991                 break;
992
993 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
994 // handling such that "self-insert" works on "arbitrary stuff" too, and
995 // math-insert only handles special math things like "matrix".
996         case LFUN_MATH_INSERT: {
997                 recordUndo(cur, Undo::ATOMIC);
998                 if (cmd.argument() == "^" || cmd.argument() == "_") {
999                         interpretChar(cur, cmd.argument()[0]);
1000                 } else
1001                         cur.niceInsert(cmd.argument());
1002                 break;
1003                 }
1004
1005         case LFUN_DIALOG_SHOW_NEW_INSET: {
1006                 docstring const & name = cmd.argument();
1007                 string data;
1008                 if (name == "ref") {
1009                         RefInset tmp(name);
1010                         data = tmp.createDialogStr(to_utf8(name));
1011                 }
1012                 cur.bv().showInsetDialog(to_utf8(name), data, 0);
1013                 break;
1014         }
1015
1016         case LFUN_INSET_INSERT: {
1017                 MathArray ar;
1018                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1019                         recordUndo(cur);
1020                         cur.insert(ar);
1021                 } else
1022                         cur.undispatched();
1023                 break;
1024         }
1025
1026         default:
1027                 InsetMathDim::doDispatch(cur, cmd);
1028                 break;
1029         }
1030 }
1031
1032
1033 bool InsetMathNest::getStatus(LCursor & cur, FuncRequest const & cmd,
1034                 FuncStatus & flag) const
1035 {
1036         // the font related toggles
1037         //string tc = "mathnormal";
1038         bool ret = true;
1039         string const arg = to_utf8(cmd.argument());
1040         switch (cmd.action) {
1041         case LFUN_TABULAR_FEATURE:
1042                 flag.enabled(false);
1043                 break;
1044 #if 0
1045         case LFUN_TABULAR_FEATURE:
1046                 // FIXME: check temporarily disabled
1047                 // valign code
1048                 char align = mathcursor::valign();
1049                 if (align == '\0') {
1050                         enable = false;
1051                         break;
1052                 }
1053                 if (cmd.argument().empty()) {
1054                         flag.clear();
1055                         break;
1056                 }
1057                 if (!contains("tcb", cmd.argument()[0])) {
1058                         enable = false;
1059                         break;
1060                 }
1061                 flag.setOnOff(cmd.argument()[0] == align);
1062                 break;
1063 #endif
1064         /// We have to handle them since 1.4 blocks all unhandled actions
1065         case LFUN_FONT_ITAL:
1066         case LFUN_FONT_BOLD:
1067         case LFUN_FONT_SANS:
1068         case LFUN_FONT_EMPH:
1069         case LFUN_FONT_CODE:
1070         case LFUN_FONT_NOUN:
1071         case LFUN_FONT_ROMAN:
1072         case LFUN_FONT_DEFAULT:
1073                 flag.enabled(true);
1074                 break;
1075         case LFUN_MATH_MUTATE:
1076                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1077                 flag.setOnOff(false);
1078                 break;
1079
1080         // we just need to be in math mode to enable that
1081         case LFUN_MATH_SIZE:
1082         case LFUN_MATH_SPACE:
1083         case LFUN_MATH_LIMITS:
1084         case LFUN_MATH_NONUMBER:
1085         case LFUN_MATH_NUMBER:
1086         case LFUN_MATH_EXTERN:
1087                 flag.enabled(true);
1088                 break;
1089
1090         case LFUN_FONT_FRAK:
1091                 flag.enabled(currentMode() != TEXT_MODE);
1092                 break;
1093
1094         case LFUN_MATH_INSERT: {
1095                 bool const textarg =
1096                         arg == "\\textbf"   || arg == "\\textsf" ||
1097                         arg == "\\textrm"   || arg == "\\textmd" ||
1098                         arg == "\\textit"   || arg == "\\textsc" ||
1099                         arg == "\\textsl"   || arg == "\\textup" ||
1100                         arg == "\\texttt"   || arg == "\\textbb" ||
1101                         arg == "\\textnormal";
1102                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1103                 break;
1104         }
1105
1106         case LFUN_MATH_MATRIX:
1107                 flag.enabled(currentMode() == MATH_MODE);
1108                 break;
1109
1110         case LFUN_INSET_INSERT: {
1111                 // Don't test createMathInset_fromDialogStr(), since
1112                 // getStatus is not called with a valid reference and the
1113                 // dialog would not be applyable.
1114                 string const name = cmd.getArg(0);
1115                 flag.enabled(name == "ref");
1116                 break;
1117         }
1118
1119         case LFUN_MATH_DELIM:
1120         case LFUN_MATH_BIGDELIM:
1121                 // Don't do this with multi-cell selections
1122                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1123                 break;
1124
1125         default:
1126                 ret = false;
1127                 break;
1128         }
1129         return ret;
1130 }
1131
1132
1133 void InsetMathNest::edit(LCursor & cur, bool left)
1134 {
1135         cur.push(*this);
1136         cur.idx() = left ? 0 : cur.lastidx();
1137         cur.pos() = left ? 0 : cur.lastpos();
1138         cur.resetAnchor();
1139         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1140 }
1141
1142
1143 InsetBase * InsetMathNest::editXY(LCursor & cur, int x, int y)
1144 {
1145         int idx_min = 0;
1146         int dist_min = 1000000;
1147         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1148                 int const d = cell(i).dist(cur.bv(), x, y);
1149                 if (d < dist_min) {
1150                         dist_min = d;
1151                         idx_min = i;
1152                 }
1153         }
1154         MathArray & ar = cell(idx_min);
1155         cur.push(*this);
1156         cur.idx() = idx_min;
1157         cur.pos() = ar.x2pos(x - ar.xo(cur.bv()));
1158
1159         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1160         if (dist_min == 0) {
1161                 // hit inside cell
1162                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1163                         if (ar[i]->covers(cur.bv(), x, y))
1164                                 return ar[i].nucleus()->editXY(cur, x, y);
1165         }
1166         return this;
1167 }
1168
1169
1170 void InsetMathNest::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1171 {
1172         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1173         BufferView & bv = cur.bv();
1174         if (cmd.button() == mouse_button::button1) {
1175                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1176                 bv.mouseSetCursor(cur);
1177                 // FIXME: we have to enable full redraw here because of the
1178                 // visual box corners that define the inset.
1179                 //cur.noUpdate();
1180         } else if (cmd.button() == mouse_button::button2) {
1181                 MathArray ar;
1182                 if (cur.selection())
1183                         asArray(bv.cursor().selectionAsString(false), ar);
1184                 else
1185                         asArray(theSelection().get(), ar);
1186
1187                 cur.insert(ar);
1188                 bv.mouseSetCursor(cur);
1189         }
1190 }
1191
1192
1193 void InsetMathNest::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1194 {
1195         // only select with button 1
1196         if (cmd.button() == mouse_button::button1) {
1197                 LCursor & bvcur = cur.bv().cursor();
1198                 if (bvcur.anchor_.hasPart(cur)) {
1199                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1200                         bvcur.setCursor(cur);
1201                         bvcur.selection() = true;
1202                         //lyxerr << "MOTION " << bvcur << endl;
1203                 }
1204                 else {
1205                         cur.undispatched();
1206                 }
1207         }
1208 }
1209
1210
1211 void InsetMathNest::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1212 {
1213         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1214
1215         if (cmd.button() == mouse_button::button1) {
1216                 //theSelection().put(cur.grabSelection());
1217                 if (!cur.selection())
1218                         cur.noUpdate();
1219                 return;
1220         }
1221
1222         if (cmd.button() == mouse_button::button3) {
1223                 // try to dispatch to enclosed insets first
1224                 cur.bv().showDialog("mathpanel");
1225                 return;
1226         }
1227
1228         cur.undispatched();
1229 }
1230
1231
1232 bool InsetMathNest::interpretChar(LCursor & cur, char_type c)
1233 {
1234         //lyxerr << "interpret 2: '" << c << "'" << endl;
1235         docstring save_selection;
1236         if (c == '^' || c == '_')
1237                 save_selection = grabAndEraseSelection(cur);
1238
1239         cur.clearTargetX();
1240
1241         // handle macroMode
1242         if (cur.inMacroMode()) {
1243                 docstring name = cur.macroName();
1244
1245                 /// are we currently typing '#1' or '#2' or...?
1246                 if (name == "\\#") {
1247                         cur.backspace();
1248                         int n = c - '0';
1249                         if (n >= 1 && n <= 9)
1250                                 cur.insert(new MathMacroArgument(n));
1251                         return true;
1252                 }
1253
1254                 if (isalpha(c)) {
1255                         cur.activeMacro()->setName(name + docstring(1, c));
1256                         return true;
1257                 }
1258
1259                 // handle 'special char' macros
1260                 if (name == "\\") {
1261                         // remove the '\\'
1262                         if (c == '\\') {
1263                                 cur.backspace();
1264                                 if (currentMode() == InsetMath::TEXT_MODE)
1265                                         cur.niceInsert(createInsetMath("textbackslash"));
1266                                 else
1267                                         cur.niceInsert(createInsetMath("backslash"));
1268                         } else if (c == '{') {
1269                                 cur.backspace();
1270                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1271                         } else if (c == '%') {
1272                                 cur.backspace();
1273                                 cur.niceInsert(MathAtom(new InsetMathComment));
1274                         } else if (c == '#') {
1275                                 BOOST_ASSERT(cur.activeMacro());
1276                                 cur.activeMacro()->setName(name + docstring(1, c));
1277                         } else {
1278                                 cur.backspace();
1279                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1280                         }
1281                         return true;
1282                 }
1283
1284                 // One character big delimiters. The others are handled in
1285                 // interpretString().
1286                 latexkeys const * l = in_word_set(name.substr(1));
1287                 if (name[0] == '\\' && l && l->inset == "big") {
1288                         docstring delim;
1289                         switch (c) {
1290                         case '{':
1291                                 delim = from_ascii("\\{");
1292                                 break;
1293                         case '}':
1294                                 delim = from_ascii("\\}");
1295                                 break;
1296                         default:
1297                                 delim = docstring(1, c);
1298                                 break;
1299                         }
1300                         if (InsetMathBig::isBigInsetDelim(delim)) {
1301                                 // name + delim ared a valid InsetMathBig.
1302                                 // We can't use cur.macroModeClose() because
1303                                 // it does not handle delim.
1304                                 InsetMathUnknown * p = cur.activeMacro();
1305                                 p->finalize();
1306                                 --cur.pos();
1307                                 cur.cell().erase(cur.pos());
1308                                 cur.plainInsert(MathAtom(
1309                                         new InsetMathBig(name.substr(1), delim)));
1310                                 return true;
1311                         }
1312                 }
1313
1314                 // leave macro mode and try again if necessary
1315                 cur.macroModeClose();
1316                 if (c == '{')
1317                         cur.niceInsert(MathAtom(new InsetMathBrace));
1318                 else if (c != ' ')
1319                         interpretChar(cur, c);
1320                 return true;
1321         }
1322
1323         // This is annoying as one has to press <space> far too often.
1324         // Disable it.
1325
1326 #if 0
1327                 // leave autocorrect mode if necessary
1328                 if (autocorrect() && c == ' ') {
1329                         autocorrect() = false;
1330                         return true;
1331                 }
1332 #endif
1333
1334         // just clear selection on pressing the space bar
1335         if (cur.selection() && c == ' ') {
1336                 cur.selection() = false;
1337                 return true;
1338         }
1339
1340         selClearOrDel(cur);
1341
1342         if (c == '\\') {
1343                 //lyxerr << "starting with macro" << endl;
1344                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1345                 return true;
1346         }
1347
1348         if (c == '\n') {
1349                 if (currentMode() == InsetMath::TEXT_MODE)
1350                         cur.insert(c);
1351                 return true;
1352         }
1353
1354         if (c == ' ') {
1355                 if (currentMode() == InsetMath::TEXT_MODE) {
1356                         // insert spaces in text mode,
1357                         // but suppress direct insertion of two spaces in a row
1358                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1359                         // it is better than nothing...
1360                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1361                                 cur.insert(c);
1362                                 // FIXME: we have to enable full redraw here because of the
1363                                 // visual box corners that define the inset. If we know for
1364                                 // sure that we stay within the same cell we can optimize for
1365                                 // that using:
1366                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1367                         }
1368                         return true;
1369                 }
1370                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1371                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1372                         // FIXME: we have to enable full redraw here because of the
1373                         // visual box corners that define the inset. If we know for
1374                         // sure that we stay within the same cell we can optimize for
1375                         // that using:
1376                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1377                         return true;
1378                 }
1379
1380                 if (cur.popRight()) {
1381                         // FIXME: we have to enable full redraw here because of the
1382                         // visual box corners that define the inset. If we know for
1383                         // sure that we stay within the same cell we can optimize for
1384                         // that using:
1385                         //cur.updateFlags(Update::FitCursor);
1386                         return true;
1387                 }
1388
1389                 // if we are at the very end, leave the formula
1390                 return cur.pos() != cur.lastpos();
1391         }
1392
1393         // These shouldn't work in text mode:
1394         if (currentMode() != InsetMath::TEXT_MODE) {
1395                 if (c == '_') {
1396                         script(cur, false, save_selection);
1397                         return true;
1398                 }
1399                 if (c == '^') {
1400                         script(cur, true, save_selection);
1401                         return true;
1402                 }
1403                 if (c == '~') {
1404                         cur.niceInsert(createInsetMath("sim"));
1405                         return true;
1406                 }
1407         }
1408
1409         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1410             c == '%' || c == '_' || c == '^') {
1411                 cur.niceInsert(createInsetMath(docstring(1, c)));
1412                 return true;
1413         }
1414
1415
1416         // try auto-correction
1417         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1418         //      return true;
1419
1420         // no special circumstances, so insert the character without any fuss
1421         cur.insert(c);
1422         cur.autocorrect() = true;
1423         return true;
1424 }
1425
1426
1427 bool InsetMathNest::interpretString(LCursor & cur, docstring const & str)
1428 {
1429         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1430         // possible
1431         if (!cur.empty() && cur.pos() > 0 &&
1432             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1433                 if (InsetMathBig::isBigInsetDelim(str)) {
1434                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1435                         if (prev[0] == '\\') {
1436                                 prev = prev.substr(1);
1437                                 latexkeys const * l = in_word_set(prev);
1438                                 if (l && l->inset == "big") {
1439                                         cur.cell()[cur.pos() - 1] =
1440                                                 MathAtom(new InsetMathBig(prev, str));
1441                                         return true;
1442                                 }
1443                         }
1444                 }
1445         }
1446         return false;
1447 }
1448
1449
1450 bool InsetMathNest::script(LCursor & cur, bool up, 
1451                 docstring const & save_selection)
1452 {
1453         // Hack to get \^ and \_ working
1454         //lyxerr << "handling script: up: " << up << endl;
1455         if (cur.inMacroMode() && cur.macroName() == "\\") {
1456                 if (up)
1457                         cur.niceInsert(createInsetMath("mathcircumflex"));
1458                 else
1459                         interpretChar(cur, '_');
1460                 return true;
1461         }
1462
1463         cur.macroModeClose();
1464         if (asScriptInset() && cur.idx() == 0) {
1465                 // we are in a nucleus of a script inset, move to _our_ script
1466                 InsetMathScript * inset = asScriptInset();
1467                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1468                 inset->ensure(up);
1469                 cur.idx() = inset->idxOfScript(up);
1470                 cur.pos() = 0;
1471         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1472                 --cur.pos();
1473                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1474                 cur.push(*inset);
1475                 inset->ensure(up);
1476                 cur.idx() = inset->idxOfScript(up);
1477                 cur.pos() = cur.lastpos();
1478         } else {
1479                 // convert the thing to our left to a scriptinset or create a new
1480                 // one if in the very first position of the array
1481                 if (cur.pos() == 0) {
1482                         //lyxerr << "new scriptinset" << endl;
1483                         cur.insert(new InsetMathScript(up));
1484                 } else {
1485                         //lyxerr << "converting prev atom " << endl;
1486                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1487                 }
1488                 --cur.pos();
1489                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1490                 // See comment in MathParser.C for special handling of {}-bases
1491
1492                 cur.push(*inset);
1493                 cur.idx() = 1;
1494                 cur.pos() = 0;
1495         }
1496         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1497         cur.niceInsert(save_selection);
1498         cur.resetAnchor();
1499         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1500         return true;
1501 }
1502
1503
1504 } // namespace lyx