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