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