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