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