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