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