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