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