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