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