]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
Fix bug 3397
[lyx.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "InsetMathRef.h"
24 #include "InsetMathScript.h"
25 #include "InsetMathSpace.h"
26 #include "InsetMathSymbol.h"
27 #include "InsetMathUnknown.h"
28 #include "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                         runparams.encoding);
366         write(wi);
367         return wi.line();
368 }
369
370
371 bool InsetMathNest::setMouseHover(bool mouse_hover)
372 {
373         mouse_hover_ = mouse_hover;
374         return true;
375 }
376
377
378 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
379 {
380         // FIXME: look here
381 #if 0
382         MathData & ar = cur.cell();
383         // remove base-only "scripts"
384         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
385                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
386                 if (p && p->nargs() == 1) {
387                         MathData ar = p->nuc();
388                         erase(i);
389                         insert(i, ar);
390                         cur.adjust(i, ar.size() - 1);
391                 }
392         }
393
394         // glue adjacent font insets of the same kind
395         for (pos_type i = 0; i + 1 < size(); ++i) {
396                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
397                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
398                 if (p && q && p->name() == q->name()) {
399                         p->cell(0).append(q->cell(0));
400                         erase(i + 1);
401                         cur.adjust(i, -1);
402                 }
403         }
404 #endif
405         return false;
406 }
407
408
409 void InsetMathNest::handleFont
410         (Cursor & cur, docstring const & arg, char const * const font)
411 {
412         handleFont(cur, arg, from_ascii(font));
413 }
414
415
416 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
417         docstring const & font)
418 {
419         cur.recordUndoSelection();
420
421         // this whole function is a hack and won't work for incremental font
422         // changes...
423         if (cur.inset().asInsetMath()->name() == font)
424                 cur.handleFont(to_utf8(font));
425         else
426                 handleNest(cur, createInsetMath(font), arg);
427 }
428
429
430 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
431 {
432         handleNest(cur, nest, docstring());
433 }
434
435
436 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
437         docstring const & arg)
438 {
439         CursorSlice i1 = cur.selBegin();
440         CursorSlice i2 = cur.selEnd();
441         if (!i1.inset().asInsetMath())
442                 return;
443         if (i1.idx() == i2.idx()) {
444                 // the easy case where only one cell is selected
445                 cur.handleNest(nest);
446                 cur.insert(arg);
447                 return;
448         }
449
450         // multiple selected cells in a simple non-grid inset
451         if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
452                 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
453                         // select cell
454                         cur.idx() = i;
455                         cur.pos() = 0;
456                         cur.resetAnchor();
457                         cur.pos() = cur.lastpos();
458                         cur.setSelection();
459
460                         // change font of cell
461                         cur.handleNest(nest);
462                         cur.insert(arg);
463
464                         // cur is in the font inset now. If the loop continues,
465                         // we need to get outside again for the next cell
466                         if (i + 1 <= i2.idx())
467                                 cur.pop_back();
468                 }
469                 return;
470         }
471
472         // the complicated case with multiple selected cells in a grid
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.recordUndoSelection();
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         Parse::flags parseflg = Parse::QUIET;
517
518         switch (cmd.action) {
519
520         case LFUN_CLIPBOARD_PASTE:
521                 parseflg |= Parse::VERBATIM;
522                 // fall through
523         case LFUN_PASTE: {
524                 cur.recordUndoSelection();
525                 cur.message(_("Paste"));
526                 replaceSelection(cur);
527                 docstring topaste;
528                 if (cmd.argument().empty() && !theClipboard().isInternal())
529                         topaste = theClipboard().getAsText();
530                 else {
531                         size_t n = 0;
532                         idocstringstream is(cmd.argument());
533                         is >> n;
534                         topaste = cap::selection(n);
535                 }
536                 cur.niceInsert(topaste, parseflg);
537                 cur.clearSelection(); // bug 393
538                 cur.finishUndo();
539                 break;
540         }
541
542         case LFUN_CUT:
543                 cur.recordUndo();
544                 cutSelection(cur, true, true);
545                 cur.message(_("Cut"));
546                 // Prevent stale position >= size crash
547                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
548                 cur.normalize();
549                 break;
550
551         case LFUN_COPY:
552                 copySelection(cur);
553                 cur.message(_("Copy"));
554                 break;
555
556         case LFUN_MOUSE_PRESS:
557                 lfunMousePress(cur, cmd);
558                 break;
559
560         case LFUN_MOUSE_MOTION:
561                 lfunMouseMotion(cur, cmd);
562                 break;
563
564         case LFUN_MOUSE_RELEASE:
565                 lfunMouseRelease(cur, cmd);
566                 break;
567
568         case LFUN_FINISHED_LEFT: // in math, left is backwards
569         case LFUN_FINISHED_BACKWARD:
570                 cur.bv().cursor() = cur;
571                 break;
572
573         case LFUN_FINISHED_RIGHT: // in math, right is forward
574         case LFUN_FINISHED_FORWARD:
575                 ++cur.pos();
576                 cur.bv().cursor() = cur;
577                 break;
578
579         case LFUN_CHAR_RIGHT:
580         case LFUN_CHAR_LEFT:
581         case LFUN_CHAR_BACKWARD:
582         case LFUN_CHAR_FORWARD:
583                 cur.updateFlags(Update::Decoration | Update::FitCursor);
584         case LFUN_CHAR_RIGHT_SELECT:
585         case LFUN_CHAR_LEFT_SELECT:
586         case LFUN_CHAR_BACKWARD_SELECT:
587         case LFUN_CHAR_FORWARD_SELECT: {
588                 // are we in a selection?
589                 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT
590                                            || cmd.action == LFUN_CHAR_LEFT_SELECT
591                                            || cmd.action == LFUN_CHAR_BACKWARD_SELECT
592                                            || cmd.action == LFUN_CHAR_FORWARD_SELECT);
593                 // are we moving forward or backwards?
594                 // If the command was RIGHT or LEFT, then whether we're moving forward
595                 // or backwards depends on the cursor movement mode (logical or visual):
596                 //  * in visual mode, since math is always LTR, right -> forward,
597                 //    left -> backwards
598                 //  * in logical mode, the mapping is determined by the
599                 //    reverseDirectionNeeded() function
600
601                 bool forward;
602                 FuncCode finish_lfun;
603
604                 if (cmd.action == LFUN_CHAR_FORWARD
605                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
606                         forward = true;
607                         finish_lfun = LFUN_FINISHED_FORWARD;
608                 }
609                 else if (cmd.action == LFUN_CHAR_BACKWARD
610                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
611                         forward = false;
612                         finish_lfun = LFUN_FINISHED_BACKWARD;
613                 }
614                 else {
615                         bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
616                                                   || cmd.action == LFUN_CHAR_RIGHT);
617                         if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
618                                 forward = right;
619                         else
620                                 forward = !right;
621
622                         if (right)
623                                 finish_lfun = LFUN_FINISHED_RIGHT;
624                         else
625                                 finish_lfun = LFUN_FINISHED_LEFT;
626                 }
627                 // Now that we know exactly what we want to do, let's do it!
628                 cur.selHandle(select);
629                 cur.autocorrect() = false;
630                 cur.clearTargetX();
631                 cur.macroModeClose();
632                 // try moving forward or backwards as necessary...
633                 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
634                         // ... and if movement failed, then finish forward or backwards
635                         // as necessary
636                         cmd = FuncRequest(finish_lfun);
637                         cur.undispatched();
638                 }
639                 break;
640         }
641
642         case LFUN_DOWN:
643         case LFUN_UP:
644                 cur.updateFlags(Update::Decoration | Update::FitCursor);
645         case LFUN_DOWN_SELECT:
646         case LFUN_UP_SELECT: {
647                 // close active macro
648                 if (cur.inMacroMode()) {
649                         cur.macroModeClose();
650                         break;
651                 }
652
653                 // stop/start the selection
654                 bool select = cmd.action == LFUN_DOWN_SELECT ||
655                         cmd.action == LFUN_UP_SELECT;
656                 cur.selHandle(select);
657
658                 // go up/down
659                 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
660                 bool successful = cur.upDownInMath(up);
661                 if (successful)
662                         break;
663
664                 if (cur.fixIfBroken())
665                         // FIXME: Something bad happened. We pass the corrected Cursor
666                         // instead of letting things go worse.
667                         break;
668
669                 // We did not manage to move the cursor.
670                 cur.undispatched();
671                 break;
672         }
673
674         case LFUN_MOUSE_DOUBLE:
675         case LFUN_MOUSE_TRIPLE:
676         case LFUN_WORD_SELECT:
677                 cur.pos() = 0;
678                 cur.idx() = 0;
679                 cur.resetAnchor();
680                 cur.setSelection(true);
681                 cur.pos() = cur.lastpos();
682                 cur.idx() = cur.lastidx();
683                 break;
684
685         case LFUN_PARAGRAPH_UP:
686         case LFUN_PARAGRAPH_DOWN:
687                 cur.updateFlags(Update::Decoration | Update::FitCursor);
688         case LFUN_PARAGRAPH_UP_SELECT:
689         case LFUN_PARAGRAPH_DOWN_SELECT:
690                 break;
691
692         case LFUN_LINE_BEGIN:
693         case LFUN_WORD_BACKWARD:
694         case LFUN_WORD_LEFT:
695                 cur.updateFlags(Update::Decoration | Update::FitCursor);
696         case LFUN_LINE_BEGIN_SELECT:
697         case LFUN_WORD_BACKWARD_SELECT:
698         case LFUN_WORD_LEFT_SELECT:
699                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
700                                 cmd.action == LFUN_WORD_LEFT_SELECT ||
701                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
702                 cur.macroModeClose();
703                 if (cur.pos() != 0) {
704                         cur.pos() = 0;
705                 } else if (cur.col() != 0) {
706                         cur.idx() -= cur.col();
707                         cur.pos() = 0;
708                 } else if (cur.idx() != 0) {
709                         cur.idx() = 0;
710                         cur.pos() = 0;
711                 } else {
712                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
713                         cur.undispatched();
714                 }
715                 break;
716
717         case LFUN_WORD_FORWARD:
718         case LFUN_WORD_RIGHT:
719         case LFUN_LINE_END:
720                 cur.updateFlags(Update::Decoration | Update::FitCursor);
721         case LFUN_WORD_FORWARD_SELECT:
722         case LFUN_WORD_RIGHT_SELECT:
723         case LFUN_LINE_END_SELECT:
724                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
725                                 cmd.action == LFUN_WORD_RIGHT_SELECT ||
726                                 cmd.action == LFUN_LINE_END_SELECT);
727                 cur.macroModeClose();
728                 cur.clearTargetX();
729                 if (cur.pos() != cur.lastpos()) {
730                         cur.pos() = cur.lastpos();
731                 } else if (ncols() && (cur.col() != cur.lastcol())) {
732                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
733                         cur.pos() = cur.lastpos();
734                 } else if (cur.idx() != cur.lastidx()) {
735                         cur.idx() = cur.lastidx();
736                         cur.pos() = cur.lastpos();
737                 } else {
738                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
739                         cur.undispatched();
740                 }
741                 break;
742
743         case LFUN_CELL_FORWARD:
744                 cur.updateFlags(Update::Decoration | Update::FitCursor);
745                 cur.inset().idxNext(cur);
746                 break;
747
748         case LFUN_CELL_BACKWARD:
749                 cur.updateFlags(Update::Decoration | Update::FitCursor);
750                 cur.inset().idxPrev(cur);
751                 break;
752
753         case LFUN_WORD_DELETE_BACKWARD:
754         case LFUN_CHAR_DELETE_BACKWARD:
755                 if (cur.pos() == 0)
756                         // May affect external cell:
757                         cur.recordUndoInset();
758                 else
759                         cur.recordUndoSelection();
760                 // if the inset can not be removed from within, delete it
761                 if (!cur.backspace()) {
762                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
763                         cur.innerText()->dispatch(cur, cmd);
764                 }
765                 break;
766
767         case LFUN_WORD_DELETE_FORWARD:
768         case LFUN_CHAR_DELETE_FORWARD:
769                 if (cur.pos() == cur.lastpos())
770                         // May affect external cell:
771                         cur.recordUndoInset();
772                 else
773                         cur.recordUndoSelection();
774                 // if the inset can not be removed from within, delete it
775                 if (!cur.erase()) {
776                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
777                         cur.innerText()->dispatch(cur, cmd);
778                 }
779                 break;
780
781         case LFUN_ESCAPE:
782                 if (cur.selection())
783                         cur.clearSelection();
784                 else  {
785                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
786                         cur.undispatched();
787                 }
788                 break;
789
790         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
791         // that is traversed by a single <CursorLeft>/<CursorRight>.
792         case LFUN_INSET_TOGGLE:
793                 cur.recordUndo();
794                 lock(!lock());
795                 cur.popForward();
796                 break;
797
798         case LFUN_SELF_INSERT:
799                 if (cmd.argument().size() != 1) {
800                         cur.recordUndoSelection();
801                         docstring const arg = cmd.argument();
802                         if (!interpretString(cur, arg))
803                                 cur.insert(arg);
804                         break;
805                 }
806                 // Don't record undo steps if we are in macro mode and
807                 // cmd.argument is the next character of the macro name.
808                 // Otherwise we'll get an invalid cursor if we undo after
809                 // the macro was finished and the macro is a known command,
810                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
811                 // the InsetMathUnknown with name "frac" by an empty
812                 // InsetMathFrac -> a pos value > 0 is invalid.
813                 // A side effect is that an undo before the macro is finished
814                 // undoes the complete macro, not only the last character.
815                 if (!cur.inMacroMode())
816                         cur.recordUndoSelection();
817
818                 // spacial handling of space. If we insert an inset
819                 // via macro mode, we want to put the cursor inside it
820                 // if relevant. Think typing "\frac<space>".
821                 if (cmd.argument()[0] == ' '
822                     && cur.inMacroMode() && cur.macroName() != "\\"
823                     && cur.macroModeClose()) {
824                         MathAtom const atom = cur.prevAtom();
825                         if (atom->asNestInset() && atom->isActive()) {
826                                 cur.posBackward();
827                                 cur.pushBackward(*cur.nextInset());
828                         }
829                 } else if (!interpretChar(cur, cmd.argument()[0])) {
830                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
831                         cur.undispatched();
832                 }
833                 break;
834
835         //case LFUN_SERVER_GET_XY:
836         //      sprintf(dispatch_buffer, "%d %d",);
837         //      break;
838
839         case LFUN_SERVER_SET_XY: {
840                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
841                 int x = 0;
842                 int y = 0;
843                 istringstream is(to_utf8(cmd.argument()));
844                 is >> x >> y;
845                 cur.setScreenPos(x, y);
846                 break;
847         }
848
849         // Special casing for superscript in case of LyX handling
850         // dead-keys:
851         case LFUN_ACCENT_CIRCUMFLEX:
852                 if (cmd.argument().empty()) {
853                         // do superscript if LyX handles
854                         // deadkeys
855                         cur.recordUndoSelection();
856                         script(cur, true, grabAndEraseSelection(cur));
857                 }
858                 break;
859
860         case LFUN_ACCENT_UMLAUT:
861         case LFUN_ACCENT_ACUTE:
862         case LFUN_ACCENT_GRAVE:
863         case LFUN_ACCENT_BREVE:
864         case LFUN_ACCENT_DOT:
865         case LFUN_ACCENT_MACRON:
866         case LFUN_ACCENT_CARON:
867         case LFUN_ACCENT_TILDE:
868         case LFUN_ACCENT_CEDILLA:
869         case LFUN_ACCENT_CIRCLE:
870         case LFUN_ACCENT_UNDERDOT:
871         case LFUN_ACCENT_TIE:
872         case LFUN_ACCENT_OGONEK:
873         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
874                 break;
875
876         //  Math fonts
877         case LFUN_TEXTSTYLE_APPLY:
878         case LFUN_TEXTSTYLE_UPDATE:
879                 handleFont2(cur, cmd.argument());
880                 break;
881
882         case LFUN_FONT_BOLD:
883                 if (currentMode() == TEXT_MODE)
884                         handleFont(cur, cmd.argument(), "textbf");
885                 else
886                         handleFont(cur, cmd.argument(), "mathbf");
887                 break;
888         case LFUN_FONT_BOLDSYMBOL:
889                 if (currentMode() == TEXT_MODE)
890                         handleFont(cur, cmd.argument(), "textbf");
891                 else
892                         handleFont(cur, cmd.argument(), "boldsymbol");
893                 break;
894         case LFUN_FONT_SANS:
895                 if (currentMode() == TEXT_MODE)
896                         handleFont(cur, cmd.argument(), "textsf");
897                 else
898                         handleFont(cur, cmd.argument(), "mathsf");
899                 break;
900         case LFUN_FONT_EMPH:
901                 if (currentMode() == TEXT_MODE)
902                         handleFont(cur, cmd.argument(), "emph");
903                 else
904                         handleFont(cur, cmd.argument(), "mathcal");
905                 break;
906         case LFUN_FONT_ROMAN:
907                 if (currentMode() == TEXT_MODE)
908                         handleFont(cur, cmd.argument(), "textrm");
909                 else
910                         handleFont(cur, cmd.argument(), "mathrm");
911                 break;
912         case LFUN_FONT_TYPEWRITER:
913                 if (currentMode() == TEXT_MODE)
914                         handleFont(cur, cmd.argument(), "texttt");
915                 else
916                         handleFont(cur, cmd.argument(), "mathtt");
917                 break;
918         case LFUN_FONT_FRAK:
919                 handleFont(cur, cmd.argument(), "mathfrak");
920                 break;
921         case LFUN_FONT_ITAL:
922                 if (currentMode() == TEXT_MODE)
923                         handleFont(cur, cmd.argument(), "textit");
924                 else
925                         handleFont(cur, cmd.argument(), "mathit");
926                 break;
927         case LFUN_FONT_NOUN:
928                 if (currentMode() == TEXT_MODE)
929                         // FIXME: should be "noun"
930                         handleFont(cur, cmd.argument(), "textsc");
931                 else
932                         handleFont(cur, cmd.argument(), "mathbb");
933                 break;
934         case LFUN_FONT_DEFAULT:
935                 handleFont(cur, cmd.argument(), "textnormal");
936                 break;
937
938         case LFUN_MATH_MODE: {
939 #if 1
940                 // ignore math-mode on when already in math mode
941                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
942                         break;
943                 cur.recordUndoSelection();
944                 cur.macroModeClose();
945                 docstring const save_selection = grabAndEraseSelection(cur);
946                 selClearOrDel(cur);
947                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
948                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
949                 cur.posBackward();
950                 cur.pushBackward(*cur.nextInset());
951                 cur.niceInsert(save_selection);
952 #else
953                 if (currentMode() == Inset::TEXT_MODE) {
954                         cur.recordUndoSelection();
955                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
956                         cur.message(_("create new math text environment ($...$)"));
957                 } else {
958                         handleFont(cur, cmd.argument(), "textrm");
959                         cur.message(_("entered math text mode (textrm)"));
960                 }
961 #endif
962                 break;
963         }
964
965         case LFUN_MATH_SIZE: {
966                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
967                 doDispatch(cur, fr);
968                 break;
969         }
970
971         case LFUN_MATH_MATRIX: {
972                 cur.recordUndo();
973                 unsigned int m = 1;
974                 unsigned int n = 1;
975                 docstring v_align;
976                 docstring h_align;
977                 idocstringstream is(cmd.argument());
978                 is >> m >> n >> v_align >> h_align;
979                 if (m < 1)
980                         m = 1;
981                 if (n < 1)
982                         n = 1;
983                 v_align += 'c';
984                 cur.niceInsert(
985                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
986                 break;
987         }
988
989         case LFUN_MATH_DELIM: {
990                 docstring ls;
991                 docstring rs = split(cmd.argument(), ls, ' ');
992                 // Reasonable default values
993                 if (ls.empty())
994                         ls = '(';
995                 if (rs.empty())
996                         rs = ')';
997                 cur.recordUndo();
998                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
999                 break;
1000         }
1001
1002         case LFUN_MATH_BIGDELIM: {
1003                 docstring const lname  = from_utf8(cmd.getArg(0));
1004                 docstring const ldelim = from_utf8(cmd.getArg(1));
1005                 docstring const rname  = from_utf8(cmd.getArg(2));
1006                 docstring const rdelim = from_utf8(cmd.getArg(3));
1007                 latexkeys const * l = in_word_set(lname);
1008                 bool const have_l = l && l->inset == "big" &&
1009                                     InsetMathBig::isBigInsetDelim(ldelim);
1010                 l = in_word_set(rname);
1011                 bool const have_r = l && l->inset == "big" &&
1012                                     InsetMathBig::isBigInsetDelim(rdelim);
1013                 // We mimic LFUN_MATH_DELIM in case we have an empty left
1014                 // or right delimiter.
1015                 if (have_l || have_r) {
1016                         cur.recordUndo();
1017                         docstring const selection = grabAndEraseSelection(cur);
1018                         selClearOrDel(cur);
1019                         if (have_l)
1020                                 cur.insert(MathAtom(new InsetMathBig(lname,
1021                                                                 ldelim)));
1022                         cur.niceInsert(selection);
1023                         if (have_r)
1024                                 cur.insert(MathAtom(new InsetMathBig(rname,
1025                                                                 rdelim)));
1026                 }
1027                 // Don't call cur.undispatched() if we did nothing, this would
1028                 // lead to infinite recursion via Text::dispatch().
1029                 break;
1030         }
1031
1032         case LFUN_SPACE_INSERT:
1033                 cur.recordUndoSelection();
1034                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1035                 break;
1036
1037         case LFUN_MATH_SPACE:
1038                 cur.recordUndoSelection();
1039                 if (cmd.argument().empty())
1040                         cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1041                 else
1042                         cur.insert(MathAtom(new InsetMathSpace(cmd.argument())));
1043                 break;
1044
1045         case LFUN_ERT_INSERT:
1046                 // interpret this as if a backslash was typed
1047                 cur.recordUndo();
1048                 interpretChar(cur, '\\');
1049                 break;
1050
1051         case LFUN_MATH_SUBSCRIPT:
1052                 // interpret this as if a _ was typed
1053                 cur.recordUndoSelection();
1054                 interpretChar(cur, '_');
1055                 break;
1056
1057         case LFUN_MATH_SUPERSCRIPT:
1058                 // interpret this as if a ^ was typed
1059                 cur.recordUndoSelection();
1060                 interpretChar(cur, '^');
1061                 break;
1062
1063         case LFUN_MATH_MACRO_FOLD:
1064         case LFUN_MATH_MACRO_UNFOLD: {
1065                 Cursor it = cur;
1066                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
1067                 bool found = findMacroToFoldUnfold(it, fold);
1068                 if (found) {
1069                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1070                         cur.recordUndoInset();
1071                         if (fold)
1072                                 macro->fold(cur);
1073                         else
1074                                 macro->unfold(cur);
1075                 }
1076                 break;
1077         }
1078
1079         case LFUN_QUOTE_INSERT:
1080                 // interpret this as if a straight " was typed
1081                 cur.recordUndoSelection();
1082                 interpretChar(cur, '\"');
1083                 break;
1084
1085 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1086 // handling such that "self-insert" works on "arbitrary stuff" too, and
1087 // math-insert only handles special math things like "matrix".
1088         case LFUN_MATH_INSERT: {
1089                 cur.recordUndoSelection();
1090                 if (cmd.argument() == "^" || cmd.argument() == "_")
1091                         interpretChar(cur, cmd.argument()[0]);
1092                 else {
1093                         MathData ar;
1094                         asArray(cmd.argument(), ar);
1095                         if (ar.size() == 1 && ar[0]->asNestInset()
1096                                         && ar[0]->asNestInset()->nargs() > 1)
1097                                 handleNest(cur, ar[0]);
1098                         else
1099                                 cur.niceInsert(cmd.argument());
1100                 }
1101                 break;
1102                 }
1103
1104         case LFUN_DIALOG_SHOW_NEW_INSET: {
1105                 docstring const & name = cmd.argument();
1106                 string data;
1107                 if (name == "ref") {
1108                         InsetMathRef tmp(name);
1109                         data = tmp.createDialogStr(to_utf8(name));
1110                 }
1111                 cur.bv().showDialog(to_utf8(name), data);
1112                 break;
1113         }
1114
1115         case LFUN_INSET_INSERT: {
1116                 MathData ar;
1117                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1118                         cur.recordUndoSelection();
1119                         cur.insert(ar);
1120                 } else
1121                         cur.undispatched();
1122                 break;
1123         }
1124         case LFUN_INSET_DISSOLVE:
1125                 if (!asHullInset()) {
1126                         cur.recordUndoInset();
1127                         cur.pullArg();
1128                 }
1129                 break;
1130
1131         default:
1132                 InsetMath::doDispatch(cur, cmd);
1133                 break;
1134         }
1135 }
1136
1137
1138 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1139         // look for macro to open/close, but stay in mathed
1140         for (; !it.empty(); it.pop_back()) {
1141
1142                 // go backward through the current cell
1143                 Inset * inset = it.nextInset();
1144                 while (inset && inset->asInsetMath()) {
1145                         MathMacro * macro = inset->asInsetMath()->asMacro();
1146                         if (macro) {
1147                                 // found the an macro to open/close?
1148                                 if (macro->folded() != fold)
1149                                         return true;
1150
1151                                 // Wrong folding state.
1152                                 // If this was the first we see in this slice, look further left,
1153                                 // otherwise go up.
1154                                 if (inset != it.nextInset())
1155                                         break;
1156                         }
1157
1158                         // go up if this was the left most position
1159                         if (it.pos() == 0)
1160                                 break;
1161
1162                         // go left
1163                         it.pos()--;
1164                         inset = it.nextInset();
1165                 }
1166         }
1167
1168         return false;
1169 }
1170
1171
1172 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1173                 FuncStatus & flag) const
1174 {
1175         // the font related toggles
1176         //string tc = "mathnormal";
1177         bool ret = true;
1178         string const arg = to_utf8(cmd.argument());
1179         switch (cmd.action) {
1180         case LFUN_TABULAR_FEATURE:
1181                 flag.setEnabled(false);
1182                 break;
1183 #if 0
1184         case LFUN_TABULAR_FEATURE:
1185                 // FIXME: check temporarily disabled
1186                 // valign code
1187                 char align = mathcursor::valign();
1188                 if (align == '\0') {
1189                         enable = false;
1190                         break;
1191                 }
1192                 if (cmd.argument().empty()) {
1193                         flag.clear();
1194                         break;
1195                 }
1196                 if (!contains("tcb", cmd.argument()[0])) {
1197                         enable = false;
1198                         break;
1199                 }
1200                 flag.setOnOff(cmd.argument()[0] == align);
1201                 break;
1202 #endif
1203         /// We have to handle them since 1.4 blocks all unhandled actions
1204         case LFUN_FONT_ITAL:
1205         case LFUN_FONT_BOLD:
1206         case LFUN_FONT_BOLDSYMBOL:
1207         case LFUN_FONT_SANS:
1208         case LFUN_FONT_EMPH:
1209         case LFUN_FONT_TYPEWRITER:
1210         case LFUN_FONT_NOUN:
1211         case LFUN_FONT_ROMAN:
1212         case LFUN_FONT_DEFAULT:
1213                 flag.setEnabled(true);
1214                 break;
1215         case LFUN_MATH_MUTATE:
1216                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1217                 flag.setOnOff(false);
1218                 break;
1219
1220         // we just need to be in math mode to enable that
1221         case LFUN_MATH_SIZE:
1222         case LFUN_MATH_SPACE:
1223         case LFUN_MATH_LIMITS:
1224         case LFUN_MATH_EXTERN:
1225                 flag.setEnabled(true);
1226                 break;
1227
1228         case LFUN_FONT_FRAK:
1229                 flag.setEnabled(currentMode() != TEXT_MODE);
1230                 break;
1231
1232         case LFUN_MATH_INSERT: {
1233                 bool const textarg =
1234                         arg == "\\textbf"   || arg == "\\textsf" ||
1235                         arg == "\\textrm"   || arg == "\\textmd" ||
1236                         arg == "\\textit"   || arg == "\\textsc" ||
1237                         arg == "\\textsl"   || arg == "\\textup" ||
1238                         arg == "\\texttt"   || arg == "\\textbb" ||
1239                         arg == "\\textnormal";
1240                 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1241                 break;
1242         }
1243
1244         case LFUN_MATH_MATRIX:
1245                 flag.setEnabled(currentMode() == MATH_MODE);
1246                 break;
1247
1248         case LFUN_INSET_INSERT: {
1249                 // Don't test createMathInset_fromDialogStr(), since
1250                 // getStatus is not called with a valid reference and the
1251                 // dialog would not be applyable.
1252                 string const name = cmd.getArg(0);
1253                 flag.setEnabled(name == "ref");
1254                 break;
1255         }
1256
1257         case LFUN_MATH_DELIM:
1258         case LFUN_MATH_BIGDELIM:
1259                 // Don't do this with multi-cell selections
1260                 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1261                 break;
1262
1263         case LFUN_MATH_MACRO_FOLD:
1264         case LFUN_MATH_MACRO_UNFOLD: {
1265                 Cursor it = cur;
1266                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1267                 flag.setEnabled(found);
1268                 break;
1269         }
1270
1271         case LFUN_SPECIALCHAR_INSERT:
1272                 // FIXME: These would probably make sense in math-text mode
1273                 flag.setEnabled(false);
1274                 break;
1275
1276         case LFUN_INSET_DISSOLVE:
1277                 flag.setEnabled(!asHullInset());
1278                 break;
1279
1280         default:
1281                 ret = false;
1282                 break;
1283         }
1284         return ret;
1285 }
1286
1287
1288 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1289 {
1290         cur.push(*this);
1291         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1292                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1293         cur.idx() = enter_front ? 0 : cur.lastidx();
1294         cur.pos() = enter_front ? 0 : cur.lastpos();
1295         cur.resetAnchor();
1296         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1297 }
1298
1299
1300 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1301 {
1302         int idx_min = 0;
1303         int dist_min = 1000000;
1304         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1305                 int const d = cell(i).dist(cur.bv(), x, y);
1306                 if (d < dist_min) {
1307                         dist_min = d;
1308                         idx_min = i;
1309                 }
1310         }
1311         MathData & ar = cell(idx_min);
1312         cur.push(*this);
1313         cur.idx() = idx_min;
1314         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1315
1316         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1317         if (dist_min == 0) {
1318                 // hit inside cell
1319                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1320                         if (ar[i]->covers(cur.bv(), x, y))
1321                                 return ar[i].nucleus()->editXY(cur, x, y);
1322         }
1323         return this;
1324 }
1325
1326
1327 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1328 {
1329         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1330         BufferView & bv = cur.bv();
1331         bool do_selection = cmd.button() == mouse_button::button1
1332                 && cmd.argument() == "region-select";
1333         bv.mouseSetCursor(cur, do_selection);
1334         if (cmd.button() == mouse_button::button1) {
1335                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1336                 // Update the cursor update flags as needed:
1337                 //
1338                 // Update::Decoration: tells to update the decoration
1339                 //                     (visual box corners that define
1340                 //                     the inset)/
1341                 // Update::FitCursor: adjust the screen to the cursor
1342                 //                    position if needed
1343                 // cur.result().update(): don't overwrite previously set flags.
1344                 cur.updateFlags(Update::Decoration | Update::FitCursor
1345                                 | cur.result().update());
1346         } else if (cmd.button() == mouse_button::button2) {
1347                 if (cap::selection()) {
1348                         // See comment in Text::dispatch why we do this
1349                         cap::copySelectionToStack();
1350                         cmd = FuncRequest(LFUN_PASTE, "0");
1351                         doDispatch(bv.cursor(), cmd);
1352                 } else {
1353                         MathData ar;
1354                         asArray(theSelection().get(), ar);
1355                         bv.cursor().insert(ar);
1356                 }
1357         }
1358 }
1359
1360
1361 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1362 {
1363         // only select with button 1
1364         if (cmd.button() == mouse_button::button1) {
1365                 Cursor & bvcur = cur.bv().cursor();
1366                 if (bvcur.anchor_.hasPart(cur)) {
1367                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1368                         bvcur.setCursor(cur);
1369                         bvcur.setSelection(true);
1370                         //lyxerr << "MOTION " << bvcur << endl;
1371                 } else
1372                         cur.undispatched();
1373         }
1374 }
1375
1376
1377 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1378 {
1379         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1380
1381         if (cmd.button() == mouse_button::button1) {
1382                 if (!cur.selection())
1383                         cur.noUpdate();
1384                 else {
1385                         Cursor & bvcur = cur.bv().cursor();
1386                         bvcur.setSelection(true);
1387                 }
1388                 return;
1389         }
1390
1391         cur.undispatched();
1392 }
1393
1394
1395 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1396 {
1397         //lyxerr << "interpret 2: '" << c << "'" << endl;
1398         docstring save_selection;
1399         if (c == '^' || c == '_')
1400                 save_selection = grabAndEraseSelection(cur);
1401
1402         cur.clearTargetX();
1403
1404         // handle macroMode
1405         if (cur.inMacroMode()) {
1406                 docstring name = cur.macroName();
1407
1408                 /// are we currently typing '#1' or '#2' or...?
1409                 if (name == "\\#") {
1410                         cur.backspace();
1411                         int n = c - '0';
1412                         if (n >= 1 && n <= 9)
1413                                 cur.insert(new MathMacroArgument(n));
1414                         return true;
1415                 }
1416
1417                 // do not finish macro for known * commands
1418                 MathWordList const & mwl = mathedWordList();
1419                 bool star_macro = c == '*'
1420                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1421                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1422                 if (isAlphaASCII(c) || star_macro) {
1423                         cur.activeMacro()->setName(name + docstring(1, c));
1424                         return true;
1425                 }
1426
1427                 // handle 'special char' macros
1428                 if (name == "\\") {
1429                         // remove the '\\'
1430                         if (c == '\\') {
1431                                 cur.backspace();
1432                                 if (currentMode() == InsetMath::TEXT_MODE)
1433                                         cur.niceInsert(createInsetMath("textbackslash"));
1434                                 else
1435                                         cur.niceInsert(createInsetMath("backslash"));
1436                         } else if (c == '{') {
1437                                 cur.backspace();
1438                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1439                         } else if (c == '%') {
1440                                 cur.backspace();
1441                                 cur.niceInsert(MathAtom(new InsetMathComment));
1442                         } else if (c == '#') {
1443                                 LASSERT(cur.activeMacro(), /**/);
1444                                 cur.activeMacro()->setName(name + docstring(1, c));
1445                         } else {
1446                                 cur.backspace();
1447                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1448                         }
1449                         return true;
1450                 }
1451
1452                 // One character big delimiters. The others are handled in
1453                 // interpretString().
1454                 latexkeys const * l = in_word_set(name.substr(1));
1455                 if (name[0] == '\\' && l && l->inset == "big") {
1456                         docstring delim;
1457                         switch (c) {
1458                         case '{':
1459                                 delim = from_ascii("\\{");
1460                                 break;
1461                         case '}':
1462                                 delim = from_ascii("\\}");
1463                                 break;
1464                         default:
1465                                 delim = docstring(1, c);
1466                                 break;
1467                         }
1468                         if (InsetMathBig::isBigInsetDelim(delim)) {
1469                                 // name + delim ared a valid InsetMathBig.
1470                                 // We can't use cur.macroModeClose() because
1471                                 // it does not handle delim.
1472                                 InsetMathUnknown * p = cur.activeMacro();
1473                                 p->finalize();
1474                                 --cur.pos();
1475                                 cur.cell().erase(cur.pos());
1476                                 cur.plainInsert(MathAtom(
1477                                         new InsetMathBig(name.substr(1), delim)));
1478                                 return true;
1479                         }
1480                 }
1481
1482                 // leave macro mode and try again if necessary
1483                 cur.macroModeClose();
1484                 if (c == '{')
1485                         cur.niceInsert(MathAtom(new InsetMathBrace));
1486                 else if (c != ' ')
1487                         interpretChar(cur, c);
1488                 return true;
1489         }
1490
1491         // This is annoying as one has to press <space> far too often.
1492         // Disable it.
1493
1494 #if 0
1495                 // leave autocorrect mode if necessary
1496                 if (autocorrect() && c == ' ') {
1497                         autocorrect() = false;
1498                         return true;
1499                 }
1500 #endif
1501
1502         // just clear selection on pressing the space bar
1503         if (cur.selection() && c == ' ') {
1504                 cur.setSelection(false);
1505                 return true;
1506         }
1507
1508         if (c == '\\') {
1509                 //lyxerr << "starting with macro" << endl;
1510                 bool reduced = cap::reduceSelectionToOneCell(cur);
1511                 if (reduced || !cur.selection()) {
1512                         docstring const safe = cap::grabAndEraseSelection(cur);
1513                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1514                 }
1515                 return true;
1516         }
1517
1518         selClearOrDel(cur);
1519
1520         if (c == '\n') {
1521                 if (currentMode() == InsetMath::TEXT_MODE)
1522                         cur.insert(c);
1523                 return true;
1524         }
1525
1526         if (c == ' ') {
1527                 if (currentMode() == InsetMath::TEXT_MODE) {
1528                         // insert spaces in text mode,
1529                         // but suppress direct insertion of two spaces in a row
1530                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1531                         // it is better than nothing...
1532                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1533                                 cur.insert(c);
1534                                 // FIXME: we have to enable full redraw here because of the
1535                                 // visual box corners that define the inset. If we know for
1536                                 // sure that we stay within the same cell we can optimize for
1537                                 // that using:
1538                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1539                         }
1540                         return true;
1541                 }
1542                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1543                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1544                         // FIXME: we have to enable full redraw here because of the
1545                         // visual box corners that define the inset. If we know for
1546                         // sure that we stay within the same cell we can optimize for
1547                         // that using:
1548                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1549                         return true;
1550                 }
1551
1552                 if (cur.popForward()) {
1553                         // FIXME: we have to enable full redraw here because of the
1554                         // visual box corners that define the inset. If we know for
1555                         // sure that we stay within the same cell we can optimize for
1556                         // that using:
1557                         //cur.updateFlags(Update::FitCursor);
1558                         return true;
1559                 }
1560
1561                 // if we are at the very end, leave the formula
1562                 return cur.pos() != cur.lastpos();
1563         }
1564
1565         // These shouldn't work in text mode:
1566         if (currentMode() != InsetMath::TEXT_MODE) {
1567                 if (c == '_') {
1568                         script(cur, false, save_selection);
1569                         return true;
1570                 }
1571                 if (c == '^') {
1572                         script(cur, true, save_selection);
1573                         return true;
1574                 }
1575                 if (c == '~') {
1576                         cur.niceInsert(createInsetMath("sim"));
1577                         return true;
1578                 }
1579         }
1580
1581         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1582             c == '%' || c == '_' || c == '^') {
1583                 cur.niceInsert(createInsetMath(docstring(1, c)));
1584                 return true;
1585         }
1586
1587
1588         // try auto-correction
1589         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1590         //      return true;
1591
1592         // no special circumstances, so insert the character without any fuss
1593         cur.insert(c);
1594         cur.autocorrect() = true;
1595         return true;
1596 }
1597
1598
1599 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1600 {
1601         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1602         // possible
1603         if (!cur.empty() && cur.pos() > 0 &&
1604             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1605                 if (InsetMathBig::isBigInsetDelim(str)) {
1606                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1607                         if (prev[0] == '\\') {
1608                                 prev = prev.substr(1);
1609                                 latexkeys const * l = in_word_set(prev);
1610                                 if (l && l->inset == "big") {
1611                                         cur.cell()[cur.pos() - 1] =
1612                                                 MathAtom(new InsetMathBig(prev, str));
1613                                         return true;
1614                                 }
1615                         }
1616                 }
1617         }
1618         return false;
1619 }
1620
1621
1622 bool InsetMathNest::script(Cursor & cur, bool up)
1623 {
1624         return script(cur, up, docstring());
1625 }
1626
1627
1628 bool InsetMathNest::script(Cursor & cur, bool up,
1629                 docstring const & save_selection)
1630 {
1631         // Hack to get \^ and \_ working
1632         //lyxerr << "handling script: up: " << up << endl;
1633         if (cur.inMacroMode() && cur.macroName() == "\\") {
1634                 if (up)
1635                         cur.niceInsert(createInsetMath("mathcircumflex"));
1636                 else
1637                         interpretChar(cur, '_');
1638                 return true;
1639         }
1640
1641         cur.macroModeClose();
1642         if (asScriptInset() && cur.idx() == 0) {
1643                 // we are in a nucleus of a script inset, move to _our_ script
1644                 InsetMathScript * inset = asScriptInset();
1645                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1646                 inset->ensure(up);
1647                 cur.idx() = inset->idxOfScript(up);
1648                 cur.pos() = 0;
1649         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1650                 --cur.pos();
1651                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1652                 cur.push(*inset);
1653                 inset->ensure(up);
1654                 cur.idx() = inset->idxOfScript(up);
1655                 cur.pos() = cur.lastpos();
1656         } else {
1657                 // convert the thing to our left to a scriptinset or create a new
1658                 // one if in the very first position of the array
1659                 if (cur.pos() == 0) {
1660                         //lyxerr << "new scriptinset" << endl;
1661                         cur.insert(new InsetMathScript(up));
1662                 } else {
1663                         //lyxerr << "converting prev atom " << endl;
1664                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1665                 }
1666                 --cur.pos();
1667                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1668                 // See comment in MathParser.cpp for special handling of {}-bases
1669
1670                 cur.push(*inset);
1671                 cur.idx() = 1;
1672                 cur.pos() = 0;
1673         }
1674         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1675         cur.niceInsert(save_selection);
1676         cur.resetAnchor();
1677         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1678         return true;
1679 }
1680
1681
1682 bool InsetMathNest::completionSupported(Cursor const & cur) const
1683 {
1684         return cur.inMacroMode();
1685 }
1686
1687
1688 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1689 {
1690         return cur.inMacroMode();
1691 }
1692
1693
1694 bool InsetMathNest::automaticInlineCompletion() const
1695 {
1696         return lyxrc.completion_inline_math;
1697 }
1698
1699
1700 bool InsetMathNest::automaticPopupCompletion() const
1701 {
1702         return lyxrc.completion_popup_math;
1703 }
1704
1705
1706 CompletionList const *
1707 InsetMathNest::createCompletionList(Cursor const & cur) const
1708 {
1709         if (!cur.inMacroMode())
1710                 return 0;
1711
1712         return new MathCompletionList(cur);
1713 }
1714
1715
1716 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1717 {
1718         if (!cur.inMacroMode())
1719                 return docstring();
1720
1721         return cur.activeMacro()->name();
1722 }
1723
1724
1725 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1726                                      bool finished)
1727 {
1728         if (!cur.inMacroMode())
1729                 return false;
1730
1731         // append completion to active macro
1732         InsetMathUnknown * inset = cur.activeMacro();
1733         inset->setName(inset->name() + s);
1734
1735         // finish macro
1736         if (finished) {
1737 #if 0
1738                 // FIXME: this creates duplicates in the completion popup
1739                 // which looks ugly. Moreover the changes the list lengths
1740                 // which seems to
1741                 confuse the popup as well.
1742                 MathCompletionList::addToFavorites(inset->name());
1743 #endif
1744                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1745         }
1746
1747         return true;
1748 }
1749
1750
1751 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
1752                                         Dimension & dim) const
1753 {
1754         Inset const * inset = cur.activeMacro();
1755         if (!inset)
1756                 return;
1757
1758         // get inset dimensions
1759         dim = cur.bv().coordCache().insets().dim(inset);
1760         // FIXME: these 3 are no accurate, but should depend on the font.
1761         // Now the popup jumps down if you enter a char with descent > 0.
1762         dim.des += 3;
1763         dim.asc += 3;
1764
1765         // and position
1766         Point xy
1767         = cur.bv().coordCache().insets().xy(inset);
1768         x = xy.x_;
1769         y = xy.y_;
1770 }
1771
1772
1773 bool InsetMathNest::cursorMathForward(Cursor & cur)
1774 {
1775         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1776                 cur.pushBackward(*cur.nextAtom().nucleus());
1777                 cur.inset().idxFirst(cur);
1778                 return true;
1779         }
1780         if (cur.posForward() || idxForward(cur))
1781                 return true;
1782         // try to pop forwards --- but don't pop out of math! leave that to
1783         // the FINISH lfuns
1784         int s = cur.depth() - 2;
1785         if (s >= 0 && cur[s].inset().asInsetMath())
1786                 return cur.popForward();
1787         return false;
1788 }
1789
1790
1791 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1792 {
1793         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1794                 cur.posBackward();
1795                 cur.push(*cur.nextAtom().nucleus());
1796                 cur.inset().idxLast(cur);
1797                 return true;
1798         }
1799         if (cur.posBackward() || idxBackward(cur))
1800                 return true;
1801         // try to pop backwards --- but don't pop out of math! leave that to
1802         // the FINISH lfuns
1803         int s = cur.depth() - 2;
1804         if (s >= 0 && cur[s].inset().asInsetMath())
1805                 return cur.popBackward();
1806         return false;
1807 }
1808
1809
1810 ////////////////////////////////////////////////////////////////////
1811
1812 MathCompletionList::MathCompletionList(Cursor const & cur)
1813 {
1814         // fill it with macros from the buffer
1815         MacroNameSet macros;
1816         cur.buffer().listMacroNames(macros);
1817         MacroNameSet::const_iterator it;
1818         for (it = macros.begin(); it != macros.end(); ++it) {
1819                 if (cur.buffer().getMacro(*it, cur, false))
1820                         locals.push_back("\\" + *it);
1821         }
1822         sort(locals.begin(), locals.end());
1823
1824         if (globals.size() > 0)
1825                 return;
1826
1827         // fill in global macros
1828         macros.clear();
1829         MacroTable::globalMacros().getMacroNames(macros);
1830         //lyxerr << "Globals completion macros: ";
1831         for (it = macros.begin(); it != macros.end(); ++it) {
1832                 //lyxerr << "\\" + *it << " ";
1833                 globals.push_back("\\" + *it);
1834         }
1835         //lyxerr << std::endl;
1836
1837         // fill in global commands
1838         globals.push_back(from_ascii("\\boxed"));
1839         globals.push_back(from_ascii("\\fbox"));
1840         globals.push_back(from_ascii("\\framebox"));
1841         globals.push_back(from_ascii("\\makebox"));
1842         globals.push_back(from_ascii("\\kern"));
1843         globals.push_back(from_ascii("\\xrightarrow"));
1844         globals.push_back(from_ascii("\\xleftarrow"));
1845         globals.push_back(from_ascii("\\split"));
1846         globals.push_back(from_ascii("\\gathered"));
1847         globals.push_back(from_ascii("\\aligned"));
1848         globals.push_back(from_ascii("\\alignedat"));
1849         globals.push_back(from_ascii("\\cases"));
1850         globals.push_back(from_ascii("\\substack"));
1851         globals.push_back(from_ascii("\\xymatrix"));
1852         globals.push_back(from_ascii("\\subarray"));
1853         globals.push_back(from_ascii("\\array"));
1854         globals.push_back(from_ascii("\\sqrt"));
1855         globals.push_back(from_ascii("\\root"));
1856         globals.push_back(from_ascii("\\tabular"));
1857         globals.push_back(from_ascii("\\stackrel"));
1858         globals.push_back(from_ascii("\\binom"));
1859         globals.push_back(from_ascii("\\choose"));
1860         globals.push_back(from_ascii("\\brace"));
1861         globals.push_back(from_ascii("\\brack"));
1862         globals.push_back(from_ascii("\\frac"));
1863         globals.push_back(from_ascii("\\over"));
1864         globals.push_back(from_ascii("\\nicefrac"));
1865         globals.push_back(from_ascii("\\unitfrac"));
1866         globals.push_back(from_ascii("\\unitfracthree"));
1867         globals.push_back(from_ascii("\\unitone"));
1868         globals.push_back(from_ascii("\\unittwo"));
1869         globals.push_back(from_ascii("\\infer"));
1870         globals.push_back(from_ascii("\\atop"));
1871         globals.push_back(from_ascii("\\lefteqn"));
1872         globals.push_back(from_ascii("\\boldsymbol"));
1873         globals.push_back(from_ascii("\\bm"));
1874         globals.push_back(from_ascii("\\color"));
1875         globals.push_back(from_ascii("\\normalcolor"));
1876         globals.push_back(from_ascii("\\textcolor"));
1877         globals.push_back(from_ascii("\\dfrac"));
1878         globals.push_back(from_ascii("\\tfrac"));
1879         globals.push_back(from_ascii("\\dbinom"));
1880         globals.push_back(from_ascii("\\tbinom"));
1881         globals.push_back(from_ascii("\\hphantom"));
1882         globals.push_back(from_ascii("\\phantom"));
1883         globals.push_back(from_ascii("\\vphantom"));
1884         MathWordList const & words = mathedWordList();
1885         MathWordList::const_iterator it2;
1886         //lyxerr << "Globals completion commands: ";
1887         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1888                 globals.push_back("\\" + (*it2).first);
1889                 //lyxerr << "\\" + (*it2).first << " ";
1890         }
1891         //lyxerr << std::endl;
1892         sort(globals.begin(), globals.end());
1893 }
1894
1895
1896 MathCompletionList::~MathCompletionList()
1897 {
1898 }
1899
1900
1901 size_type MathCompletionList::size() const
1902 {
1903         return locals.size() + globals.size();
1904 }
1905
1906
1907 docstring const & MathCompletionList::data(size_t idx) const
1908 {
1909         size_t lsize = locals.size();
1910         if (idx >= lsize)
1911                 return globals[idx - lsize];
1912         else
1913                 return locals[idx];
1914 }
1915
1916
1917 std::string MathCompletionList::icon(size_t idx) const
1918 {
1919         // get the latex command
1920         docstring cmd;
1921         size_t lsize = locals.size();
1922         if (idx >= lsize)
1923                 cmd = globals[idx - lsize];
1924         else
1925                 cmd = locals[idx];
1926
1927         // get the icon resource name by stripping the backslash
1928         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1929 }
1930
1931 std::vector<docstring> MathCompletionList::globals;
1932
1933 } // namespace lyx