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