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