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