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