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