]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
Two fixes involving RtL text drawing
[lyx.git] / src / mathed / math_nestinset.C
1 /**
2  * \file math_nestinset.C
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 "math_nestinset.h"
14
15 #include "math_arrayinset.h"
16 #include "math_boxinset.h"
17 #include "math_braceinset.h"
18 #include "math_colorinset.h"
19 #include "math_commentinset.h"
20 #include "math_data.h"
21 #include "math_deliminset.h"
22 #include "math_factory.h"
23 #include "math_hullinset.h"
24 #include "math_mathmlstream.h"
25 #include "math_macroarg.h"
26 //#include "math_mboxinset.h"
27 #include "math_parser.h"
28 #include "math_scriptinset.h"
29 #include "math_spaceinset.h"
30 #include "math_symbolinset.h"
31 #include "math_support.h"
32 #include "math_unknowninset.h"
33
34 #include "BufferView.h"
35 #include "CutAndPaste.h"
36 #include "FuncStatus.h"
37 #include "LColor.h"
38 #include "bufferview_funcs.h"
39 #include "coordcache.h"
40 #include "cursor.h"
41 #include "debug.h"
42 #include "dispatchresult.h"
43 #include "funcrequest.h"
44 #include "gettext.h"
45 #include "outputparams.h"
46 #include "undo.h"
47
48 #include "support/lstrings.h"
49
50 #include "frontends/Dialogs.h"
51 #include "frontends/LyXView.h"
52 #include "frontends/Painter.h"
53
54 #include <sstream>
55
56 using lyx::cap::copySelection;
57 using lyx::cap::grabAndEraseSelection;
58 using lyx::cap::cutSelection;
59 using lyx::cap::pasteSelection;
60 using lyx::cap::replaceSelection;
61 using lyx::cap::selClearOrDel;
62
63 using std::endl;
64 using std::string;
65 using std::istringstream;
66
67
68 MathNestInset::MathNestInset(idx_type nargs)
69         : cells_(nargs), lock_(false)
70 {}
71
72
73 MathInset::idx_type MathNestInset::nargs() const
74 {
75         return cells_.size();
76 }
77
78
79 MathArray & MathNestInset::cell(idx_type i)
80 {
81         return cells_[i];
82 }
83
84
85 MathArray const & MathNestInset::cell(idx_type i) const
86 {
87         return cells_[i];
88 }
89
90
91 void MathNestInset::cursorPos(CursorSlice const & sl, bool /*boundary*/,
92         int & x, int & y) const
93 {
94 // FIXME: This is a hack. Ideally, the coord cache should not store
95 // absolute positions, but relative ones. This would mean to call
96 // setXY() not in MathArray::draw(), but in the parent insets' draw()
97 // with the correctly adjusted x,y values. But this means that we'd have
98 // to touch all (math)inset's draw() methods. Right now, we'll store
99 // absolute value, and make them here relative, only to make them
100 // absolute again when actually drawing the cursor. What a mess.
101         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
102         MathArray const & ar = sl.cell();
103         if (!theCoords.getArrays().has(&ar)) {
104                 // this can (semi-)legally happen if we just created this cell
105                 // and it never has been drawn before. So don't ASSERT.
106                 //lyxerr << "no cached data for array " << &ar << endl;
107                 x = 0;
108                 y = 0;
109                 return;
110         }
111         Point const pt = theCoords.getArrays().xy(&ar);
112         if (!theCoords.getInsets().has(this)) {
113                 // same as above
114                 //lyxerr << "no cached data for inset " << this << endl;
115                 x = 0;
116                 y = 0;
117                 return;
118         }
119         Point const pt2 = theCoords.getInsets().xy(this);
120         //lyxerr << "retrieving position cache for MathArray "
121         //      << pt.x_ << ' ' << pt.y_ << std::endl;
122         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
123         y = pt.y_ - pt2.y_;
124 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
125 //              << " asc: " << ascent() << "  des: " << descent()
126 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
127         // move cursor visually into empty cells ("blue rectangles");
128         if (ar.empty())
129                 x += 2;
130 }
131
132
133 void MathNestInset::metrics(MetricsInfo const & mi) const
134 {
135         MetricsInfo m = mi;
136         for (idx_type i = 0, n = nargs(); i != n; ++i)
137                 cell(i).metrics(m);
138 }
139
140
141 bool MathNestInset::idxNext(LCursor & cur) const
142 {
143         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
144         if (cur.idx() == cur.lastidx())
145                 return false;
146         ++cur.idx();
147         cur.pos() = 0;
148         return true;
149 }
150
151
152 bool MathNestInset::idxRight(LCursor & cur) const
153 {
154         return idxNext(cur);
155 }
156
157
158 bool MathNestInset::idxPrev(LCursor & cur) const
159 {
160         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
161         if (cur.idx() == 0)
162                 return false;
163         --cur.idx();
164         cur.pos() = cur.lastpos();
165         return true;
166 }
167
168
169 bool MathNestInset::idxLeft(LCursor & cur) const
170 {
171         return idxPrev(cur);
172 }
173
174
175 bool MathNestInset::idxFirst(LCursor & cur) const
176 {
177         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
178         if (nargs() == 0)
179                 return false;
180         cur.idx() = 0;
181         cur.pos() = 0;
182         return true;
183 }
184
185
186 bool MathNestInset::idxLast(LCursor & cur) const
187 {
188         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
189         if (nargs() == 0)
190                 return false;
191         cur.idx() = cur.lastidx();
192         cur.pos() = cur.lastpos();
193         return true;
194 }
195
196
197 void MathNestInset::dump() const
198 {
199         WriteStream os(lyxerr);
200         os << "---------------------------------------------\n";
201         write(os);
202         os << "\n";
203         for (idx_type i = 0, n = nargs(); i != n; ++i)
204                 os << cell(i) << "\n";
205         os << "---------------------------------------------\n";
206 }
207
208
209 void MathNestInset::draw(PainterInfo & pi, int x, int y) const
210 {
211 #if 0
212         if (lock_)
213                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
214                                         LColor::mathlockbg);
215 #endif
216         setPosCache(pi, x, y);
217 }
218
219
220 void MathNestInset::drawSelection(PainterInfo & pi, int x, int y) const
221 {
222         // FIXME: hack to get position cache warm
223         draw(pi, x, y);
224
225         // this should use the x/y values given, not the cached values
226         LCursor & cur = pi.base.bv->cursor();
227         if (!cur.selection())
228                 return;
229         if (!ptr_cmp(&cur.inset(), this))
230                 return;
231
232         CursorSlice s1 = cur.selBegin();
233         CursorSlice s2 = cur.selEnd();
234         //lyxerr << "MathNestInset::drawing selection: "
235         //      << " s1: " << s1 << " s2: " << s2 << endl;
236         if (s1.idx() == s2.idx()) {
237                 MathArray const & c = cell(s1.idx());
238                 int x1 = c.xo() + c.pos2x(s1.pos());
239                 int y1 = c.yo() - c.ascent();
240                 int x2 = c.xo() + c.pos2x(s2.pos());
241                 int y2 = c.yo() + c.descent();
242                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
243         //lyxerr << "MathNestInset::drawing selection 3: "
244         //      << " x1: " << x1 << " x2: " << x2
245         //      << " y1: " << y1 << " y2: " << y2 << endl;
246         } else {
247                 for (idx_type i = 0; i < nargs(); ++i) {
248                         if (idxBetween(i, s1.idx(), s2.idx())) {
249                                 MathArray const & c = cell(i);
250                                 int x1 = c.xo();
251                                 int y1 = c.yo() - c.ascent();
252                                 int x2 = c.xo() + c.width();
253                                 int y2 = c.yo() + c.descent();
254                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
255                         }
256                 }
257         }
258 }
259
260
261 void MathNestInset::validate(LaTeXFeatures & features) const
262 {
263         for (idx_type i = 0; i < nargs(); ++i)
264                 cell(i).validate(features);
265 }
266
267
268 void MathNestInset::replace(ReplaceData & rep)
269 {
270         for (idx_type i = 0; i < nargs(); ++i)
271                 cell(i).replace(rep);
272 }
273
274
275 bool MathNestInset::contains(MathArray const & ar) const
276 {
277         for (idx_type i = 0; i < nargs(); ++i)
278                 if (cell(i).contains(ar))
279                         return true;
280         return false;
281 }
282
283
284 bool MathNestInset::lock() const
285 {
286         return lock_;
287 }
288
289
290 void MathNestInset::lock(bool l)
291 {
292         lock_ = l;
293 }
294
295
296 bool MathNestInset::isActive() const
297 {
298         return nargs() > 0;
299 }
300
301
302 MathArray MathNestInset::glue() const
303 {
304         MathArray ar;
305         for (size_t i = 0; i < nargs(); ++i)
306                 ar.append(cell(i));
307         return ar;
308 }
309
310
311 void MathNestInset::write(WriteStream & os) const
312 {
313         os << '\\' << name().c_str();
314         for (size_t i = 0; i < nargs(); ++i)
315                 os << '{' << cell(i) << '}';
316         if (nargs() == 0)
317                 os.pendingSpace(true);
318         if (lock_ && !os.latex()) {
319                 os << "\\lyxlock";
320                 os.pendingSpace(true);
321         }
322 }
323
324
325 void MathNestInset::normalize(NormalStream & os) const
326 {
327         os << '[' << name().c_str();
328         for (size_t i = 0; i < nargs(); ++i)
329                 os << ' ' << cell(i);
330         os << ']';
331 }
332
333
334 int MathNestInset::latex(Buffer const &, std::ostream & os,
335                         OutputParams const & runparams) const
336 {
337         WriteStream wi(os, runparams.moving_arg, true);
338         write(wi);
339         return wi.line();
340 }
341
342
343 void MathNestInset::notifyCursorLeaves(LCursor & /*cur*/)
344 {
345 #ifdef WITH_WARNINGS
346 #warning look here
347 #endif
348 #if 0
349         MathArray & ar = cur.cell();
350         // remove base-only "scripts"
351         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
352                 MathScriptInset * p = operator[](i).nucleus()->asScriptInset();
353                 if (p && p->nargs() == 1) {
354                         MathArray ar = p->nuc();
355                         erase(i);
356                         insert(i, ar);
357                         cur.adjust(i, ar.size() - 1);
358                 }
359         }
360
361         // glue adjacent font insets of the same kind
362         for (pos_type i = 0; i + 1 < size(); ++i) {
363                 MathFontInset * p = operator[](i).nucleus()->asFontInset();
364                 MathFontInset const * q = operator[](i + 1)->asFontInset();
365                 if (p && q && p->name() == q->name()) {
366                         p->cell(0).append(q->cell(0));
367                         erase(i + 1);
368                         cur.adjust(i, -1);
369                 }
370         }
371 #endif
372 }
373
374
375 void MathNestInset::handleFont
376         (LCursor & cur, string const & arg, string const & font)
377 {
378         // this whole function is a hack and won't work for incremental font
379         // changes...
380         recordUndo(cur, Undo::ATOMIC);
381
382         if (cur.inset().asMathInset()->name() == font)
383                 cur.handleFont(font);
384         else {
385                 cur.handleNest(createMathInset(font));
386                 cur.insert(arg);
387         }
388 }
389
390
391 void MathNestInset::handleFont2(LCursor & cur, string const & arg)
392 {
393         recordUndo(cur, Undo::ATOMIC);
394         LyXFont font;
395         bool b;
396         bv_funcs::string2font(arg, font, b);
397         if (font.color() != LColor::inherit) {
398                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
399                 cur.handleNest(at, 0);
400         }
401 }
402
403
404 void MathNestInset::doDispatch(LCursor & cur, FuncRequest & cmd)
405 {
406         //lyxerr << "MathNestInset: request: " << cmd << std::endl;
407         //CursorSlice sl = cur.current();
408
409         switch (cmd.action) {
410
411         case LFUN_PASTE: {
412                 recordUndo(cur);
413                 cur.message(_("Paste"));
414                 replaceSelection(cur);
415                 size_t n = 0;
416                 istringstream is(cmd.argument);
417                 is >> n;
418                 pasteSelection(cur, n);
419                 cur.clearSelection(); // bug 393
420                 cur.bv().switchKeyMap();
421                 finishUndo();
422                 break;
423         }
424
425         case LFUN_CUT:
426                 recordUndo(cur);
427                 cutSelection(cur, true, true);
428                 cur.message(_("Cut"));
429                 // Prevent stale position >= size crash
430                 cur.normalize();
431                 break;
432
433         case LFUN_COPY:
434                 copySelection(cur);
435                 cur.message(_("Copy"));
436                 break;
437
438         case LFUN_MOUSE_PRESS:
439                 lfunMousePress(cur, cmd);
440                 break;
441
442         case LFUN_MOUSE_MOTION:
443                 lfunMouseMotion(cur, cmd);
444                 break;
445
446         case LFUN_MOUSE_RELEASE:
447                 lfunMouseRelease(cur, cmd);
448                 break;
449
450         case LFUN_FINISHED_LEFT:
451                 cur.bv().cursor() = cur;
452                 break;
453
454         case LFUN_FINISHED_RIGHT:
455                 ++cur.pos();
456                 cur.bv().cursor() = cur;
457                 break;
458
459         case LFUN_FINISHED_UP:
460                 cur.bv().cursor() = cur;
461                 break;
462
463         case LFUN_FINISHED_DOWN:
464                 ++cur.pos();
465                 cur.bv().cursor() = cur;
466                 break;
467
468         case LFUN_RIGHTSEL:
469         case LFUN_RIGHT:
470                 cur.selHandle(cmd.action == LFUN_RIGHTSEL);
471                 cur.autocorrect() = false;
472                 cur.clearTargetX();
473                 cur.macroModeClose();
474                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
475                         cur.pushLeft(*cur.nextAtom().nucleus());
476                         cur.inset().idxFirst(cur);
477                 } else if (cur.posRight() || idxRight(cur)
478                         || cur.popRight() || cur.selection())
479                         ;
480                 else {
481                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
482                         cur.undispatched();
483                 }
484                 break;
485
486         case LFUN_LEFTSEL:
487         case LFUN_LEFT:
488                 cur.selHandle(cmd.action == LFUN_LEFTSEL);
489                 cur.autocorrect() = false;
490                 cur.clearTargetX();
491                 cur.macroModeClose();
492                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
493                         cur.posLeft();
494                         cur.push(*cur.nextAtom().nucleus());
495                         cur.inset().idxLast(cur);
496                 } else if (cur.posLeft() || idxLeft(cur)
497                         || cur.popLeft() || cur.selection())
498                         ;
499                 else {
500                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
501                         cur.undispatched();
502                 }
503                 break;
504
505         case LFUN_UPSEL:
506         case LFUN_UP:
507                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
508                 if (cur.inMacroMode()) {
509                         // Make Helge happy
510                         cur.macroModeClose();
511                         break;
512                 }
513                 cur.selHandle(cmd.action == LFUN_UPSEL);
514                 if (!cur.up()) {
515                         cmd = FuncRequest(LFUN_FINISHED_UP);
516                         cur.undispatched();
517                 }
518                 // fixes bug 1598. Please check!
519                 cur.normalize();
520                 break;
521
522         case LFUN_DOWNSEL:
523         case LFUN_DOWN:
524                 if (cur.inMacroMode()) {
525                         cur.macroModeClose();
526                         break;
527                 }
528                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
529                 if (!cur.down()) {
530                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
531                         cur.undispatched();
532                 }
533                 // fixes bug 1598. Please check!
534                 cur.normalize();
535                 break;
536
537         case LFUN_MOUSE_DOUBLE:
538         case LFUN_MOUSE_TRIPLE:
539         case LFUN_WORDSEL:
540                 cur.pos() = 0;
541                 cur.idx() = 0;
542                 cur.resetAnchor();
543                 cur.selection() = true;
544                 cur.pos() = cur.lastpos();
545                 cur.idx() = cur.lastidx();
546                 break;
547
548         case LFUN_UP_PARAGRAPHSEL:
549         case LFUN_UP_PARAGRAPH:
550         case LFUN_DOWN_PARAGRAPHSEL:
551         case LFUN_DOWN_PARAGRAPH:
552                 break;
553
554         case LFUN_HOMESEL:
555         case LFUN_HOME:
556         case LFUN_WORDLEFTSEL:
557         case LFUN_WORDLEFT:
558                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
559                 cur.macroModeClose();
560                 if (cur.pos() != 0) {
561                         cur.pos() = 0;
562                 } else if (cur.col() != 0) {
563                         cur.idx() -= cur.col();
564                         cur.pos() = 0;
565                 } else if (cur.idx() != 0) {
566                         cur.idx() = 0;
567                         cur.pos() = 0;
568                 } else {
569                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
570                         cur.undispatched();
571                 }
572                 break;
573
574         case LFUN_WORDRIGHTSEL:
575         case LFUN_WORDRIGHT:
576         case LFUN_ENDSEL:
577         case LFUN_END:
578                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
579                 cur.macroModeClose();
580                 cur.clearTargetX();
581                 if (cur.pos() != cur.lastpos()) {
582                         cur.pos() = cur.lastpos();
583                 } else if (ncols() && (cur.col() != cur.lastcol())) {
584                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
585                         cur.pos() = cur.lastpos();
586                 } else if (cur.idx() != cur.lastidx()) {
587                         cur.idx() = cur.lastidx();
588                         cur.pos() = cur.lastpos();
589                 } else {
590                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
591                         cur.undispatched();
592                 }
593                 break;
594
595         case LFUN_PRIORSEL:
596         case LFUN_PRIOR:
597                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
598                 cur.undispatched();
599                 break;
600
601         case LFUN_NEXTSEL:
602         case LFUN_NEXT:
603                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
604                 cur.undispatched();
605                 break;
606
607         case LFUN_CELL_FORWARD:
608                 cur.inset().idxNext(cur);
609                 break;
610
611         case LFUN_CELL_BACKWARD:
612                 cur.inset().idxPrev(cur);
613                 break;
614
615         case LFUN_DELETE_WORD_BACKWARD:
616         case LFUN_BACKSPACE:
617                 if (cur.pos() == 0)
618                         // delete whole cell
619                         recordUndoInset(cur, Undo::ATOMIC);
620                 else
621                         recordUndo(cur, Undo::ATOMIC);
622                 cur.backspace();
623                 break;
624
625         case LFUN_DELETE_WORD_FORWARD:
626         case LFUN_DELETE:
627                 recordUndo(cur);
628                 cur.erase();
629                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
630                 cur.undispatched();
631                 break;
632
633         case LFUN_ESCAPE:
634                 if (cur.selection())
635                         cur.clearSelection();
636                 else  {
637                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
638                         cur.undispatched();
639                 }
640                 break;
641
642         case LFUN_INSET_TOGGLE:
643                 recordUndo(cur);
644                 //lockToggle();
645                 if (cur.pos() != cur.lastpos()) {
646                         // toggle previous inset ...
647                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
648                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
649                         // ... or enclosing inset if we are in the last inset position
650                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
651                         ++cur.pos();
652                 }
653                 break;
654
655         case LFUN_SELFINSERT:
656                 recordUndo(cur);
657                 if (cmd.argument.size() != 1) {
658                         cur.insert(cmd.argument);
659                         break;
660                 }
661                 if (!interpret(cur, cmd.argument[0])) {
662                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
663                         cur.undispatched();
664                 }
665                 break;
666
667         //case LFUN_GETXY:
668         //      sprintf(dispatch_buffer, "%d %d",);
669         //      break;
670
671         case LFUN_SETXY: {
672                 lyxerr << "LFUN_SETXY broken!" << endl;
673                 int x = 0;
674                 int y = 0;
675                 istringstream is(cmd.argument);
676                 is >> x >> y;
677                 cur.setScreenPos(x, y);
678                 break;
679         }
680
681         // Special casing for superscript in case of LyX handling
682         // dead-keys:
683         case LFUN_CIRCUMFLEX:
684                 if (cmd.argument.empty()) {
685                         // do superscript if LyX handles
686                         // deadkeys
687                         recordUndo(cur, Undo::ATOMIC);
688                         script(cur, true);
689                 }
690                 break;
691
692         case LFUN_UMLAUT:
693         case LFUN_ACUTE:
694         case LFUN_GRAVE:
695         case LFUN_BREVE:
696         case LFUN_DOT:
697         case LFUN_MACRON:
698         case LFUN_CARON:
699         case LFUN_TILDE:
700         case LFUN_CEDILLA:
701         case LFUN_CIRCLE:
702         case LFUN_UNDERDOT:
703         case LFUN_TIE:
704         case LFUN_OGONEK:
705         case LFUN_HUNG_UMLAUT:
706                 break;
707
708         //  Math fonts
709         case LFUN_FREEFONT_APPLY:
710         case LFUN_FREEFONT_UPDATE:
711                 handleFont2(cur, cmd.argument);
712                 break;
713
714         case LFUN_BOLD:
715                 if (currentMode() == TEXT_MODE)
716                         handleFont(cur, cmd.argument, "textbf");
717                 else
718                         handleFont(cur, cmd.argument, "mathbf");
719                 break;
720         case LFUN_SANS:
721                 if (currentMode() == TEXT_MODE)
722                         handleFont(cur, cmd.argument, "textsf");
723                 else
724                         handleFont(cur, cmd.argument, "mathsf");
725                 break;
726         case LFUN_EMPH:
727                 if (currentMode() == TEXT_MODE)
728                         handleFont(cur, cmd.argument, "emph");
729                 else
730                         handleFont(cur, cmd.argument, "mathcal");
731                 break;
732         case LFUN_ROMAN:
733                 if (currentMode() == TEXT_MODE)
734                         handleFont(cur, cmd.argument, "textrm");
735                 else
736                         handleFont(cur, cmd.argument, "mathrm");
737                 break;
738         case LFUN_CODE:
739                 if (currentMode() == TEXT_MODE)
740                         handleFont(cur, cmd.argument, "texttt");
741                 else
742                         handleFont(cur, cmd.argument, "mathtt");
743                 break;
744         case LFUN_FRAK:
745                 handleFont(cur, cmd.argument, "mathfrak");
746                 break;
747         case LFUN_ITAL:
748                 if (currentMode() == TEXT_MODE)
749                         handleFont(cur, cmd.argument, "textit");
750                 else
751                         handleFont(cur, cmd.argument, "mathit");
752                 break;
753         case LFUN_NOUN:
754                 if (currentMode() == TEXT_MODE)
755                         // FIXME: should be "noun"
756                         handleFont(cur, cmd.argument, "textsc");
757                 else
758                         handleFont(cur, cmd.argument, "mathbb");
759                 break;
760         //case LFUN_FREEFONT_APPLY:
761                 handleFont(cur, cmd.argument, "textrm");
762                 break;
763         case LFUN_DEFAULT:
764                 handleFont(cur, cmd.argument, "textnormal");
765                 break;
766
767         case LFUN_MATH_MODE:
768 #if 1
769                 // ignore math-mode on when already in math mode
770                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
771                         break;
772                 cur.macroModeClose();
773                 selClearOrDel(cur);
774                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
775                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
776                 cur.posLeft();
777                 cur.pushLeft(*cur.nextInset());
778 #else
779                 if (currentMode() == InsetBase::TEXT_MODE) {
780                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
781                         cur.message(_("create new math text environment ($...$)"));
782                 } else {
783                         handleFont(cur, cmd.argument, "textrm");
784                         cur.message(_("entered math text mode (textrm)"));
785                 }
786 #endif
787                 break;
788
789         case LFUN_MATH_SIZE:
790 #if 0
791                 recordUndo(cur);
792                 cur.setSize(arg);
793 #endif
794                 break;
795
796         case LFUN_INSERT_MATRIX: {
797                 recordUndo(cur, Undo::ATOMIC);
798                 unsigned int m = 1;
799                 unsigned int n = 1;
800                 string v_align;
801                 string h_align;
802                 istringstream is(cmd.argument);
803                 is >> m >> n >> v_align >> h_align;
804                 if (m < 1)
805                         m = 1;
806                 if (n < 1)
807                         n = 1;
808                 v_align += 'c';
809                 cur.niceInsert(
810                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
811                 break;
812         }
813
814         case LFUN_MATH_DELIM: {
815                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
816                 string ls;
817                 string rs = lyx::support::split(cmd.argument, ls, ' ');
818                 // Reasonable default values
819                 if (ls.empty())
820                         ls = '(';
821                 if (rs.empty())
822                         rs = ')';
823                 recordUndo(cur, Undo::ATOMIC);
824                 // Don't do this with multi-cell selections
825                 if (cur.selBegin().idx() == cur.selEnd().idx())
826                         cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
827                 break;
828         }
829
830         case LFUN_SPACE_INSERT:
831         case LFUN_MATH_SPACE:
832                 recordUndo(cur, Undo::ATOMIC);
833                 cur.insert(MathAtom(new MathSpaceInset(",")));
834                 break;
835
836         case LFUN_INSET_ERT:
837                 // interpret this as if a backslash was typed
838                 recordUndo(cur, Undo::ATOMIC);
839                 interpret(cur, '\\');
840                 break;
841
842         case LFUN_SUBSCRIPT:
843                 // interpret this as if a _ was typed
844                 recordUndo(cur, Undo::ATOMIC);
845                 interpret(cur, '_');
846                 break;
847
848         case LFUN_SUPERSCRIPT:
849                 // interpret this as if a ^ was typed
850                 recordUndo(cur, Undo::ATOMIC);
851                 interpret(cur, '^');
852                 break;
853
854 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
855 // handling such that "self-insert" works on "arbitrary stuff" too, and
856 // math-insert only handles special math things like "matrix".
857         case LFUN_INSERT_MATH: {
858                 recordUndo(cur, Undo::ATOMIC);
859                 MathArray ar;
860                 asArray(cmd.argument, ar);
861                 int cell(0);
862                 if (cmd.argument == "\\root")
863                         cell = 1;
864                 if (ar.size() == 1 && (ar[0].nucleus()->asNestInset())) {
865                         cur.handleNest(ar[0], cell);
866                 } else
867                         cur.niceInsert(cmd.argument);
868                 break;
869                 }
870
871         case LFUN_DIALOG_SHOW_NEW_INSET: {
872                 string const & name = cmd.argument;
873                 string data;
874 #if 0
875                 if (name == "ref") {
876                         RefInset tmp(name);
877                         data = tmp.createDialogStr(name);
878                 }
879 #endif
880                 cur.bv().owner()->getDialogs().show(name, data, 0);
881                 break;
882         }
883
884         case LFUN_INSET_APPLY: {
885                 string const name = cmd.getArg(0);
886                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
887
888                 if (base) {
889                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
890                         base->dispatch(cur, fr);
891                         break;
892                 }
893                 MathArray ar;
894                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
895                         cur.insert(ar);
896                         break;
897                 }
898                 cur.undispatched();
899                 break;
900         }
901
902         default:
903                 MathDimInset::doDispatch(cur, cmd);
904                 break;
905         }
906 }
907
908
909 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
910                 FuncStatus & flag) const
911 {
912         // the font related toggles
913         //string tc = "mathnormal";
914         bool ret = true;
915         string const arg = cmd.argument;
916         switch (cmd.action) {
917         case LFUN_TABULAR_FEATURE:
918                 flag.enabled(false);
919                 break;
920 #if 0
921         case LFUN_TABULAR_FEATURE:
922                 // FIXME: check temporarily disabled
923                 // valign code
924                 char align = mathcursor::valign();
925                 if (align == '\0') {
926                         enable = false;
927                         break;
928                 }
929                 if (cmd.argument.empty()) {
930                         flag.clear();
931                         break;
932                 }
933                 if (!contains("tcb", cmd.argument[0])) {
934                         enable = false;
935                         break;
936                 }
937                 flag.setOnOff(cmd.argument[0] == align);
938                 break;
939 #endif
940         /// We have to handle them since 1.4 blocks all unhandled actions
941         case LFUN_ITAL:
942         case LFUN_BOLD:
943         case LFUN_SANS:
944         case LFUN_EMPH:
945         case LFUN_CODE:
946         case LFUN_NOUN:
947         case LFUN_ROMAN:
948         case LFUN_DEFAULT:
949                 flag.enabled(true);
950                 break;
951         case LFUN_MATH_MUTATE:
952                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
953                 flag.setOnOff(false);
954                 break;
955
956         // we just need to be in math mode to enable that
957         case LFUN_MATH_SIZE:
958         case LFUN_MATH_SPACE:
959         case LFUN_MATH_LIMITS:
960         case LFUN_MATH_NONUMBER:
961         case LFUN_MATH_NUMBER:
962         case LFUN_MATH_EXTERN:
963                 flag.enabled(true);
964                 break;
965
966         case LFUN_FRAK:
967                 flag.enabled(currentMode() != TEXT_MODE);
968                 break;
969
970         case LFUN_INSERT_MATH: {
971                 bool const textarg =
972                         arg == "\\textbf"   || arg == "\\textsf" ||
973                         arg == "\\textrm"   || arg == "\\textmd" ||
974                         arg == "\\textit"   || arg == "\\textsc" ||
975                         arg == "\\textsl"   || arg == "\\textup" ||
976                         arg == "\\texttt"   || arg == "\\textbb" ||
977                         arg == "\\textnormal";
978                 flag.enabled(currentMode() != TEXT_MODE || textarg);
979                 break;
980         }
981
982         case LFUN_INSERT_MATRIX:
983                 flag.enabled(currentMode() == MATH_MODE);
984                 break;
985         default:
986                 ret = false;
987                 break;
988         }
989         return ret;
990 }
991
992
993 void MathNestInset::edit(LCursor & cur, bool left)
994 {
995         cur.push(*this);
996         cur.idx() = left ? 0 : cur.lastidx();
997         cur.pos() = left ? 0 : cur.lastpos();
998         cur.resetAnchor();
999         //lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
1000 }
1001
1002
1003 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y)
1004 {
1005         int idx_min = 0;
1006         int dist_min = 1000000;
1007         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1008                 int const d = cell(i).dist(x, y);
1009                 if (d < dist_min) {
1010                         dist_min = d;
1011                         idx_min = i;
1012                 }
1013         }
1014         MathArray & ar = cell(idx_min);
1015         cur.push(*this);
1016         cur.idx() = idx_min;
1017         cur.pos() = ar.x2pos(x - ar.xo());
1018         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1019         if (dist_min == 0) {
1020                 // hit inside cell
1021                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1022                         if (ar[i]->covers(x, y))
1023                                 return ar[i].nucleus()->editXY(cur, x, y);
1024         }
1025         return this;
1026 }
1027
1028
1029 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1030 {
1031         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1032         if (cmd.button() == mouse_button::button1) {
1033                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1034                 cur.resetAnchor();
1035                 cur.bv().cursor() = cur;
1036         }
1037
1038         if (cmd.button() == mouse_button::button2) {
1039                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
1040         }
1041 }
1042
1043
1044 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1045 {
1046         // only select with button 1
1047         if (cmd.button() == mouse_button::button1) {
1048                 LCursor & bvcur = cur.bv().cursor();
1049                 if (bvcur.anchor_.hasPart(cur)) {
1050                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1051                         bvcur.setCursor(cur);
1052                         bvcur.selection() = true;
1053                         //lyxerr << "MOTION " << bvcur << endl;
1054                 }
1055                 else {
1056                         cur.undispatched();
1057                 }
1058         }
1059 }
1060
1061
1062 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1063 {
1064         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1065
1066         if (cmd.button() == mouse_button::button1) {
1067                 //cur.bv().stuffClipboard(cur.grabSelection());
1068                 return;
1069         }
1070
1071         if (cmd.button() == mouse_button::button2) {
1072                 MathArray ar;
1073                 asArray(cur.bv().getClipboard(), ar);
1074                 cur.clearSelection();
1075                 cur.setScreenPos(cmd.x, cmd.y);
1076                 cur.insert(ar);
1077                 cur.bv().update();
1078                 return;
1079         }
1080
1081         if (cmd.button() == mouse_button::button3) {
1082                 // try to dispatch to enclosed insets first
1083                 cur.bv().owner()->getDialogs().show("mathpanel");
1084                 return;
1085         }
1086
1087         cur.undispatched();
1088 }
1089
1090
1091 bool MathNestInset::interpret(LCursor & cur, char c)
1092 {
1093         //lyxerr << "interpret 2: '" << c << "'" << endl;
1094         cur.clearTargetX();
1095
1096         // handle macroMode
1097         if (cur.inMacroMode()) {
1098                 string name = cur.macroName();
1099
1100                 /// are we currently typing '#1' or '#2' or...?
1101                 if (name == "\\#") {
1102                         cur.backspace();
1103                         int n = c - '0';
1104                         if (n >= 1 && n <= 9)
1105                                 cur.insert(new MathMacroArgument(n));
1106                         return true;
1107                 }
1108
1109                 if (isalpha(c)) {
1110                         cur.activeMacro()->setName(name + c);
1111                         return true;
1112                 }
1113
1114                 // handle 'special char' macros
1115                 if (name == "\\") {
1116                         // remove the '\\'
1117                         if (c == '\\') {
1118                                 cur.backspace();
1119                                 if (currentMode() == MathInset::TEXT_MODE)
1120                                         cur.niceInsert(createMathInset("textbackslash"));
1121                                 else
1122                                         cur.niceInsert(createMathInset("backslash"));
1123                         } else if (c == '{') {
1124                                 cur.backspace();
1125                                 cur.niceInsert(MathAtom(new MathBraceInset));
1126                         } else if (c == '%') {
1127                                 cur.backspace();
1128                                 cur.niceInsert(MathAtom(new MathCommentInset));
1129                         } else if (c == '#') {
1130                                 BOOST_ASSERT(cur.activeMacro());
1131                                 cur.activeMacro()->setName(name + c);
1132                         } else {
1133                                 cur.backspace();
1134                                 cur.niceInsert(createMathInset(string(1, c)));
1135                         }
1136                         return true;
1137                 }
1138
1139                 // leave macro mode and try again if necessary
1140                 cur.macroModeClose();
1141                 if (c == '{')
1142                         cur.niceInsert(MathAtom(new MathBraceInset));
1143                 else if (c != ' ')
1144                         interpret(cur, c);
1145                 return true;
1146         }
1147
1148         // This is annoying as one has to press <space> far too often.
1149         // Disable it.
1150
1151 #if 0
1152                 // leave autocorrect mode if necessary
1153                 if (autocorrect() && c == ' ') {
1154                         autocorrect() = false;
1155                         return true;
1156                 }
1157 #endif
1158
1159         // just clear selection on pressing the space bar
1160         if (cur.selection() && c == ' ') {
1161                 cur.selection() = false;
1162                 return true;
1163         }
1164
1165         selClearOrDel(cur);
1166
1167         if (c == '\\') {
1168                 //lyxerr << "starting with macro" << endl;
1169                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1170                 return true;
1171         }
1172
1173         if (c == '\n') {
1174                 if (currentMode() == MathInset::TEXT_MODE)
1175                         cur.insert(c);
1176                 return true;
1177         }
1178
1179         if (c == ' ') {
1180                 if (currentMode() == MathInset::TEXT_MODE) {
1181                         // insert spaces in text mode,
1182                         // but suppress direct insertion of two spaces in a row
1183                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1184                         // it is better than nothing...
1185                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1186                                 cur.insert(c);
1187                         return true;
1188                 }
1189                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1190                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1191                         return true;
1192                 }
1193                 if (cur.popRight())
1194                         return true;
1195                 // if are at the very end, leave the formula
1196                 return cur.pos() != cur.lastpos();
1197         }
1198
1199         // These shouldn't work in text mode:
1200         if (currentMode() != MathInset::TEXT_MODE) {
1201                 if (c == '_') {
1202                         script(cur, false);
1203                         return true;
1204                 }
1205                 if (c == '^') {
1206                         script(cur, true);
1207                         return true;
1208                 }
1209                 if (c == '~') {
1210                         cur.niceInsert(createMathInset("sim"));
1211                         return true;
1212                 }
1213         }
1214
1215         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%'
1216       || c == '_' || c == '^') {
1217                 cur.niceInsert(createMathInset(string(1, c)));
1218                 return true;
1219         }
1220
1221
1222         // try auto-correction
1223         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1224         //      return true;
1225
1226         // no special circumstances, so insert the character without any fuss
1227         cur.insert(c);
1228         cur.autocorrect() = true;
1229         return true;
1230 }
1231
1232
1233 bool MathNestInset::script(LCursor & cur, bool up)
1234 {
1235         // Hack to get \^ and \_ working
1236         lyxerr << "handling script: up: " << up << endl;
1237         if (cur.inMacroMode() && cur.macroName() == "\\") {
1238                 if (up)
1239                         cur.niceInsert(createMathInset("mathcircumflex"));
1240                 else
1241                         interpret(cur, '_');
1242                 return true;
1243         }
1244
1245         cur.macroModeClose();
1246         string safe = grabAndEraseSelection(cur);
1247         if (asScriptInset() && cur.idx() == 0) {
1248                 // we are in a nucleus of a script inset, move to _our_ script
1249                 MathScriptInset * inset = asScriptInset();
1250                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1251                 inset->ensure(up);
1252                 cur.idx() = inset->idxOfScript(up);
1253                 cur.pos() = 0;
1254         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1255                 --cur.pos();
1256                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1257                 cur.push(*inset);
1258                 cur.idx() = inset->idxOfScript(up);
1259                 cur.pos() = cur.lastpos();
1260         } else {
1261                 // convert the thing to our left to a scriptinset or create a new
1262                 // one if in the very first position of the array
1263                 if (cur.pos() == 0) {
1264                         //lyxerr << "new scriptinset" << endl;
1265                         cur.insert(new MathScriptInset(up));
1266                 } else {
1267                         //lyxerr << "converting prev atom " << endl;
1268                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1269                 }
1270                 --cur.pos();
1271                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1272                 cur.push(*inset);
1273                 cur.idx() = 1;
1274                 cur.pos() = 0;
1275         }
1276         //lyxerr << "pasting 1: safe:\n" << safe << endl;
1277         cur.paste(safe);
1278         cur.resetAnchor();
1279         //lyxerr << "pasting 2: safe:\n" << safe << endl;
1280         return true;
1281 }