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