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