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