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