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