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