]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
adjust
[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         case LFUN_INSET_DISSOLVE:
1007                 if (!asHullInset()) {
1008                         recordUndoInset(cur, Undo::ATOMIC);
1009                         cur.pullArg();
1010                 }
1011                 break;
1012
1013         default:
1014                 InsetMath::doDispatch(cur, cmd);
1015                 break;
1016         }
1017 }
1018
1019
1020 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1021                 FuncStatus & flag) const
1022 {
1023         // the font related toggles
1024         //string tc = "mathnormal";
1025         bool ret = true;
1026         string const arg = to_utf8(cmd.argument());
1027         switch (cmd.action) {
1028         case LFUN_TABULAR_FEATURE:
1029                 flag.enabled(false);
1030                 break;
1031 #if 0
1032         case LFUN_TABULAR_FEATURE:
1033                 // FIXME: check temporarily disabled
1034                 // valign code
1035                 char align = mathcursor::valign();
1036                 if (align == '\0') {
1037                         enable = false;
1038                         break;
1039                 }
1040                 if (cmd.argument().empty()) {
1041                         flag.clear();
1042                         break;
1043                 }
1044                 if (!contains("tcb", cmd.argument()[0])) {
1045                         enable = false;
1046                         break;
1047                 }
1048                 flag.setOnOff(cmd.argument()[0] == align);
1049                 break;
1050 #endif
1051         /// We have to handle them since 1.4 blocks all unhandled actions
1052         case LFUN_FONT_ITAL:
1053         case LFUN_FONT_BOLD:
1054         case LFUN_FONT_SANS:
1055         case LFUN_FONT_EMPH:
1056         case LFUN_FONT_TYPEWRITER:
1057         case LFUN_FONT_NOUN:
1058         case LFUN_FONT_ROMAN:
1059         case LFUN_FONT_DEFAULT:
1060                 flag.enabled(true);
1061                 break;
1062         case LFUN_MATH_MUTATE:
1063                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1064                 flag.setOnOff(false);
1065                 break;
1066
1067         // we just need to be in math mode to enable that
1068         case LFUN_MATH_SIZE:
1069         case LFUN_MATH_SPACE:
1070         case LFUN_MATH_LIMITS:
1071         case LFUN_MATH_NONUMBER:
1072         case LFUN_MATH_NUMBER:
1073         case LFUN_MATH_EXTERN:
1074                 flag.enabled(true);
1075                 break;
1076
1077         case LFUN_FONT_FRAK:
1078                 flag.enabled(currentMode() != TEXT_MODE);
1079                 break;
1080
1081         case LFUN_MATH_INSERT: {
1082                 bool const textarg =
1083                         arg == "\\textbf"   || arg == "\\textsf" ||
1084                         arg == "\\textrm"   || arg == "\\textmd" ||
1085                         arg == "\\textit"   || arg == "\\textsc" ||
1086                         arg == "\\textsl"   || arg == "\\textup" ||
1087                         arg == "\\texttt"   || arg == "\\textbb" ||
1088                         arg == "\\textnormal";
1089                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1090                 break;
1091         }
1092
1093         case LFUN_MATH_MATRIX:
1094                 flag.enabled(currentMode() == MATH_MODE);
1095                 break;
1096
1097         case LFUN_INSET_INSERT: {
1098                 // Don't test createMathInset_fromDialogStr(), since
1099                 // getStatus is not called with a valid reference and the
1100                 // dialog would not be applyable.
1101                 string const name = cmd.getArg(0);
1102                 flag.enabled(name == "ref");
1103                 break;
1104         }
1105
1106         case LFUN_MATH_DELIM:
1107         case LFUN_MATH_BIGDELIM:
1108                 // Don't do this with multi-cell selections
1109                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1110                 break;
1111
1112         case LFUN_HYPHENATION_POINT_INSERT:
1113         case LFUN_LIGATURE_BREAK_INSERT:
1114         case LFUN_MENU_SEPARATOR_INSERT:
1115         case LFUN_DOTS_INSERT:
1116         case LFUN_END_OF_SENTENCE_PERIOD_INSERT:
1117                 // FIXME: These would probably make sense in math-text mode
1118                 flag.enabled(false);
1119                 break;
1120
1121         case LFUN_INSET_DISSOLVE:
1122                 flag.enabled(!asHullInset());
1123                 break;
1124
1125         default:
1126                 ret = false;
1127                 break;
1128         }
1129         return ret;
1130 }
1131
1132
1133 void InsetMathNest::edit(Cursor & cur, bool left)
1134 {
1135         cur.push(*this);
1136         cur.idx() = left ? 0 : cur.lastidx();
1137         cur.pos() = left ? 0 : cur.lastpos();
1138         cur.resetAnchor();
1139         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1140 }
1141
1142
1143 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1144 {
1145         int idx_min = 0;
1146         int dist_min = 1000000;
1147         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1148                 int const d = cell(i).dist(cur.bv(), x, y);
1149                 if (d < dist_min) {
1150                         dist_min = d;
1151                         idx_min = i;
1152                 }
1153         }
1154         MathData & ar = cell(idx_min);
1155         cur.push(*this);
1156         cur.idx() = idx_min;
1157         cur.pos() = ar.x2pos(x - ar.xo(cur.bv()));
1158
1159         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1160         if (dist_min == 0) {
1161                 // hit inside cell
1162                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1163                         if (ar[i]->covers(cur.bv(), x, y))
1164                                 return ar[i].nucleus()->editXY(cur, x, y);
1165         }
1166         return this;
1167 }
1168
1169
1170 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1171 {
1172         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1173         BufferView & bv = cur.bv();
1174         bool do_selection = cmd.button() == mouse_button::button1
1175                 && cmd.argument() == "region-select";
1176         bv.mouseSetCursor(cur, do_selection);
1177         if (cmd.button() == mouse_button::button1) {
1178                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1179                 // Update the cursor update flags as needed:
1180                 //
1181                 // Update::Decoration: tells to update the decoration
1182                 //                     (visual box corners that define
1183                 //                     the inset)/
1184                 // Update::FitCursor: adjust the screen to the cursor
1185                 //                    position if needed
1186                 // cur.result().update(): don't overwrite previously set flags.
1187                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1188                                 | cur.result().update());
1189         } else if (cmd.button() == mouse_button::button2) {
1190                 if (cap::selection()) {
1191                         // See comment in Text::dispatch why we do this
1192                         cap::copySelectionToStack();
1193                         cmd = FuncRequest(LFUN_PASTE, "0");
1194                         doDispatch(bv.cursor(), cmd);
1195                 } else {
1196                         MathData ar;
1197                         asArray(theSelection().get(), ar);
1198                         bv.cursor().insert(ar);
1199                 }
1200         }
1201 }
1202
1203
1204 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1205 {
1206         // only select with button 1
1207         if (cmd.button() == mouse_button::button1) {
1208                 Cursor & bvcur = cur.bv().cursor();
1209                 if (bvcur.anchor_.hasPart(cur)) {
1210                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1211                         bvcur.setCursor(cur);
1212                         bvcur.selection() = true;
1213                         //lyxerr << "MOTION " << bvcur << endl;
1214                 } else
1215                         cur.undispatched();
1216         }
1217 }
1218
1219
1220 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1221 {
1222         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1223
1224         if (cmd.button() == mouse_button::button1) {
1225                 if (!cur.selection())
1226                         cur.noUpdate();
1227                 else {
1228                         Cursor & bvcur = cur.bv().cursor();
1229                         bvcur.selection() = true;
1230                 }
1231                 return;
1232         }
1233
1234         cur.undispatched();
1235 }
1236
1237
1238 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1239 {
1240         //lyxerr << "interpret 2: '" << c << "'" << endl;
1241         docstring save_selection;
1242         if (c == '^' || c == '_')
1243                 save_selection = grabAndEraseSelection(cur);
1244
1245         cur.clearTargetX();
1246
1247         // handle macroMode
1248         if (cur.inMacroMode()) {
1249                 docstring name = cur.macroName();
1250
1251                 /// are we currently typing '#1' or '#2' or...?
1252                 if (name == "\\#") {
1253                         cur.backspace();
1254                         int n = c - '0';
1255                         if (n >= 1 && n <= 9)
1256                                 cur.insert(new MathMacroArgument(n));
1257                         return true;
1258                 }
1259
1260                 if (isAlphaASCII(c)) {
1261                         cur.activeMacro()->setName(name + docstring(1, c));
1262                         return true;
1263                 }
1264
1265                 // handle 'special char' macros
1266                 if (name == "\\") {
1267                         // remove the '\\'
1268                         if (c == '\\') {
1269                                 cur.backspace();
1270                                 if (currentMode() == InsetMath::TEXT_MODE)
1271                                         cur.niceInsert(createInsetMath("textbackslash"));
1272                                 else
1273                                         cur.niceInsert(createInsetMath("backslash"));
1274                         } else if (c == '{') {
1275                                 cur.backspace();
1276                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1277                         } else if (c == '%') {
1278                                 cur.backspace();
1279                                 cur.niceInsert(MathAtom(new InsetMathComment));
1280                         } else if (c == '#') {
1281                                 BOOST_ASSERT(cur.activeMacro());
1282                                 cur.activeMacro()->setName(name + docstring(1, c));
1283                         } else {
1284                                 cur.backspace();
1285                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1286                         }
1287                         return true;
1288                 }
1289
1290                 // One character big delimiters. The others are handled in
1291                 // interpretString().
1292                 latexkeys const * l = in_word_set(name.substr(1));
1293                 if (name[0] == '\\' && l && l->inset == "big") {
1294                         docstring delim;
1295                         switch (c) {
1296                         case '{':
1297                                 delim = from_ascii("\\{");
1298                                 break;
1299                         case '}':
1300                                 delim = from_ascii("\\}");
1301                                 break;
1302                         default:
1303                                 delim = docstring(1, c);
1304                                 break;
1305                         }
1306                         if (InsetMathBig::isBigInsetDelim(delim)) {
1307                                 // name + delim ared a valid InsetMathBig.
1308                                 // We can't use cur.macroModeClose() because
1309                                 // it does not handle delim.
1310                                 InsetMathUnknown * p = cur.activeMacro();
1311                                 p->finalize();
1312                                 --cur.pos();
1313                                 cur.cell().erase(cur.pos());
1314                                 cur.plainInsert(MathAtom(
1315                                         new InsetMathBig(name.substr(1), delim)));
1316                                 return true;
1317                         }
1318                 }
1319
1320                 // leave macro mode and try again if necessary
1321                 cur.macroModeClose();
1322                 if (c == '{')
1323                         cur.niceInsert(MathAtom(new InsetMathBrace));
1324                 else if (c != ' ')
1325                         interpretChar(cur, c);
1326                 return true;
1327         }
1328
1329         // This is annoying as one has to press <space> far too often.
1330         // Disable it.
1331
1332 #if 0
1333                 // leave autocorrect mode if necessary
1334                 if (autocorrect() && c == ' ') {
1335                         autocorrect() = false;
1336                         return true;
1337                 }
1338 #endif
1339
1340         // just clear selection on pressing the space bar
1341         if (cur.selection() && c == ' ') {
1342                 cur.selection() = false;
1343                 return true;
1344         }
1345
1346         selClearOrDel(cur);
1347
1348         if (c == '\\') {
1349                 //lyxerr << "starting with macro" << endl;
1350                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1351                 return true;
1352         }
1353
1354         if (c == '\n') {
1355                 if (currentMode() == InsetMath::TEXT_MODE)
1356                         cur.insert(c);
1357                 return true;
1358         }
1359
1360         if (c == ' ') {
1361                 if (currentMode() == InsetMath::TEXT_MODE) {
1362                         // insert spaces in text mode,
1363                         // but suppress direct insertion of two spaces in a row
1364                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1365                         // it is better than nothing...
1366                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1367                                 cur.insert(c);
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::SinglePar | Update::FitCursor);
1373                         }
1374                         return true;
1375                 }
1376                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1377                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1378                         // FIXME: we have to enable full redraw here because of the
1379                         // visual box corners that define the inset. If we know for
1380                         // sure that we stay within the same cell we can optimize for
1381                         // that using:
1382                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1383                         return true;
1384                 }
1385
1386                 if (cur.popRight()) {
1387                         // FIXME: we have to enable full redraw here because of the
1388                         // visual box corners that define the inset. If we know for
1389                         // sure that we stay within the same cell we can optimize for
1390                         // that using:
1391                         //cur.updateFlags(Update::FitCursor);
1392                         return true;
1393                 }
1394
1395                 // if we are at the very end, leave the formula
1396                 return cur.pos() != cur.lastpos();
1397         }
1398
1399         // These shouldn't work in text mode:
1400         if (currentMode() != InsetMath::TEXT_MODE) {
1401                 if (c == '_') {
1402                         script(cur, false, save_selection);
1403                         return true;
1404                 }
1405                 if (c == '^') {
1406                         script(cur, true, save_selection);
1407                         return true;
1408                 }
1409                 if (c == '~') {
1410                         cur.niceInsert(createInsetMath("sim"));
1411                         return true;
1412                 }
1413         }
1414
1415         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1416             c == '%' || c == '_' || c == '^') {
1417                 cur.niceInsert(createInsetMath(docstring(1, c)));
1418                 return true;
1419         }
1420
1421
1422         // try auto-correction
1423         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1424         //      return true;
1425
1426         // no special circumstances, so insert the character without any fuss
1427         cur.insert(c);
1428         cur.autocorrect() = true;
1429         return true;
1430 }
1431
1432
1433 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1434 {
1435         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1436         // possible
1437         if (!cur.empty() && cur.pos() > 0 &&
1438             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1439                 if (InsetMathBig::isBigInsetDelim(str)) {
1440                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1441                         if (prev[0] == '\\') {
1442                                 prev = prev.substr(1);
1443                                 latexkeys const * l = in_word_set(prev);
1444                                 if (l && l->inset == "big") {
1445                                         cur.cell()[cur.pos() - 1] =
1446                                                 MathAtom(new InsetMathBig(prev, str));
1447                                         return true;
1448                                 }
1449                         }
1450                 }
1451         }
1452         return false;
1453 }
1454
1455
1456 bool InsetMathNest::script(Cursor & cur, bool up,
1457                 docstring const & save_selection)
1458 {
1459         // Hack to get \^ and \_ working
1460         //lyxerr << "handling script: up: " << up << endl;
1461         if (cur.inMacroMode() && cur.macroName() == "\\") {
1462                 if (up)
1463                         cur.niceInsert(createInsetMath("mathcircumflex"));
1464                 else
1465                         interpretChar(cur, '_');
1466                 return true;
1467         }
1468
1469         cur.macroModeClose();
1470         if (asScriptInset() && cur.idx() == 0) {
1471                 // we are in a nucleus of a script inset, move to _our_ script
1472                 InsetMathScript * inset = asScriptInset();
1473                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1474                 inset->ensure(up);
1475                 cur.idx() = inset->idxOfScript(up);
1476                 cur.pos() = 0;
1477         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1478                 --cur.pos();
1479                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1480                 cur.push(*inset);
1481                 inset->ensure(up);
1482                 cur.idx() = inset->idxOfScript(up);
1483                 cur.pos() = cur.lastpos();
1484         } else {
1485                 // convert the thing to our left to a scriptinset or create a new
1486                 // one if in the very first position of the array
1487                 if (cur.pos() == 0) {
1488                         //lyxerr << "new scriptinset" << endl;
1489                         cur.insert(new InsetMathScript(up));
1490                 } else {
1491                         //lyxerr << "converting prev atom " << endl;
1492                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1493                 }
1494                 --cur.pos();
1495                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1496                 // See comment in MathParser.cpp for special handling of {}-bases
1497
1498                 cur.push(*inset);
1499                 cur.idx() = 1;
1500                 cur.pos() = 0;
1501         }
1502         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1503         cur.niceInsert(save_selection);
1504         cur.resetAnchor();
1505         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1506         return true;
1507 }
1508
1509
1510 } // namespace lyx