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