]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.cpp
* BufferView: Make use of ScreenUpdateStrategy::NoScreenUpdate, avoid a screen redraw...
[features.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "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 "debug.h"
42 #include "DispatchResult.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "LyXFunc.h"
46 #include "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
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(&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                 Dimension dim;
152                 cell(i).metrics(m, dim);
153         }
154 }
155
156
157 bool InsetMathNest::idxNext(Cursor & cur) const
158 {
159         BOOST_ASSERT(&cur.inset() == this);
160         if (cur.idx() == cur.lastidx())
161                 return false;
162         ++cur.idx();
163         cur.pos() = 0;
164         return true;
165 }
166
167
168 bool InsetMathNest::idxForward(Cursor & cur) const
169 {
170         return idxNext(cur);
171 }
172
173
174 bool InsetMathNest::idxPrev(Cursor & cur) const
175 {
176         BOOST_ASSERT(&cur.inset() == this);
177         if (cur.idx() == 0)
178                 return false;
179         --cur.idx();
180         cur.pos() = cur.lastpos();
181         return true;
182 }
183
184
185 bool InsetMathNest::idxBackward(Cursor & cur) const
186 {
187         return idxPrev(cur);
188 }
189
190
191 bool InsetMathNest::idxFirst(Cursor & cur) const
192 {
193         BOOST_ASSERT(&cur.inset() == this);
194         if (nargs() == 0)
195                 return false;
196         cur.idx() = 0;
197         cur.pos() = 0;
198         return true;
199 }
200
201
202 bool InsetMathNest::idxLast(Cursor & cur) const
203 {
204         BOOST_ASSERT(&cur.inset() == this);
205         if (nargs() == 0)
206                 return false;
207         cur.idx() = cur.lastidx();
208         cur.pos() = cur.lastpos();
209         return true;
210 }
211
212
213 void InsetMathNest::dump() const
214 {
215         odocstringstream oss;
216         WriteStream os(oss);
217         os << "---------------------------------------------\n";
218         write(os);
219         os << "\n";
220         for (idx_type i = 0, n = nargs(); i != n; ++i)
221                 os << cell(i) << "\n";
222         os << "---------------------------------------------\n";
223         lyxerr << to_utf8(oss.str());
224 }
225
226
227 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
228 {
229 #if 0
230         if (lock_)
231                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
232                                         Color_mathlockbg);
233 #endif
234         setPosCache(pi, x, y);
235 }
236
237
238 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
239 {
240         BufferView & bv = *pi.base.bv;
241         // this should use the x/y values given, not the cached values
242         Cursor & cur = bv.cursor();
243         if (!cur.selection())
244                 return;
245         if (&cur.inset() != this)
246                 return;
247
248         // FIXME: hack to get position cache warm
249         bool const original_drawing_state = pi.pain.isDrawingEnabled();
250         pi.pain.setDrawingEnabled(false);
251         draw(pi, x, y);
252         pi.pain.setDrawingEnabled(original_drawing_state);
253
254         CursorSlice s1 = cur.selBegin();
255         CursorSlice s2 = cur.selEnd();
256
257         //lyxerr << "InsetMathNest::drawing selection: "
258         //      << " s1: " << s1 << " s2: " << s2 << endl;
259         if (s1.idx() == s2.idx()) {
260                 MathData const & c = cell(s1.idx());
261                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
262                 int x1 = g.pos.x_ + c.pos2x(s1.pos());
263                 int y1 = g.pos.y_ - g.dim.ascent();
264                 int x2 = g.pos.x_ + c.pos2x(s2.pos());
265                 int y2 = g.pos.y_ + g.dim.descent();
266                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
267         //lyxerr << "InsetMathNest::drawing selection 3: "
268         //      << " x1: " << x1 << " x2: " << x2
269         //      << " y1: " << y1 << " y2: " << y2 << endl;
270         } else {
271                 for (idx_type i = 0; i < nargs(); ++i) {
272                         if (idxBetween(i, s1.idx(), s2.idx())) {
273                                 MathData const & c = cell(i);
274                                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
275                                 int x1 = g.pos.x_;
276                                 int y1 = g.pos.y_ - g.dim.ascent();
277                                 int x2 = g.pos.x_ + g.dim.width();
278                                 int y2 = g.pos.y_ + g.dim.descent();
279                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
280                         }
281                 }
282         }
283 }
284
285
286 void InsetMathNest::validate(LaTeXFeatures & features) const
287 {
288         for (idx_type i = 0; i < nargs(); ++i)
289                 cell(i).validate(features);
290 }
291
292
293 void InsetMathNest::replace(ReplaceData & rep)
294 {
295         for (idx_type i = 0; i < nargs(); ++i)
296                 cell(i).replace(rep);
297 }
298
299
300 bool InsetMathNest::contains(MathData const & ar) const
301 {
302         for (idx_type i = 0; i < nargs(); ++i)
303                 if (cell(i).contains(ar))
304                         return true;
305         return false;
306 }
307
308
309 bool InsetMathNest::lock() const
310 {
311         return lock_;
312 }
313
314
315 void InsetMathNest::lock(bool l)
316 {
317         lock_ = l;
318 }
319
320
321 bool InsetMathNest::isActive() const
322 {
323         return nargs() > 0;
324 }
325
326
327 MathData InsetMathNest::glue() const
328 {
329         MathData ar;
330         for (size_t i = 0; i < nargs(); ++i)
331                 ar.append(cell(i));
332         return ar;
333 }
334
335
336 void InsetMathNest::write(WriteStream & os) const
337 {
338         os << '\\' << name().c_str();
339         for (size_t i = 0; i < nargs(); ++i)
340                 os << '{' << cell(i) << '}';
341         if (nargs() == 0)
342                 os.pendingSpace(true);
343         if (lock_ && !os.latex()) {
344                 os << "\\lyxlock";
345                 os.pendingSpace(true);
346         }
347 }
348
349
350 void InsetMathNest::normalize(NormalStream & os) const
351 {
352         os << '[' << name().c_str();
353         for (size_t i = 0; i < nargs(); ++i)
354                 os << ' ' << cell(i);
355         os << ']';
356 }
357
358
359 int InsetMathNest::latex(Buffer const &, odocstream & os,
360                         OutputParams const & runparams) const
361 {
362         WriteStream wi(os, runparams.moving_arg, true);
363         write(wi);
364         return wi.line();
365 }
366
367
368 bool InsetMathNest::setMouseHover(bool mouse_hover)
369 {
370         mouse_hover_ = mouse_hover;
371         return true;
372 }
373
374
375 bool InsetMathNest::notifyCursorLeaves(Cursor & /*cur*/)
376 {
377         // FIXME: look here
378 #if 0
379         MathData & ar = cur.cell();
380         // remove base-only "scripts"
381         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
382                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
383                 if (p && p->nargs() == 1) {
384                         MathData ar = p->nuc();
385                         erase(i);
386                         insert(i, ar);
387                         cur.adjust(i, ar.size() - 1);
388                 }
389         }
390
391         // glue adjacent font insets of the same kind
392         for (pos_type i = 0; i + 1 < size(); ++i) {
393                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
394                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
395                 if (p && q && p->name() == q->name()) {
396                         p->cell(0).append(q->cell(0));
397                         erase(i + 1);
398                         cur.adjust(i, -1);
399                 }
400         }
401 #endif
402         return false;
403 }
404
405
406 void InsetMathNest::handleFont
407         (Cursor & cur, docstring const & arg, char const * const font)
408 {
409         handleFont(cur, arg, from_ascii(font));
410 }
411
412
413 void InsetMathNest::handleFont
414         (Cursor & cur, docstring const & arg, docstring const & font)
415 {
416         // this whole function is a hack and won't work for incremental font
417         // changes...
418
419         if (cur.inset().asInsetMath()->name() == font) {
420                 cur.recordUndoInset();
421                 cur.handleFont(to_utf8(font));
422         } else {
423                 cur.recordUndo();
424                 cur.handleNest(createInsetMath(font));
425                 cur.insert(arg);
426         }
427 }
428
429
430 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
431 {
432         cur.recordUndo();
433         Font font;
434         bool b;
435         font.fromString(to_utf8(arg), b);
436         if (font.fontInfo().color() != Color_inherit) {
437                 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
438                 cur.handleNest(at, 0);
439         }
440 }
441
442
443 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
444 {
445         //lyxerr << "InsetMathNest: request: " << cmd << std::endl;
446         //CursorSlice sl = cur.current();
447
448         switch (cmd.action) {
449
450         case LFUN_PASTE: {
451                 cur.recordUndo();
452                 cur.message(_("Paste"));
453                 replaceSelection(cur);
454                 docstring topaste;
455                 if (cmd.argument().empty() && !theClipboard().isInternal())
456                         topaste = theClipboard().getAsText();
457                 else {
458                         size_t n = 0;
459                         idocstringstream is(cmd.argument());
460                         is >> n;
461                         topaste = cap::getSelection(cur.buffer(), n);
462                 }
463                 cur.niceInsert(topaste);
464                 cur.clearSelection(); // bug 393
465                 cur.finishUndo();
466                 break;
467         }
468
469         case LFUN_CUT:
470                 cur.recordUndo();
471                 cutSelection(cur, true, true);
472                 cur.message(_("Cut"));
473                 // Prevent stale position >= size crash
474                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
475                 cur.normalize();
476                 break;
477
478         case LFUN_COPY:
479                 copySelection(cur);
480                 cur.message(_("Copy"));
481                 break;
482
483         case LFUN_MOUSE_PRESS:
484                 lfunMousePress(cur, cmd);
485                 break;
486
487         case LFUN_MOUSE_MOTION:
488                 lfunMouseMotion(cur, cmd);
489                 break;
490
491         case LFUN_MOUSE_RELEASE:
492                 lfunMouseRelease(cur, cmd);
493                 break;
494
495         case LFUN_FINISHED_BACKWARD:
496                 cur.bv().cursor() = cur;
497                 break;
498
499         case LFUN_FINISHED_FORWARD:
500                 ++cur.pos();
501                 cur.bv().cursor() = cur;
502                 break;
503
504         case LFUN_CHAR_FORWARD:
505                 cur.updateFlags(Update::Decoration | Update::FitCursor);
506         case LFUN_CHAR_FORWARD_SELECT:
507                 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
508                 cur.autocorrect() = false;
509                 cur.clearTargetX();
510                 cur.macroModeClose();
511                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
512                         cur.pushBackward(*cur.nextAtom().nucleus());
513                         cur.inset().idxFirst(cur);
514                 } else if (cur.posForward() || idxForward(cur)
515                         || cur.popForward() || cur.selection())
516                         ;
517                 else {
518                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
519                         cur.undispatched();
520                 }
521                 break;
522
523         case LFUN_CHAR_BACKWARD:
524                 cur.updateFlags(Update::Decoration | Update::FitCursor);
525         case LFUN_CHAR_BACKWARD_SELECT:
526                 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
527                 cur.autocorrect() = false;
528                 cur.clearTargetX();
529                 cur.macroModeClose();
530                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
531                         cur.posBackward();
532                         cur.push(*cur.nextAtom().nucleus());
533                         cur.inset().idxLast(cur);
534                 } else if (cur.posBackward() || idxBackward(cur)
535                         || cur.popBackward() || cur.selection())
536                         ;
537                 else {
538                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
539                         cur.undispatched();
540                 }
541                 break;
542
543         case LFUN_CHAR_RIGHT:
544         case LFUN_CHAR_RIGHT_SELECT:
545                 //FIXME: for visual cursor, really move right
546                 if (reverseDirectionNeeded(cur))
547                         doDispatch(cur, FuncRequest(cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
548                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
549                 else 
550                         doDispatch(cur, FuncRequest(cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
551                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
552                 break;
553
554         case LFUN_CHAR_LEFT:
555         case LFUN_CHAR_LEFT_SELECT:
556                 //FIXME: for visual cursor, really move left
557                 if (reverseDirectionNeeded(cur))
558                         doDispatch(cur, FuncRequest(cmd.action == LFUN_CHAR_LEFT_SELECT ? 
559                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD));
560                 else 
561                         doDispatch(cur, FuncRequest(cmd.action == LFUN_CHAR_LEFT_SELECT ? 
562                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD));
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         case LFUN_INSET_TOGGLE:
728                 cur.recordUndo();
729                 lock(!lock());
730                 cur.popForward();
731                 break;
732
733         case LFUN_SELF_INSERT:
734                 if (cmd.argument().size() != 1) {
735                         cur.recordUndo();
736                         docstring const arg = cmd.argument();
737                         if (!interpretString(cur, arg))
738                                 cur.insert(arg);
739                         break;
740                 }
741                 // Don't record undo steps if we are in macro mode and
742                 // cmd.argument is the next character of the macro name.
743                 // Otherwise we'll get an invalid cursor if we undo after
744                 // the macro was finished and the macro is a known command,
745                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
746                 // the InsetMathUnknown with name "frac" by an empty
747                 // InsetMathFrac -> a pos value > 0 is invalid.
748                 // A side effect is that an undo before the macro is finished
749                 // undoes the complete macro, not only the last character.
750                 if (!cur.inMacroMode())
751                         cur.recordUndo();
752
753                 // spacial handling of space. If we insert an inset
754                 // via macro mode, we want to put the cursor inside it
755                 // if relevant. Think typing "\frac<space>".
756                 if (cmd.argument()[0] == ' '
757                     && cur.inMacroMode() && cur.macroName() != "\\"
758                     && cur.macroModeClose()) {
759                         MathAtom const atom = cur.prevAtom();
760                         if (atom->asNestInset() && atom->isActive()) {
761                                 cur.posBackward();
762                                 cur.pushBackward(*cur.nextInset());
763                         }
764                 } else if (!interpretChar(cur, cmd.argument()[0])) {
765                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
766                         cur.undispatched();
767                 }
768                 break;
769
770         //case LFUN_SERVER_GET_XY:
771         //      sprintf(dispatch_buffer, "%d %d",);
772         //      break;
773
774         case LFUN_SERVER_SET_XY: {
775                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
776                 int x = 0;
777                 int y = 0;
778                 istringstream is(to_utf8(cmd.argument()));
779                 is >> x >> y;
780                 cur.setScreenPos(x, y);
781                 break;
782         }
783
784         // Special casing for superscript in case of LyX handling
785         // dead-keys:
786         case LFUN_ACCENT_CIRCUMFLEX:
787                 if (cmd.argument().empty()) {
788                         // do superscript if LyX handles
789                         // deadkeys
790                         cur.recordUndo();
791                         script(cur, true, grabAndEraseSelection(cur));
792                 }
793                 break;
794
795         case LFUN_ACCENT_UMLAUT:
796         case LFUN_ACCENT_ACUTE:
797         case LFUN_ACCENT_GRAVE:
798         case LFUN_ACCENT_BREVE:
799         case LFUN_ACCENT_DOT:
800         case LFUN_ACCENT_MACRON:
801         case LFUN_ACCENT_CARON:
802         case LFUN_ACCENT_TILDE:
803         case LFUN_ACCENT_CEDILLA:
804         case LFUN_ACCENT_CIRCLE:
805         case LFUN_ACCENT_UNDERDOT:
806         case LFUN_ACCENT_TIE:
807         case LFUN_ACCENT_OGONEK:
808         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
809                 break;
810
811         //  Math fonts
812         case LFUN_FONT_FREE_APPLY:
813         case LFUN_FONT_FREE_UPDATE:
814                 handleFont2(cur, cmd.argument());
815                 break;
816
817         case LFUN_FONT_BOLD:
818                 if (currentMode() == TEXT_MODE)
819                         handleFont(cur, cmd.argument(), "textbf");
820                 else
821                         handleFont(cur, cmd.argument(), "mathbf");
822                 break;
823         case LFUN_FONT_SANS:
824                 if (currentMode() == TEXT_MODE)
825                         handleFont(cur, cmd.argument(), "textsf");
826                 else
827                         handleFont(cur, cmd.argument(), "mathsf");
828                 break;
829         case LFUN_FONT_EMPH:
830                 if (currentMode() == TEXT_MODE)
831                         handleFont(cur, cmd.argument(), "emph");
832                 else
833                         handleFont(cur, cmd.argument(), "mathcal");
834                 break;
835         case LFUN_FONT_ROMAN:
836                 if (currentMode() == TEXT_MODE)
837                         handleFont(cur, cmd.argument(), "textrm");
838                 else
839                         handleFont(cur, cmd.argument(), "mathrm");
840                 break;
841         case LFUN_FONT_TYPEWRITER:
842                 if (currentMode() == TEXT_MODE)
843                         handleFont(cur, cmd.argument(), "texttt");
844                 else
845                         handleFont(cur, cmd.argument(), "mathtt");
846                 break;
847         case LFUN_FONT_FRAK:
848                 handleFont(cur, cmd.argument(), "mathfrak");
849                 break;
850         case LFUN_FONT_ITAL:
851                 if (currentMode() == TEXT_MODE)
852                         handleFont(cur, cmd.argument(), "textit");
853                 else
854                         handleFont(cur, cmd.argument(), "mathit");
855                 break;
856         case LFUN_FONT_NOUN:
857                 if (currentMode() == TEXT_MODE)
858                         // FIXME: should be "noun"
859                         handleFont(cur, cmd.argument(), "textsc");
860                 else
861                         handleFont(cur, cmd.argument(), "mathbb");
862                 break;
863         /*
864         case LFUN_FONT_FREE_APPLY:
865                 handleFont(cur, cmd.argument(), "textrm");
866                 break;
867         */
868         case LFUN_FONT_DEFAULT:
869                 handleFont(cur, cmd.argument(), "textnormal");
870                 break;
871
872         case LFUN_MATH_MODE: {
873 #if 1
874                 // ignore math-mode on when already in math mode
875                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
876                         break;
877                 cur.macroModeClose();
878                 docstring const save_selection = grabAndEraseSelection(cur);
879                 selClearOrDel(cur);
880                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
881                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
882                 cur.posBackward();
883                 cur.pushBackward(*cur.nextInset());
884                 cur.niceInsert(save_selection);
885 #else
886                 if (currentMode() == Inset::TEXT_MODE) {
887                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
888                         cur.message(_("create new math text environment ($...$)"));
889                 } else {
890                         handleFont(cur, cmd.argument(), "textrm");
891                         cur.message(_("entered math text mode (textrm)"));
892                 }
893 #endif
894                 break;
895         }
896
897         case LFUN_MATH_SIZE:
898 #if 0
899                 cur.recordUndo();
900                 cur.setSize(arg);
901 #endif
902                 break;
903
904         case LFUN_MATH_MATRIX: {
905                 cur.recordUndo();
906                 unsigned int m = 1;
907                 unsigned int n = 1;
908                 docstring v_align;
909                 docstring h_align;
910                 idocstringstream is(cmd.argument());
911                 is >> m >> n >> v_align >> h_align;
912                 if (m < 1)
913                         m = 1;
914                 if (n < 1)
915                         n = 1;
916                 v_align += 'c';
917                 cur.niceInsert(
918                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
919                 break;
920         }
921
922         case LFUN_MATH_DELIM: {
923                 docstring ls;
924                 docstring rs = support::split(cmd.argument(), ls, ' ');
925                 // Reasonable default values
926                 if (ls.empty())
927                         ls = '(';
928                 if (rs.empty())
929                         rs = ')';
930                 cur.recordUndo();
931                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
932                 break;
933         }
934
935         case LFUN_MATH_BIGDELIM: {
936                 docstring const lname  = from_utf8(cmd.getArg(0));
937                 docstring const ldelim = from_utf8(cmd.getArg(1));
938                 docstring const rname  = from_utf8(cmd.getArg(2));
939                 docstring const rdelim = from_utf8(cmd.getArg(3));
940                 latexkeys const * l = in_word_set(lname);
941                 bool const have_l = l && l->inset == "big" &&
942                                     InsetMathBig::isBigInsetDelim(ldelim);
943                 l = in_word_set(rname);
944                 bool const have_r = l && l->inset == "big" &&
945                                     InsetMathBig::isBigInsetDelim(rdelim);
946                 // We mimic LFUN_MATH_DELIM in case we have an empty left
947                 // or right delimiter.
948                 if (have_l || have_r) {
949                         cur.recordUndo();
950                         docstring const selection = grabAndEraseSelection(cur);
951                         selClearOrDel(cur);
952                         if (have_l)
953                                 cur.insert(MathAtom(new InsetMathBig(lname,
954                                                                 ldelim)));
955                         cur.niceInsert(selection);
956                         if (have_r)
957                                 cur.insert(MathAtom(new InsetMathBig(rname,
958                                                                 rdelim)));
959                 }
960                 // Don't call cur.undispatched() if we did nothing, this would
961                 // lead to infinite recursion via Text::dispatch().
962                 break;
963         }
964
965         case LFUN_SPACE_INSERT:
966         case LFUN_MATH_SPACE:
967                 cur.recordUndo();
968                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
969                 break;
970
971         case LFUN_ERT_INSERT:
972                 // interpret this as if a backslash was typed
973                 cur.recordUndo();
974                 interpretChar(cur, '\\');
975                 break;
976
977         case LFUN_MATH_SUBSCRIPT:
978                 // interpret this as if a _ was typed
979                 cur.recordUndo();
980                 interpretChar(cur, '_');
981                 break;
982
983         case LFUN_MATH_SUPERSCRIPT:
984                 // interpret this as if a ^ was typed
985                 cur.recordUndo();
986                 interpretChar(cur, '^');
987                 break;
988                 
989         case LFUN_MATH_MACRO_FOLD:
990         case LFUN_MATH_MACRO_UNFOLD: {
991                 Cursor it = cur;
992                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
993                 bool found = findMacroToFoldUnfold(it, fold);
994                 if (found) {
995                         cur.recordUndo();
996                         if (fold)
997                                 it.nextInset()->asInsetMath()->asMacro()->fold(cur);
998                         else
999                                 it.nextInset()->asInsetMath()->asMacro()->unfold(cur);
1000                 }\v
1001                 break;
1002         }
1003
1004         case LFUN_QUOTE_INSERT:
1005                 // interpret this as if a straight " was typed
1006                 cur.recordUndo();
1007                 interpretChar(cur, '\"');
1008                 break;
1009
1010 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1011 // handling such that "self-insert" works on "arbitrary stuff" too, and
1012 // math-insert only handles special math things like "matrix".
1013         case LFUN_MATH_INSERT: {
1014                 cur.recordUndo();
1015                 if (cmd.argument() == "^" || cmd.argument() == "_") {
1016                         interpretChar(cur, cmd.argument()[0]);
1017                 } else
1018                         cur.niceInsert(cmd.argument());
1019                 break;
1020                 }
1021
1022         case LFUN_DIALOG_SHOW_NEW_INSET: {
1023                 docstring const & name = cmd.argument();
1024                 string data;
1025                 if (name == "ref") {
1026                         InsetMathRef tmp(name);
1027                         data = tmp.createDialogStr(to_utf8(name));
1028                 }
1029                 cur.bv().showInsetDialog(to_utf8(name), data, 0);
1030                 break;
1031         }
1032
1033         case LFUN_INSET_INSERT: {
1034                 MathData ar;
1035                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1036                         cur.recordUndo();
1037                         cur.insert(ar);
1038                 } else
1039                         cur.undispatched();
1040                 break;
1041         }
1042         case LFUN_INSET_DISSOLVE:
1043                 if (!asHullInset()) {
1044                         cur.recordUndoInset();
1045                         cur.pullArg();
1046                 }
1047                 break;
1048
1049         default:
1050                 InsetMath::doDispatch(cur, cmd);
1051                 break;
1052         }
1053 }
1054
1055
1056 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1057         // look for macro to open/close, but stay in mathed
1058         for (; !it.empty(); it.pop_back()) {
1059                         
1060                 // go backward through the current cell
1061                 Inset * inset = it.nextInset();
1062                 while (inset && inset->asInsetMath()) {
1063                         MathMacro * macro = inset->asInsetMath()->asMacro();
1064                         if (macro) {
1065                                 // found the an macro to open/close?
1066                                 if (macro->folded() != fold)
1067                                         return true;
1068                                 
1069                                 // Wrong folding state.
1070                                 // If this was the first we see in this slice, look further left,
1071                                 // otherwise go up.
1072                                 if (inset != it.nextInset())
1073                                         break;
1074                         }
1075                         
1076                         // go up if this was the left most position
1077                         if (it.pos() == 0)
1078                                 break;
1079                         
1080                         // go left
1081                         it.pos()--;
1082                         inset = it.nextInset();
1083                 }
1084         }
1085         
1086         return false;
1087 }
1088
1089
1090 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1091                 FuncStatus & flag) const
1092 {
1093         // the font related toggles
1094         //string tc = "mathnormal";
1095         bool ret = true;
1096         string const arg = to_utf8(cmd.argument());
1097         switch (cmd.action) {
1098         case LFUN_TABULAR_FEATURE:
1099                 flag.enabled(false);
1100                 break;
1101 #if 0
1102         case LFUN_TABULAR_FEATURE:
1103                 // FIXME: check temporarily disabled
1104                 // valign code
1105                 char align = mathcursor::valign();
1106                 if (align == '\0') {
1107                         enable = false;
1108                         break;
1109                 }
1110                 if (cmd.argument().empty()) {
1111                         flag.clear();
1112                         break;
1113                 }
1114                 if (!contains("tcb", cmd.argument()[0])) {
1115                         enable = false;
1116                         break;
1117                 }
1118                 flag.setOnOff(cmd.argument()[0] == align);
1119                 break;
1120 #endif
1121         /// We have to handle them since 1.4 blocks all unhandled actions
1122         case LFUN_FONT_ITAL:
1123         case LFUN_FONT_BOLD:
1124         case LFUN_FONT_SANS:
1125         case LFUN_FONT_EMPH:
1126         case LFUN_FONT_TYPEWRITER:
1127         case LFUN_FONT_NOUN:
1128         case LFUN_FONT_ROMAN:
1129         case LFUN_FONT_DEFAULT:
1130                 flag.enabled(true);
1131                 break;
1132         case LFUN_MATH_MUTATE:
1133                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1134                 flag.setOnOff(false);
1135                 break;
1136
1137         // we just need to be in math mode to enable that
1138         case LFUN_MATH_SIZE:
1139         case LFUN_MATH_SPACE:
1140         case LFUN_MATH_LIMITS:
1141         case LFUN_MATH_NONUMBER:
1142         case LFUN_MATH_NUMBER:
1143         case LFUN_MATH_EXTERN:
1144                 flag.enabled(true);
1145                 break;
1146
1147         case LFUN_FONT_FRAK:
1148                 flag.enabled(currentMode() != TEXT_MODE);
1149                 break;
1150
1151         case LFUN_MATH_INSERT: {
1152                 bool const textarg =
1153                         arg == "\\textbf"   || arg == "\\textsf" ||
1154                         arg == "\\textrm"   || arg == "\\textmd" ||
1155                         arg == "\\textit"   || arg == "\\textsc" ||
1156                         arg == "\\textsl"   || arg == "\\textup" ||
1157                         arg == "\\texttt"   || arg == "\\textbb" ||
1158                         arg == "\\textnormal";
1159                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1160                 break;
1161         }
1162
1163         case LFUN_MATH_MATRIX:
1164                 flag.enabled(currentMode() == MATH_MODE);
1165                 break;
1166
1167         case LFUN_INSET_INSERT: {
1168                 // Don't test createMathInset_fromDialogStr(), since
1169                 // getStatus is not called with a valid reference and the
1170                 // dialog would not be applyable.
1171                 string const name = cmd.getArg(0);
1172                 flag.enabled(name == "ref");
1173                 break;
1174         }
1175
1176         case LFUN_MATH_DELIM:
1177         case LFUN_MATH_BIGDELIM:
1178                 // Don't do this with multi-cell selections
1179                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1180                 break;
1181                 
1182         case LFUN_MATH_MACRO_FOLD:
1183         case LFUN_MATH_MACRO_UNFOLD: {
1184                 Cursor it = cur;
1185                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1186                 flag.enabled(found);
1187                 break;
1188         }
1189                 
1190         case LFUN_HYPHENATION_POINT_INSERT:
1191         case LFUN_LIGATURE_BREAK_INSERT:
1192         case LFUN_MENU_SEPARATOR_INSERT:
1193         case LFUN_DOTS_INSERT:
1194         case LFUN_END_OF_SENTENCE_PERIOD_INSERT:
1195                 // FIXME: These would probably make sense in math-text mode
1196                 flag.enabled(false);
1197                 break;
1198
1199         case LFUN_INSET_DISSOLVE:
1200                 flag.enabled(!asHullInset());
1201                 break;
1202
1203         default:
1204                 ret = false;
1205                 break;
1206         }
1207         return ret;
1208 }
1209
1210
1211 void InsetMathNest::edit(Cursor & cur, bool left)
1212 {
1213         cur.push(*this);
1214         cur.idx() = left ? 0 : cur.lastidx();
1215         cur.pos() = left ? 0 : cur.lastpos();
1216         cur.resetAnchor();
1217         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1218 }
1219
1220
1221 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1222 {
1223         int idx_min = 0;
1224         int dist_min = 1000000;
1225         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1226                 int const d = cell(i).dist(cur.bv(), x, y);
1227                 if (d < dist_min) {
1228                         dist_min = d;
1229                         idx_min = i;
1230                 }
1231         }
1232         MathData & ar = cell(idx_min);
1233         cur.push(*this);
1234         cur.idx() = idx_min;
1235         cur.pos() = ar.x2pos(x - ar.xo(cur.bv()));
1236
1237         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1238         if (dist_min == 0) {
1239                 // hit inside cell
1240                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1241                         if (ar[i]->covers(cur.bv(), x, y))
1242                                 return ar[i].nucleus()->editXY(cur, x, y);
1243         }
1244         return this;
1245 }
1246
1247
1248 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1249 {
1250         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1251         BufferView & bv = cur.bv();
1252         bool do_selection = cmd.button() == mouse_button::button1
1253                 && cmd.argument() == "region-select";
1254         bv.mouseSetCursor(cur, do_selection);
1255         if (cmd.button() == mouse_button::button1) {
1256                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1257                 // Update the cursor update flags as needed:
1258                 //
1259                 // Update::Decoration: tells to update the decoration
1260                 //                     (visual box corners that define
1261                 //                     the inset)/
1262                 // Update::FitCursor: adjust the screen to the cursor
1263                 //                    position if needed
1264                 // cur.result().update(): don't overwrite previously set flags.
1265                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1266                                 | cur.result().update());
1267         } else if (cmd.button() == mouse_button::button2) {
1268                 if (cap::selection()) {
1269                         // See comment in Text::dispatch why we do this
1270                         cap::copySelectionToStack();
1271                         cmd = FuncRequest(LFUN_PASTE, "0");
1272                         doDispatch(bv.cursor(), cmd);
1273                 } else {
1274                         MathData ar;
1275                         asArray(theSelection().get(), ar);
1276                         bv.cursor().insert(ar);
1277                 }
1278         }
1279 }
1280
1281
1282 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1283 {
1284         // only select with button 1
1285         if (cmd.button() == mouse_button::button1) {
1286                 Cursor & bvcur = cur.bv().cursor();
1287                 if (bvcur.anchor_.hasPart(cur)) {
1288                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1289                         bvcur.setCursor(cur);
1290                         bvcur.selection() = true;
1291                         //lyxerr << "MOTION " << bvcur << endl;
1292                 } else
1293                         cur.undispatched();
1294         }
1295 }
1296
1297
1298 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1299 {
1300         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1301
1302         if (cmd.button() == mouse_button::button1) {
1303                 if (!cur.selection())
1304                         cur.noUpdate();
1305                 else {
1306                         Cursor & bvcur = cur.bv().cursor();
1307                         bvcur.selection() = true;
1308                 }
1309                 return;
1310         }
1311
1312         cur.undispatched();
1313 }
1314
1315
1316 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1317 {
1318         //lyxerr << "interpret 2: '" << c << "'" << endl;
1319         docstring save_selection;
1320         if (c == '^' || c == '_')
1321                 save_selection = grabAndEraseSelection(cur);
1322
1323         cur.clearTargetX();
1324
1325         // handle macroMode
1326         if (cur.inMacroMode()) {
1327                 docstring name = cur.macroName();
1328
1329                 /// are we currently typing '#1' or '#2' or...?
1330                 if (name == "\\#") {
1331                         cur.backspace();
1332                         int n = c - '0';
1333                         if (n >= 1 && n <= 9)
1334                                 cur.insert(new MathMacroArgument(n));
1335                         return true;
1336                 }
1337
1338                 if (isAlphaASCII(c)) {
1339                         cur.activeMacro()->setName(name + docstring(1, c));
1340                         return true;
1341                 }
1342
1343                 // handle 'special char' macros
1344                 if (name == "\\") {
1345                         // remove the '\\'
1346                         if (c == '\\') {
1347                                 cur.backspace();
1348                                 if (currentMode() == InsetMath::TEXT_MODE)
1349                                         cur.niceInsert(createInsetMath("textbackslash"));
1350                                 else
1351                                         cur.niceInsert(createInsetMath("backslash"));
1352                         } else if (c == '{') {
1353                                 cur.backspace();
1354                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1355                         } else if (c == '%') {
1356                                 cur.backspace();
1357                                 cur.niceInsert(MathAtom(new InsetMathComment));
1358                         } else if (c == '#') {
1359                                 BOOST_ASSERT(cur.activeMacro());
1360                                 cur.activeMacro()->setName(name + docstring(1, c));
1361                         } else {
1362                                 cur.backspace();
1363                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1364                         }
1365                         return true;
1366                 }
1367
1368                 // One character big delimiters. The others are handled in
1369                 // interpretString().
1370                 latexkeys const * l = in_word_set(name.substr(1));
1371                 if (name[0] == '\\' && l && l->inset == "big") {
1372                         docstring delim;
1373                         switch (c) {
1374                         case '{':
1375                                 delim = from_ascii("\\{");
1376                                 break;
1377                         case '}':
1378                                 delim = from_ascii("\\}");
1379                                 break;
1380                         default:
1381                                 delim = docstring(1, c);
1382                                 break;
1383                         }
1384                         if (InsetMathBig::isBigInsetDelim(delim)) {
1385                                 // name + delim ared a valid InsetMathBig.
1386                                 // We can't use cur.macroModeClose() because
1387                                 // it does not handle delim.
1388                                 InsetMathUnknown * p = cur.activeMacro();
1389                                 p->finalize();
1390                                 --cur.pos();
1391                                 cur.cell().erase(cur.pos());
1392                                 cur.plainInsert(MathAtom(
1393                                         new InsetMathBig(name.substr(1), delim)));
1394                                 return true;
1395                         }
1396                 }
1397
1398                 // leave macro mode and try again if necessary
1399                 cur.macroModeClose();
1400                 if (c == '{')
1401                         cur.niceInsert(MathAtom(new InsetMathBrace));
1402                 else if (c != ' ')
1403                         interpretChar(cur, c);
1404                 return true;
1405         }
1406
1407         // This is annoying as one has to press <space> far too often.
1408         // Disable it.
1409
1410 #if 0
1411                 // leave autocorrect mode if necessary
1412                 if (autocorrect() && c == ' ') {
1413                         autocorrect() = false;
1414                         return true;
1415                 }
1416 #endif
1417
1418         // just clear selection on pressing the space bar
1419         if (cur.selection() && c == ' ') {
1420                 cur.selection() = false;
1421                 return true;
1422         }
1423
1424         selClearOrDel(cur);
1425
1426         if (c == '\\') {
1427                 //lyxerr << "starting with macro" << endl;
1428                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1429                 return true;
1430         }
1431
1432         if (c == '\n') {
1433                 if (currentMode() == InsetMath::TEXT_MODE)
1434                         cur.insert(c);
1435                 return true;
1436         }
1437
1438         if (c == ' ') {
1439                 if (currentMode() == InsetMath::TEXT_MODE) {
1440                         // insert spaces in text mode,
1441                         // but suppress direct insertion of two spaces in a row
1442                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1443                         // it is better than nothing...
1444                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1445                                 cur.insert(c);
1446                                 // FIXME: we have to enable full redraw here because of the
1447                                 // visual box corners that define the inset. If we know for
1448                                 // sure that we stay within the same cell we can optimize for
1449                                 // that using:
1450                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1451                         }
1452                         return true;
1453                 }
1454                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1455                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1456                         // FIXME: we have to enable full redraw here because of the
1457                         // visual box corners that define the inset. If we know for
1458                         // sure that we stay within the same cell we can optimize for
1459                         // that using:
1460                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1461                         return true;
1462                 }
1463
1464                 if (cur.popForward()) {
1465                         // FIXME: we have to enable full redraw here because of the
1466                         // visual box corners that define the inset. If we know for
1467                         // sure that we stay within the same cell we can optimize for
1468                         // that using:
1469                         //cur.updateFlags(Update::FitCursor);
1470                         return true;
1471                 }
1472
1473                 // if we are at the very end, leave the formula
1474                 return cur.pos() != cur.lastpos();
1475         }
1476
1477         // These shouldn't work in text mode:
1478         if (currentMode() != InsetMath::TEXT_MODE) {
1479                 if (c == '_') {
1480                         script(cur, false, save_selection);
1481                         return true;
1482                 }
1483                 if (c == '^') {
1484                         script(cur, true, save_selection);
1485                         return true;
1486                 }
1487                 if (c == '~') {
1488                         cur.niceInsert(createInsetMath("sim"));
1489                         return true;
1490                 }
1491         }
1492
1493         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1494             c == '%' || c == '_' || c == '^') {
1495                 cur.niceInsert(createInsetMath(docstring(1, c)));
1496                 return true;
1497         }
1498
1499
1500         // try auto-correction
1501         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1502         //      return true;
1503
1504         // no special circumstances, so insert the character without any fuss
1505         cur.insert(c);
1506         cur.autocorrect() = true;
1507         return true;
1508 }
1509
1510
1511 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1512 {
1513         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1514         // possible
1515         if (!cur.empty() && cur.pos() > 0 &&
1516             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1517                 if (InsetMathBig::isBigInsetDelim(str)) {
1518                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1519                         if (prev[0] == '\\') {
1520                                 prev = prev.substr(1);
1521                                 latexkeys const * l = in_word_set(prev);
1522                                 if (l && l->inset == "big") {
1523                                         cur.cell()[cur.pos() - 1] =
1524                                                 MathAtom(new InsetMathBig(prev, str));
1525                                         return true;
1526                                 }
1527                         }
1528                 }
1529         }
1530         return false;
1531 }
1532
1533
1534 bool InsetMathNest::script(Cursor & cur, bool up,
1535                 docstring const & save_selection)
1536 {
1537         // Hack to get \^ and \_ working
1538         //lyxerr << "handling script: up: " << up << endl;
1539         if (cur.inMacroMode() && cur.macroName() == "\\") {
1540                 if (up)
1541                         cur.niceInsert(createInsetMath("mathcircumflex"));
1542                 else
1543                         interpretChar(cur, '_');
1544                 return true;
1545         }
1546
1547         cur.macroModeClose();
1548         if (asScriptInset() && cur.idx() == 0) {
1549                 // we are in a nucleus of a script inset, move to _our_ script
1550                 InsetMathScript * inset = asScriptInset();
1551                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1552                 inset->ensure(up);
1553                 cur.idx() = inset->idxOfScript(up);
1554                 cur.pos() = 0;
1555         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1556                 --cur.pos();
1557                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1558                 cur.push(*inset);
1559                 inset->ensure(up);
1560                 cur.idx() = inset->idxOfScript(up);
1561                 cur.pos() = cur.lastpos();
1562         } else {
1563                 // convert the thing to our left to a scriptinset or create a new
1564                 // one if in the very first position of the array
1565                 if (cur.pos() == 0) {
1566                         //lyxerr << "new scriptinset" << endl;
1567                         cur.insert(new InsetMathScript(up));
1568                 } else {
1569                         //lyxerr << "converting prev atom " << endl;
1570                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1571                 }
1572                 --cur.pos();
1573                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1574                 // See comment in MathParser.cpp for special handling of {}-bases
1575
1576                 cur.push(*inset);
1577                 cur.idx() = 1;
1578                 cur.pos() = 0;
1579         }
1580         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1581         cur.niceInsert(save_selection);
1582         cur.resetAnchor();
1583         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1584         return true;
1585 }
1586
1587
1588 } // namespace lyx