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