]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.cpp
Whitespace cleanup
[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_FINISHED_UP:
480                 cur.bv().cursor() = cur;
481                 break;
482
483         case LFUN_FINISHED_DOWN:
484                 ++cur.pos();
485                 cur.bv().cursor() = cur;
486                 break;
487
488         case LFUN_CHAR_FORWARD:
489                 cur.updateFlags(Update::Decoration | Update::FitCursor);
490         case LFUN_CHAR_FORWARD_SELECT:
491                 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
492                 cur.autocorrect() = false;
493                 cur.clearTargetX();
494                 cur.macroModeClose();
495                 if (reverseDirectionNeeded(cur))
496                         goto goto_char_backwards;
497
498 goto_char_forwards:
499                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
500                         cur.pushLeft(*cur.nextAtom().nucleus());
501                         cur.inset().idxFirst(cur);
502                 } else if (cur.posRight() || idxRight(cur)
503                         || cur.popRight() || cur.selection())
504                         ;
505                 else {
506                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
507                         cur.undispatched();
508                 }
509                 break;
510
511         case LFUN_CHAR_BACKWARD:
512                 cur.updateFlags(Update::Decoration | Update::FitCursor);
513         case LFUN_CHAR_BACKWARD_SELECT:
514                 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
515                 cur.autocorrect() = false;
516                 cur.clearTargetX();
517                 cur.macroModeClose();
518                 if (reverseDirectionNeeded(cur))
519                         goto goto_char_forwards;
520
521 goto_char_backwards:
522                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
523                         cur.posLeft();
524                         cur.push(*cur.nextAtom().nucleus());
525                         cur.inset().idxLast(cur);
526                 } else if (cur.posLeft() || idxLeft(cur)
527                         || cur.popLeft() || cur.selection())
528                         ;
529                 else {
530                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
531                         cur.undispatched();
532                 }
533                 break;
534
535         case LFUN_UP:
536                 cur.updateFlags(Update::Decoration | Update::FitCursor);
537         case LFUN_UP_SELECT:
538                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
539                 if (cur.inMacroMode()) {
540                         // Make Helge happy
541                         cur.macroModeClose();
542                         break;
543                 }
544                 cur.selHandle(cmd.action == LFUN_UP_SELECT);
545                 if (!cur.up()) {
546                         cmd = FuncRequest(LFUN_FINISHED_UP);
547                         cur.undispatched();
548                 }
549                 // fixes bug 1598. Please check!
550                 cur.normalize();
551                 break;
552
553         case LFUN_DOWN:
554                 cur.updateFlags(Update::Decoration | Update::FitCursor);
555         case LFUN_DOWN_SELECT:
556                 if (cur.inMacroMode()) {
557                         cur.macroModeClose();
558                         break;
559                 }
560                 cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
561                 if (!cur.down()) {
562                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
563                         cur.undispatched();
564                 }
565                 // fixes bug 1598. Please check!
566                 cur.normalize();
567                 break;
568
569         case LFUN_MOUSE_DOUBLE:
570         case LFUN_MOUSE_TRIPLE:
571         case LFUN_WORD_SELECT:
572                 cur.pos() = 0;
573                 cur.idx() = 0;
574                 cur.resetAnchor();
575                 cur.selection() = true;
576                 cur.pos() = cur.lastpos();
577                 cur.idx() = cur.lastidx();
578                 cap::saveSelection(cur);
579                 break;
580
581         case LFUN_PARAGRAPH_UP:
582         case LFUN_PARAGRAPH_DOWN:
583                 cur.updateFlags(Update::Decoration | Update::FitCursor);
584         case LFUN_PARAGRAPH_UP_SELECT:
585         case LFUN_PARAGRAPH_DOWN_SELECT:
586                 break;
587
588         case LFUN_LINE_BEGIN:
589         case LFUN_WORD_BACKWARD:
590                 cur.updateFlags(Update::Decoration | Update::FitCursor);
591         case LFUN_LINE_BEGIN_SELECT:
592         case LFUN_WORD_BACKWARD_SELECT:
593                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
594                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
595                 cur.macroModeClose();
596                 if (cur.pos() != 0) {
597                         cur.pos() = 0;
598                 } else if (cur.col() != 0) {
599                         cur.idx() -= cur.col();
600                         cur.pos() = 0;
601                 } else if (cur.idx() != 0) {
602                         cur.idx() = 0;
603                         cur.pos() = 0;
604                 } else {
605                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
606                         cur.undispatched();
607                 }
608                 break;
609
610         case LFUN_WORD_FORWARD:
611         case LFUN_LINE_END:
612                 cur.updateFlags(Update::Decoration | Update::FitCursor);
613         case LFUN_WORD_FORWARD_SELECT:
614         case LFUN_LINE_END_SELECT:
615                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
616                                 cmd.action == LFUN_LINE_END_SELECT);
617                 cur.macroModeClose();
618                 cur.clearTargetX();
619                 if (cur.pos() != cur.lastpos()) {
620                         cur.pos() = cur.lastpos();
621                 } else if (ncols() && (cur.col() != cur.lastcol())) {
622                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
623                         cur.pos() = cur.lastpos();
624                 } else if (cur.idx() != cur.lastidx()) {
625                         cur.idx() = cur.lastidx();
626                         cur.pos() = cur.lastpos();
627                 } else {
628                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
629                         cur.undispatched();
630                 }
631                 break;
632
633         case LFUN_SCREEN_UP_SELECT:
634         case LFUN_SCREEN_UP:
635                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
636                 cur.undispatched();
637                 break;
638
639         case LFUN_SCREEN_DOWN_SELECT:
640         case LFUN_SCREEN_DOWN:
641                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
642                 cur.undispatched();
643                 break;
644
645         case LFUN_CELL_FORWARD:
646                 cur.updateFlags(Update::Decoration | Update::FitCursor);
647                 cur.inset().idxNext(cur);
648                 break;
649
650         case LFUN_CELL_BACKWARD:
651                 cur.updateFlags(Update::Decoration | Update::FitCursor);
652                 cur.inset().idxPrev(cur);
653                 break;
654
655         case LFUN_WORD_DELETE_BACKWARD:
656         case LFUN_CHAR_DELETE_BACKWARD:
657                 if (cur.pos() == 0)
658                         // May affect external cell:
659                         recordUndoInset(cur, Undo::ATOMIC);
660                 else
661                         recordUndo(cur, Undo::ATOMIC);
662                 // if the inset can not be removed from within, delete it
663                 if (!cur.backspace()) {
664                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
665                         cur.innerText()->dispatch(cur, cmd);
666                 }
667                 break;
668
669         case LFUN_WORD_DELETE_FORWARD:
670         case LFUN_CHAR_DELETE_FORWARD:
671                 if (cur.pos() == cur.lastpos())
672                         // May affect external cell:
673                         recordUndoInset(cur, Undo::ATOMIC);
674                 else
675                         recordUndo(cur, Undo::ATOMIC);
676                 // if the inset can not be removed from within, delete it
677                 if (!cur.erase()) {
678                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
679                         cur.innerText()->dispatch(cur, cmd);
680                 }
681                 break;
682
683         case LFUN_ESCAPE:
684                 if (cur.selection())
685                         cur.clearSelection();
686                 else  {
687                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
688                         cur.undispatched();
689                 }
690                 break;
691
692         case LFUN_INSET_TOGGLE:
693                 recordUndo(cur);
694                 lock(!lock());
695                 cur.popRight();
696                 break;
697
698         case LFUN_SELF_INSERT:
699                 if (cmd.argument().size() != 1) {
700                         recordUndo(cur);
701                         docstring const arg = cmd.argument();
702                         if (!interpretString(cur, arg))
703                                 cur.insert(arg);
704                         break;
705                 }
706                 // Don't record undo steps if we are in macro mode and
707                 // cmd.argument is the next character of the macro name.
708                 // Otherwise we'll get an invalid cursor if we undo after
709                 // the macro was finished and the macro is a known command,
710                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
711                 // the InsetMathUnknown with name "frac" by an empty
712                 // InsetMathFrac -> a pos value > 0 is invalid.
713                 // A side effect is that an undo before the macro is finished
714                 // undoes the complete macro, not only the last character.
715                 if (!cur.inMacroMode())
716                         recordUndo(cur);
717
718                 // spacial handling of space. If we insert an inset
719                 // via macro mode, we want to put the cursor inside it
720                 // if relevant. Think typing "\frac<space>".
721                 if (cmd.argument()[0] == ' '
722                     && cur.inMacroMode() && cur.macroName() != "\\"
723                     && cur.macroModeClose()) {
724                         MathAtom const atom = cur.prevAtom();
725                         if (atom->asNestInset() && atom->nargs() > 0) {
726                                 cur.posLeft();
727                                 cur.pushLeft(*cur.nextInset());
728                         }
729                 } else if (!interpretChar(cur, cmd.argument()[0])) {
730                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
731                         cur.undispatched();
732                 }
733                 break;
734
735         //case LFUN_SERVER_GET_XY:
736         //      sprintf(dispatch_buffer, "%d %d",);
737         //      break;
738
739         case LFUN_SERVER_SET_XY: {
740                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
741                 int x = 0;
742                 int y = 0;
743                 istringstream is(to_utf8(cmd.argument()));
744                 is >> x >> y;
745                 cur.setScreenPos(x, y);
746                 break;
747         }
748
749         // Special casing for superscript in case of LyX handling
750         // dead-keys:
751         case LFUN_ACCENT_CIRCUMFLEX:
752                 if (cmd.argument().empty()) {
753                         // do superscript if LyX handles
754                         // deadkeys
755                         recordUndo(cur, Undo::ATOMIC);
756                         script(cur, true, grabAndEraseSelection(cur));
757                 }
758                 break;
759
760         case LFUN_ACCENT_UMLAUT:
761         case LFUN_ACCENT_ACUTE:
762         case LFUN_ACCENT_GRAVE:
763         case LFUN_ACCENT_BREVE:
764         case LFUN_ACCENT_DOT:
765         case LFUN_ACCENT_MACRON:
766         case LFUN_ACCENT_CARON:
767         case LFUN_ACCENT_TILDE:
768         case LFUN_ACCENT_CEDILLA:
769         case LFUN_ACCENT_CIRCLE:
770         case LFUN_ACCENT_UNDERDOT:
771         case LFUN_ACCENT_TIE:
772         case LFUN_ACCENT_OGONEK:
773         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
774                 break;
775
776         //  Math fonts
777         case LFUN_FONT_FREE_APPLY:
778         case LFUN_FONT_FREE_UPDATE:
779                 handleFont2(cur, cmd.argument());
780                 break;
781
782         case LFUN_FONT_BOLD:
783                 if (currentMode() == TEXT_MODE)
784                         handleFont(cur, cmd.argument(), "textbf");
785                 else
786                         handleFont(cur, cmd.argument(), "mathbf");
787                 break;
788         case LFUN_FONT_SANS:
789                 if (currentMode() == TEXT_MODE)
790                         handleFont(cur, cmd.argument(), "textsf");
791                 else
792                         handleFont(cur, cmd.argument(), "mathsf");
793                 break;
794         case LFUN_FONT_EMPH:
795                 if (currentMode() == TEXT_MODE)
796                         handleFont(cur, cmd.argument(), "emph");
797                 else
798                         handleFont(cur, cmd.argument(), "mathcal");
799                 break;
800         case LFUN_FONT_ROMAN:
801                 if (currentMode() == TEXT_MODE)
802                         handleFont(cur, cmd.argument(), "textrm");
803                 else
804                         handleFont(cur, cmd.argument(), "mathrm");
805                 break;
806         case LFUN_FONT_CODE:
807                 if (currentMode() == TEXT_MODE)
808                         handleFont(cur, cmd.argument(), "texttt");
809                 else
810                         handleFont(cur, cmd.argument(), "mathtt");
811                 break;
812         case LFUN_FONT_FRAK:
813                 handleFont(cur, cmd.argument(), "mathfrak");
814                 break;
815         case LFUN_FONT_ITAL:
816                 if (currentMode() == TEXT_MODE)
817                         handleFont(cur, cmd.argument(), "textit");
818                 else
819                         handleFont(cur, cmd.argument(), "mathit");
820                 break;
821         case LFUN_FONT_NOUN:
822                 if (currentMode() == TEXT_MODE)
823                         // FIXME: should be "noun"
824                         handleFont(cur, cmd.argument(), "textsc");
825                 else
826                         handleFont(cur, cmd.argument(), "mathbb");
827                 break;
828         /*
829         case LFUN_FONT_FREE_APPLY:
830                 handleFont(cur, cmd.argument(), "textrm");
831                 break;
832         */
833         case LFUN_FONT_DEFAULT:
834                 handleFont(cur, cmd.argument(), "textnormal");
835                 break;
836
837         case LFUN_MATH_MODE: {
838 #if 1
839                 // ignore math-mode on when already in math mode
840                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
841                         break;
842                 cur.macroModeClose();
843                 docstring const save_selection = grabAndEraseSelection(cur);
844                 selClearOrDel(cur);
845                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
846                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
847                 cur.posLeft();
848                 cur.pushLeft(*cur.nextInset());
849                 cur.niceInsert(save_selection);
850 #else
851                 if (currentMode() == Inset::TEXT_MODE) {
852                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
853                         cur.message(_("create new math text environment ($...$)"));
854                 } else {
855                         handleFont(cur, cmd.argument(), "textrm");
856                         cur.message(_("entered math text mode (textrm)"));
857                 }
858 #endif
859                 break;
860         }
861
862         case LFUN_MATH_SIZE:
863 #if 0
864                 recordUndo(cur);
865                 cur.setSize(arg);
866 #endif
867                 break;
868
869         case LFUN_MATH_MATRIX: {
870                 recordUndo(cur, Undo::ATOMIC);
871                 unsigned int m = 1;
872                 unsigned int n = 1;
873                 docstring v_align;
874                 docstring h_align;
875                 idocstringstream is(cmd.argument());
876                 is >> m >> n >> v_align >> h_align;
877                 if (m < 1)
878                         m = 1;
879                 if (n < 1)
880                         n = 1;
881                 v_align += 'c';
882                 cur.niceInsert(
883                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
884                 break;
885         }
886
887         case LFUN_MATH_DELIM: {
888                 docstring ls;
889                 docstring rs = support::split(cmd.argument(), ls, ' ');
890                 // Reasonable default values
891                 if (ls.empty())
892                         ls = '(';
893                 if (rs.empty())
894                         rs = ')';
895                 recordUndo(cur, Undo::ATOMIC);
896                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
897                 break;
898         }
899
900         case LFUN_MATH_BIGDELIM: {
901                 docstring const lname  = from_utf8(cmd.getArg(0));
902                 docstring const ldelim = from_utf8(cmd.getArg(1));
903                 docstring const rname  = from_utf8(cmd.getArg(2));
904                 docstring const rdelim = from_utf8(cmd.getArg(3));
905                 latexkeys const * l = in_word_set(lname);
906                 bool const have_l = l && l->inset == "big" &&
907                                     InsetMathBig::isBigInsetDelim(ldelim);
908                 l = in_word_set(rname);
909                 bool const have_r = l && l->inset == "big" &&
910                                     InsetMathBig::isBigInsetDelim(rdelim);
911                 // We mimic LFUN_MATH_DELIM in case we have an empty left
912                 // or right delimiter.
913                 if (have_l || have_r) {
914                         recordUndo(cur, Undo::ATOMIC);
915                         docstring const selection = grabAndEraseSelection(cur);
916                         selClearOrDel(cur);
917                         if (have_l)
918                                 cur.insert(MathAtom(new InsetMathBig(lname,
919                                                                 ldelim)));
920                         cur.niceInsert(selection);
921                         if (have_r)
922                                 cur.insert(MathAtom(new InsetMathBig(rname,
923                                                                 rdelim)));
924                 }
925                 // Don't call cur.undispatched() if we did nothing, this would
926                 // lead to infinite recursion via Text::dispatch().
927                 break;
928         }
929
930         case LFUN_SPACE_INSERT:
931         case LFUN_MATH_SPACE:
932                 recordUndo(cur, Undo::ATOMIC);
933                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
934                 break;
935
936         case LFUN_ERT_INSERT:
937                 // interpret this as if a backslash was typed
938                 recordUndo(cur, Undo::ATOMIC);
939                 interpretChar(cur, '\\');
940                 break;
941
942         case LFUN_MATH_SUBSCRIPT:
943                 // interpret this as if a _ was typed
944                 recordUndo(cur, Undo::ATOMIC);
945                 interpretChar(cur, '_');
946                 break;
947
948         case LFUN_MATH_SUPERSCRIPT:
949                 // interpret this as if a ^ was typed
950                 recordUndo(cur, Undo::ATOMIC);
951                 interpretChar(cur, '^');
952                 break;
953
954         case LFUN_QUOTE_INSERT:
955                 // interpret this as if a straight " was typed
956                 recordUndo(cur, Undo::ATOMIC);
957                 interpretChar(cur, '\"');
958                 break;
959
960 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
961 // handling such that "self-insert" works on "arbitrary stuff" too, and
962 // math-insert only handles special math things like "matrix".
963         case LFUN_MATH_INSERT: {
964                 recordUndo(cur, Undo::ATOMIC);
965                 if (cmd.argument() == "^" || cmd.argument() == "_") {
966                         interpretChar(cur, cmd.argument()[0]);
967                 } else
968                         cur.niceInsert(cmd.argument());
969                 break;
970                 }
971
972         case LFUN_DIALOG_SHOW_NEW_INSET: {
973                 docstring const & name = cmd.argument();
974                 string data;
975                 if (name == "ref") {
976                         InsetMathRef tmp(name);
977                         data = tmp.createDialogStr(to_utf8(name));
978                 }
979                 cur.bv().showInsetDialog(to_utf8(name), data, 0);
980                 break;
981         }
982
983         case LFUN_INSET_INSERT: {
984                 MathData ar;
985                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
986                         recordUndo(cur);
987                         cur.insert(ar);
988                 } else
989                         cur.undispatched();
990                 break;
991         }
992
993         default:
994                 InsetMath::doDispatch(cur, cmd);
995                 break;
996         }
997 }
998
999
1000 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1001                 FuncStatus & flag) const
1002 {
1003         // the font related toggles
1004         //string tc = "mathnormal";
1005         bool ret = true;
1006         string const arg = to_utf8(cmd.argument());
1007         switch (cmd.action) {
1008         case LFUN_TABULAR_FEATURE:
1009                 flag.enabled(false);
1010                 break;
1011 #if 0
1012         case LFUN_TABULAR_FEATURE:
1013                 // FIXME: check temporarily disabled
1014                 // valign code
1015                 char align = mathcursor::valign();
1016                 if (align == '\0') {
1017                         enable = false;
1018                         break;
1019                 }
1020                 if (cmd.argument().empty()) {
1021                         flag.clear();
1022                         break;
1023                 }
1024                 if (!contains("tcb", cmd.argument()[0])) {
1025                         enable = false;
1026                         break;
1027                 }
1028                 flag.setOnOff(cmd.argument()[0] == align);
1029                 break;
1030 #endif
1031         /// We have to handle them since 1.4 blocks all unhandled actions
1032         case LFUN_FONT_ITAL:
1033         case LFUN_FONT_BOLD:
1034         case LFUN_FONT_SANS:
1035         case LFUN_FONT_EMPH:
1036         case LFUN_FONT_CODE:
1037         case LFUN_FONT_NOUN:
1038         case LFUN_FONT_ROMAN:
1039         case LFUN_FONT_DEFAULT:
1040                 flag.enabled(true);
1041                 break;
1042         case LFUN_MATH_MUTATE:
1043                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1044                 flag.setOnOff(false);
1045                 break;
1046
1047         // we just need to be in math mode to enable that
1048         case LFUN_MATH_SIZE:
1049         case LFUN_MATH_SPACE:
1050         case LFUN_MATH_LIMITS:
1051         case LFUN_MATH_NONUMBER:
1052         case LFUN_MATH_NUMBER:
1053         case LFUN_MATH_EXTERN:
1054                 flag.enabled(true);
1055                 break;
1056
1057         case LFUN_FONT_FRAK:
1058                 flag.enabled(currentMode() != TEXT_MODE);
1059                 break;
1060
1061         case LFUN_MATH_INSERT: {
1062                 bool const textarg =
1063                         arg == "\\textbf"   || arg == "\\textsf" ||
1064                         arg == "\\textrm"   || arg == "\\textmd" ||
1065                         arg == "\\textit"   || arg == "\\textsc" ||
1066                         arg == "\\textsl"   || arg == "\\textup" ||
1067                         arg == "\\texttt"   || arg == "\\textbb" ||
1068                         arg == "\\textnormal";
1069                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1070                 break;
1071         }
1072
1073         case LFUN_MATH_MATRIX:
1074                 flag.enabled(currentMode() == MATH_MODE);
1075                 break;
1076
1077         case LFUN_INSET_INSERT: {
1078                 // Don't test createMathInset_fromDialogStr(), since
1079                 // getStatus is not called with a valid reference and the
1080                 // dialog would not be applyable.
1081                 string const name = cmd.getArg(0);
1082                 flag.enabled(name == "ref");
1083                 break;
1084         }
1085
1086         case LFUN_MATH_DELIM:
1087         case LFUN_MATH_BIGDELIM:
1088                 // Don't do this with multi-cell selections
1089                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1090                 break;
1091
1092         case LFUN_HYPHENATION_POINT_INSERT:
1093         case LFUN_LIGATURE_BREAK_INSERT:
1094         case LFUN_MENU_SEPARATOR_INSERT:
1095         case LFUN_DOTS_INSERT:
1096         case LFUN_END_OF_SENTENCE_PERIOD_INSERT:
1097                 // FIXME: These would probably make sense in math-text mode
1098                 flag.enabled(false);
1099                 break;
1100
1101         default:
1102                 ret = false;
1103                 break;
1104         }
1105         return ret;
1106 }
1107
1108
1109 void InsetMathNest::edit(Cursor & cur, bool left)
1110 {
1111         cur.push(*this);
1112         cur.idx() = left ? 0 : cur.lastidx();
1113         cur.pos() = left ? 0 : cur.lastpos();
1114         cur.resetAnchor();
1115         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1116 }
1117
1118
1119 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1120 {
1121         int idx_min = 0;
1122         int dist_min = 1000000;
1123         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1124                 int const d = cell(i).dist(cur.bv(), x, y);
1125                 if (d < dist_min) {
1126                         dist_min = d;
1127                         idx_min = i;
1128                 }
1129         }
1130         MathData & ar = cell(idx_min);
1131         cur.push(*this);
1132         cur.idx() = idx_min;
1133         cur.pos() = ar.x2pos(x - ar.xo(cur.bv()));
1134
1135         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1136         if (dist_min == 0) {
1137                 // hit inside cell
1138                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1139                         if (ar[i]->covers(cur.bv(), x, y))
1140                                 return ar[i].nucleus()->editXY(cur, x, y);
1141         }
1142         return this;
1143 }
1144
1145
1146 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1147 {
1148         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1149         BufferView & bv = cur.bv();
1150         if (cmd.button() == mouse_button::button1) {
1151                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1152                 bv.mouseSetCursor(cur);
1153                 // Update the cursor update flags as needed:
1154                 //
1155                 // Update::Decoration: tells to update the decoration (visual box
1156                 //                     corners that define the inset)/
1157                 // Update::FitCursor: adjust the screen to the cursor position if
1158                 //                    needed
1159                 // cur.result().update(): don't overwrite previously set flags.
1160                 cur.updateFlags(Update::Decoration | Update::FitCursor | cur.result().update());
1161         } else if (cmd.button() == mouse_button::button2) {
1162                 MathData ar;
1163                 if (cap::selection()) {
1164                         // See comment in Text::dispatch why we do this
1165                         cap::copySelectionToStack();
1166                         cmd = FuncRequest(LFUN_PASTE, "0");
1167                         doDispatch(cur, cmd);
1168                 } else
1169                         asArray(theSelection().get(), ar);
1170
1171                 cur.insert(ar);
1172                 bv.mouseSetCursor(cur);
1173         }
1174 }
1175
1176
1177 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1178 {
1179         // only select with button 1
1180         if (cmd.button() == mouse_button::button1) {
1181                 Cursor & bvcur = cur.bv().cursor();
1182                 if (bvcur.anchor_.hasPart(cur)) {
1183                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1184                         bvcur.setCursor(cur);
1185                         bvcur.selection() = true;
1186                         //lyxerr << "MOTION " << bvcur << endl;
1187                 } else
1188                         cur.undispatched();
1189         }
1190 }
1191
1192
1193 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1194 {
1195         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1196
1197         if (cmd.button() == mouse_button::button1) {
1198                 if (!cur.selection())
1199                         cur.noUpdate();
1200                 else {
1201                         Cursor & bvcur = cur.bv().cursor();
1202                         bvcur.selection() = true;
1203                         cap::saveSelection(bvcur);
1204                 }
1205                 return;
1206         }
1207
1208         cur.undispatched();
1209 }
1210
1211
1212 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1213 {
1214         //lyxerr << "interpret 2: '" << c << "'" << endl;
1215         docstring save_selection;
1216         if (c == '^' || c == '_')
1217                 save_selection = grabAndEraseSelection(cur);
1218
1219         cur.clearTargetX();
1220
1221         // handle macroMode
1222         if (cur.inMacroMode()) {
1223                 docstring name = cur.macroName();
1224
1225                 /// are we currently typing '#1' or '#2' or...?
1226                 if (name == "\\#") {
1227                         cur.backspace();
1228                         int n = c - '0';
1229                         if (n >= 1 && n <= 9)
1230                                 cur.insert(new MathMacroArgument(n));
1231                         return true;
1232                 }
1233
1234                 if (isAlphaASCII(c)) {
1235                         cur.activeMacro()->setName(name + docstring(1, c));
1236                         return true;
1237                 }
1238
1239                 // handle 'special char' macros
1240                 if (name == "\\") {
1241                         // remove the '\\'
1242                         if (c == '\\') {
1243                                 cur.backspace();
1244                                 if (currentMode() == InsetMath::TEXT_MODE)
1245                                         cur.niceInsert(createInsetMath("textbackslash"));
1246                                 else
1247                                         cur.niceInsert(createInsetMath("backslash"));
1248                         } else if (c == '{') {
1249                                 cur.backspace();
1250                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1251                         } else if (c == '%') {
1252                                 cur.backspace();
1253                                 cur.niceInsert(MathAtom(new InsetMathComment));
1254                         } else if (c == '#') {
1255                                 BOOST_ASSERT(cur.activeMacro());
1256                                 cur.activeMacro()->setName(name + docstring(1, c));
1257                         } else {
1258                                 cur.backspace();
1259                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1260                         }
1261                         return true;
1262                 }
1263
1264                 // One character big delimiters. The others are handled in
1265                 // interpretString().
1266                 latexkeys const * l = in_word_set(name.substr(1));
1267                 if (name[0] == '\\' && l && l->inset == "big") {
1268                         docstring delim;
1269                         switch (c) {
1270                         case '{':
1271                                 delim = from_ascii("\\{");
1272                                 break;
1273                         case '}':
1274                                 delim = from_ascii("\\}");
1275                                 break;
1276                         default:
1277                                 delim = docstring(1, c);
1278                                 break;
1279                         }
1280                         if (InsetMathBig::isBigInsetDelim(delim)) {
1281                                 // name + delim ared a valid InsetMathBig.
1282                                 // We can't use cur.macroModeClose() because
1283                                 // it does not handle delim.
1284                                 InsetMathUnknown * p = cur.activeMacro();
1285                                 p->finalize();
1286                                 --cur.pos();
1287                                 cur.cell().erase(cur.pos());
1288                                 cur.plainInsert(MathAtom(
1289                                         new InsetMathBig(name.substr(1), delim)));
1290                                 return true;
1291                         }
1292                 }
1293
1294                 // leave macro mode and try again if necessary
1295                 cur.macroModeClose();
1296                 if (c == '{')
1297                         cur.niceInsert(MathAtom(new InsetMathBrace));
1298                 else if (c != ' ')
1299                         interpretChar(cur, c);
1300                 return true;
1301         }
1302
1303         // This is annoying as one has to press <space> far too often.
1304         // Disable it.
1305
1306 #if 0
1307                 // leave autocorrect mode if necessary
1308                 if (autocorrect() && c == ' ') {
1309                         autocorrect() = false;
1310                         return true;
1311                 }
1312 #endif
1313
1314         // just clear selection on pressing the space bar
1315         if (cur.selection() && c == ' ') {
1316                 cur.selection() = false;
1317                 return true;
1318         }
1319
1320         selClearOrDel(cur);
1321
1322         if (c == '\\') {
1323                 //lyxerr << "starting with macro" << endl;
1324                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1325                 return true;
1326         }
1327
1328         if (c == '\n') {
1329                 if (currentMode() == InsetMath::TEXT_MODE)
1330                         cur.insert(c);
1331                 return true;
1332         }
1333
1334         if (c == ' ') {
1335                 if (currentMode() == InsetMath::TEXT_MODE) {
1336                         // insert spaces in text mode,
1337                         // but suppress direct insertion of two spaces in a row
1338                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1339                         // it is better than nothing...
1340                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1341                                 cur.insert(c);
1342                                 // FIXME: we have to enable full redraw here because of the
1343                                 // visual box corners that define the inset. If we know for
1344                                 // sure that we stay within the same cell we can optimize for
1345                                 // that using:
1346                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1347                         }
1348                         return true;
1349                 }
1350                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1351                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1352                         // FIXME: we have to enable full redraw here because of the
1353                         // visual box corners that define the inset. If we know for
1354                         // sure that we stay within the same cell we can optimize for
1355                         // that using:
1356                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1357                         return true;
1358                 }
1359
1360                 if (cur.popRight()) {
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::FitCursor);
1366                         return true;
1367                 }
1368
1369                 // if we are at the very end, leave the formula
1370                 return cur.pos() != cur.lastpos();
1371         }
1372
1373         // These shouldn't work in text mode:
1374         if (currentMode() != InsetMath::TEXT_MODE) {
1375                 if (c == '_') {
1376                         script(cur, false, save_selection);
1377                         return true;
1378                 }
1379                 if (c == '^') {
1380                         script(cur, true, save_selection);
1381                         return true;
1382                 }
1383                 if (c == '~') {
1384                         cur.niceInsert(createInsetMath("sim"));
1385                         return true;
1386                 }
1387         }
1388
1389         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1390             c == '%' || c == '_' || c == '^') {
1391                 cur.niceInsert(createInsetMath(docstring(1, c)));
1392                 return true;
1393         }
1394
1395
1396         // try auto-correction
1397         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1398         //      return true;
1399
1400         // no special circumstances, so insert the character without any fuss
1401         cur.insert(c);
1402         cur.autocorrect() = true;
1403         return true;
1404 }
1405
1406
1407 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1408 {
1409         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1410         // possible
1411         if (!cur.empty() && cur.pos() > 0 &&
1412             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1413                 if (InsetMathBig::isBigInsetDelim(str)) {
1414                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1415                         if (prev[0] == '\\') {
1416                                 prev = prev.substr(1);
1417                                 latexkeys const * l = in_word_set(prev);
1418                                 if (l && l->inset == "big") {
1419                                         cur.cell()[cur.pos() - 1] =
1420                                                 MathAtom(new InsetMathBig(prev, str));
1421                                         return true;
1422                                 }
1423                         }
1424                 }
1425         }
1426         return false;
1427 }
1428
1429
1430 bool InsetMathNest::script(Cursor & cur, bool up,
1431                 docstring const & save_selection)
1432 {
1433         // Hack to get \^ and \_ working
1434         //lyxerr << "handling script: up: " << up << endl;
1435         if (cur.inMacroMode() && cur.macroName() == "\\") {
1436                 if (up)
1437                         cur.niceInsert(createInsetMath("mathcircumflex"));
1438                 else
1439                         interpretChar(cur, '_');
1440                 return true;
1441         }
1442
1443         cur.macroModeClose();
1444         if (asScriptInset() && cur.idx() == 0) {
1445                 // we are in a nucleus of a script inset, move to _our_ script
1446                 InsetMathScript * inset = asScriptInset();
1447                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1448                 inset->ensure(up);
1449                 cur.idx() = inset->idxOfScript(up);
1450                 cur.pos() = 0;
1451         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1452                 --cur.pos();
1453                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1454                 cur.push(*inset);
1455                 inset->ensure(up);
1456                 cur.idx() = inset->idxOfScript(up);
1457                 cur.pos() = cur.lastpos();
1458         } else {
1459                 // convert the thing to our left to a scriptinset or create a new
1460                 // one if in the very first position of the array
1461                 if (cur.pos() == 0) {
1462                         //lyxerr << "new scriptinset" << endl;
1463                         cur.insert(new InsetMathScript(up));
1464                 } else {
1465                         //lyxerr << "converting prev atom " << endl;
1466                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1467                 }
1468                 --cur.pos();
1469                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1470                 // See comment in MathParser.cpp for special handling of {}-bases
1471
1472                 cur.push(*inset);
1473                 cur.idx() = 1;
1474                 cur.pos() = 0;
1475         }
1476         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1477         cur.niceInsert(save_selection);
1478         cur.resetAnchor();
1479         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1480         return true;
1481 }
1482
1483
1484 } // namespace lyx