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