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