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