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