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