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