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