]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.C
move everything into namespace lyx
[lyx.git] / src / mathed / InsetMathGrid.C
1 /**
2  * \file InsetMathGrid.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 "InsetMathGrid.h"
14 #include "MathData.h"
15 #include "MathMLStream.h"
16 #include "MathStream.h"
17
18 #include "BufferView.h"
19 #include "CutAndPaste.h"
20 #include "FuncStatus.h"
21 #include "LColor.h"
22 #include "cursor.h"
23 #include "debug.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "undo.h"
27
28 #include "frontends/Painter.h"
29
30 #include "insets/mailinset.h"
31
32 #include "support/lstrings.h"
33
34 #include <sstream>
35
36
37 namespace lyx {
38
39 using support::bformat;
40
41 using std::endl;
42 using std::max;
43 using std::min;
44 using std::swap;
45
46 using std::string;
47 using std::auto_ptr;
48 using std::istream;
49 using std::istringstream;
50 using std::vector;
51
52
53 class GridInsetMailer : public MailInset {
54 public:
55         GridInsetMailer(InsetMathGrid & inset) : inset_(inset) {}
56         ///
57         virtual string const & name() const
58         {
59                 static string const theName = "tabular";
60                 return theName;
61         }
62         ///
63         virtual string const inset2string(Buffer const &) const
64         {
65                 odocstringstream data;
66                 //data << name() << " active_cell " << inset.getActCell() << '\n';
67                 data << from_utf8(name()) << " active_cell " << 0 << '\n';
68                 WriteStream ws(data);
69                 inset_.write(ws);
70                 return to_utf8(data.str());
71         }
72
73 protected:
74         InsetBase & inset() const { return inset_; }
75         InsetMathGrid & inset_;
76 };
77
78
79 void mathed_parse_normal(InsetMathGrid &, string const & argument);
80
81 namespace {
82
83 string verboseHLine(int n)
84 {
85         string res;
86         for (int i = 0; i < n; ++i)
87                 res += "\\hline";
88         if (n)
89                 res += ' ';
90         return res;
91 }
92
93
94 int extractInt(istream & is)
95 {
96         int num = 1;
97         is >> num;
98         return (num == 0) ? 1 : num;
99 }
100
101 }
102
103
104 //////////////////////////////////////////////////////////////
105
106
107 InsetMathGrid::CellInfo::CellInfo()
108         : dummy_(false)
109 {}
110
111
112
113
114 //////////////////////////////////////////////////////////////
115
116
117 InsetMathGrid::RowInfo::RowInfo()
118         : lines_(0), skip_(0)
119 {}
120
121
122
123 int InsetMathGrid::RowInfo::skipPixels() const
124 {
125         return crskip_.inBP();
126 }
127
128
129
130 //////////////////////////////////////////////////////////////
131
132
133 InsetMathGrid::ColInfo::ColInfo()
134         : align_('c'), lines_(0)
135 {}
136
137
138 //////////////////////////////////////////////////////////////
139
140
141 InsetMathGrid::InsetMathGrid(char v, string const & h)
142         : InsetMathNest(guessColumns(h)),
143           rowinfo_(2),
144           colinfo_(guessColumns(h) + 1),
145           cellinfo_(1 * guessColumns(h))
146 {
147         setDefaults();
148         valign(v);
149         halign(h);
150         //lyxerr << "created grid with " << ncols() << " columns" << endl;
151 }
152
153
154 InsetMathGrid::InsetMathGrid()
155         : InsetMathNest(1),
156           rowinfo_(1 + 1),
157                 colinfo_(1 + 1),
158                 cellinfo_(1),
159                 v_align_('c')
160 {
161         setDefaults();
162 }
163
164
165 InsetMathGrid::InsetMathGrid(col_type m, row_type n)
166         : InsetMathNest(m * n),
167           rowinfo_(n + 1),
168                 colinfo_(m + 1),
169                 cellinfo_(m * n),
170                 v_align_('c')
171 {
172         setDefaults();
173 }
174
175
176 InsetMathGrid::InsetMathGrid(col_type m, row_type n, char v, string const & h)
177         : InsetMathNest(m * n),
178           rowinfo_(n + 1),
179           colinfo_(m + 1),
180                 cellinfo_(m * n),
181                 v_align_(v)
182 {
183         setDefaults();
184         valign(v);
185         halign(h);
186 }
187
188
189 InsetMathGrid::~InsetMathGrid()
190 {
191         GridInsetMailer mailer(*this);
192         mailer.hideDialog();
193 }
194
195
196 auto_ptr<InsetBase> InsetMathGrid::doClone() const
197 {
198         return auto_ptr<InsetBase>(new InsetMathGrid(*this));
199 }
200
201
202 InsetMath::idx_type InsetMathGrid::index(row_type row, col_type col) const
203 {
204         return col + ncols() * row;
205 }
206
207
208 void InsetMathGrid::setDefaults()
209 {
210         if (ncols() <= 0)
211                 lyxerr << "positive number of columns expected" << endl;
212         //if (nrows() <= 0)
213         //      lyxerr << "positive number of rows expected" << endl;
214         for (col_type col = 0; col < ncols(); ++col) {
215                 colinfo_[col].align_ = defaultColAlign(col);
216                 colinfo_[col].skip_  = defaultColSpace(col);
217         }
218 }
219
220
221 void InsetMathGrid::halign(string const & hh)
222 {
223         col_type col = 0;
224         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it) {
225                 char c = *it;
226                 if (c == '|') {
227                         colinfo_[col].lines_++;
228                 } else if (col >= ncols()) {
229                         // Only '|' is allowed in the last dummy column
230                         break;
231                 } else if (c == 'c' || c == 'l' || c == 'r') {
232                         colinfo_[col].align_ = c;
233                         ++col;
234                         colinfo_[col].lines_ = 0;
235                 } else {
236                         lyxerr << "unknown column separator: '" << c << "'" << endl;
237                 }
238         }
239
240 /*
241         col_type n = hh.size();
242         if (n > ncols())
243                 n = ncols();
244         for (col_type col = 0; col < n; ++col)
245                 colinfo_[col].align_ = hh[col];
246 */
247 }
248
249
250 InsetMathGrid::col_type InsetMathGrid::guessColumns(string const & hh) const
251 {
252         col_type col = 0;
253         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it)
254                 if (*it == 'c' || *it == 'l' || *it == 'r')
255                         ++col;
256         // let's have at least one column, even if we did not recognize its
257         // alignment
258         if (col == 0)
259                 col = 1;
260         return col;
261 }
262
263
264 void InsetMathGrid::halign(char h, col_type col)
265 {
266         colinfo_[col].align_ = h;
267 }
268
269
270 char InsetMathGrid::halign(col_type col) const
271 {
272         return colinfo_[col].align_;
273 }
274
275
276 string InsetMathGrid::halign() const
277 {
278         string res;
279         for (col_type col = 0; col < ncols(); ++col) {
280                 res += string(colinfo_[col].lines_, '|');
281                 res += colinfo_[col].align_;
282         }
283         return res + string(colinfo_[ncols()].lines_, '|');
284 }
285
286
287 void InsetMathGrid::valign(char c)
288 {
289         v_align_ = c;
290 }
291
292
293 char InsetMathGrid::valign() const
294 {
295         return v_align_;
296 }
297
298
299 InsetMathGrid::col_type InsetMathGrid::ncols() const
300 {
301         return colinfo_.size() - 1;
302 }
303
304
305 InsetMathGrid::row_type InsetMathGrid::nrows() const
306 {
307         return rowinfo_.size() - 1;
308 }
309
310
311 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
312 {
313         return idx % ncols();
314 }
315
316
317 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
318 {
319         return idx / ncols();
320 }
321
322
323 void InsetMathGrid::vcrskip(LyXLength const & crskip, row_type row)
324 {
325         rowinfo_[row].crskip_ = crskip;
326 }
327
328
329 LyXLength InsetMathGrid::vcrskip(row_type row) const
330 {
331         return rowinfo_[row].crskip_;
332 }
333
334
335 void InsetMathGrid::metrics(MetricsInfo & mi) const
336 {
337         // let the cells adjust themselves
338         InsetMathNest::metrics(mi);
339
340         // compute absolute sizes of vertical structure
341         for (row_type row = 0; row < nrows(); ++row) {
342                 int asc  = 0;
343                 int desc = 0;
344                 for (col_type col = 0; col < ncols(); ++col) {
345                         MathArray const & c = cell(index(row, col));
346                         asc  = max(asc,  c.ascent());
347                         desc = max(desc, c.descent());
348                 }
349                 rowinfo_[row].ascent_  = asc;
350                 rowinfo_[row].descent_ = desc;
351         }
352         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
353         rowinfo_[nrows()].ascent_  = 0;
354         rowinfo_[nrows()].descent_ = 0;
355
356         // compute vertical offsets
357         rowinfo_[0].offset_ = 0;
358         for (row_type row = 1; row <= nrows(); ++row) {
359                 rowinfo_[row].offset_  =
360                         rowinfo_[row - 1].offset_  +
361                         rowinfo_[row - 1].descent_ +
362                         rowinfo_[row - 1].skipPixels() +
363                         rowsep() +
364                         rowinfo_[row].lines_ * hlinesep() +
365                         rowinfo_[row].ascent_;
366         }
367
368         // adjust vertical offset
369         int h = 0;
370         switch (v_align_) {
371                 case 't':
372                         h = 0;
373                         break;
374                 case 'b':
375                         h = rowinfo_[nrows() - 1].offset_;
376                         break;
377                 default:
378                         h = rowinfo_[nrows() - 1].offset_ / 2;
379         }
380         for (row_type row = 0; row <= nrows(); ++row)
381                 rowinfo_[row].offset_ -= h;
382
383
384         // compute absolute sizes of horizontal structure
385         for (col_type col = 0; col < ncols(); ++col) {
386                 int wid = 0;
387                 for (row_type row = 0; row < nrows(); ++row)
388                         wid = max(wid, cell(index(row, col)).width());
389                 colinfo_[col].width_ = wid;
390         }
391         colinfo_[ncols()].width_  = 0;
392
393         // compute horizontal offsets
394         colinfo_[0].offset_ = border();
395         for (col_type col = 1; col <= ncols(); ++col) {
396                 colinfo_[col].offset_ =
397                         colinfo_[col - 1].offset_ +
398                         colinfo_[col - 1].width_ +
399                         colinfo_[col - 1].skip_ +
400                         colsep() +
401                         colinfo_[col].lines_ * vlinesep();
402         }
403
404
405         dim_.wid   =   colinfo_[ncols() - 1].offset_
406                        + colinfo_[ncols() - 1].width_
407                  + vlinesep() * colinfo_[ncols()].lines_
408                        + border();
409
410         dim_.asc  = - rowinfo_[0].offset_
411                        + rowinfo_[0].ascent_
412                  + hlinesep() * rowinfo_[0].lines_
413                        + border();
414
415         dim_.des =   rowinfo_[nrows() - 1].offset_
416                        + rowinfo_[nrows() - 1].descent_
417                  + hlinesep() * rowinfo_[nrows()].lines_
418                        + border();
419
420
421 /*
422         // Increase ws_[i] for 'R' columns (except the first one)
423         for (int i = 1; i < nc_; ++i)
424                 if (align_[i] == 'R')
425                         ws_[i] += 10 * df_width;
426         // Increase ws_[i] for 'C' column
427         if (align_[0] == 'C')
428                 if (ws_[0] < 7 * workwidth / 8)
429                         ws_[0] = 7 * workwidth / 8;
430
431         // Adjust local tabs
432         width = colsep();
433         for (cxrow = row_.begin(); cxrow; ++cxrow) {
434                 int rg = COLSEP;
435                 int lf = 0;
436                 for (int i = 0; i < nc_; ++i) {
437                         bool isvoid = false;
438                         if (cxrow->getTab(i) <= 0) {
439                                 cxrow->setTab(i, df_width);
440                                 isvoid = true;
441                         }
442                         switch (align_[i]) {
443                         case 'l':
444                                 lf = 0;
445                                 break;
446                         case 'c':
447                                 lf = (ws_[i] - cxrow->getTab(i))/2;
448                                 break;
449                         case 'r':
450                         case 'R':
451                                 lf = ws_[i] - cxrow->getTab(i);
452                                 break;
453                         case 'C':
454                                 if (cxrow == row_.begin())
455                                         lf = 0;
456                                 else if (cxrow.is_last())
457                                         lf = ws_[i] - cxrow->getTab(i);
458                                 else
459                                         lf = (ws_[i] - cxrow->getTab(i))/2;
460                                 break;
461                         }
462                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
463                         cxrow->setTab(i, lf + rg);
464                         rg = ws_[i] - ww + colsep();
465                         if (cxrow == row_.begin())
466                                 width += ws_[i] + colsep();
467                 }
468                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
469         }
470 */
471         metricsMarkers2(dim_);
472 }
473
474
475 void InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
476 {
477         metrics(mi);
478         dim = dim_;
479 }
480
481
482 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
483 {
484         drawWithMargin(pi, x, y, 0, 0);
485 }
486
487 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
488         int lmargin, int rmargin) const
489 {
490         for (idx_type idx = 0; idx < nargs(); ++idx)
491                 cell(idx).draw(pi, x + lmargin + cellXOffset(idx),
492                         y + cellYOffset(idx));
493
494         for (row_type row = 0; row <= nrows(); ++row)
495                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
496                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
497                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
498                         pi.pain.line(x + lmargin + 1, yy,
499                                      x + dim_.width() - rmargin - 1, yy,
500                                      LColor::foreground);
501                 }
502
503         for (col_type col = 0; col <= ncols(); ++col)
504                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
505                         int xx = x + lmargin + colinfo_[col].offset_
506                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
507                         pi.pain.line(xx, y - dim_.ascent() + 1,
508                                      xx, y + dim_.descent() - 1,
509                                      LColor::foreground);
510                 }
511         drawMarkers2(pi, x, y);
512 }
513
514
515 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
516 {
517         // let the cells adjust themselves
518         //InsetMathNest::metrics(mi);
519         for (idx_type i = 0; i < nargs(); ++i)
520                 cell(i).metricsT(mi, dim);
521
522         // compute absolute sizes of vertical structure
523         for (row_type row = 0; row < nrows(); ++row) {
524                 int asc  = 0;
525                 int desc = 0;
526                 for (col_type col = 0; col < ncols(); ++col) {
527                         MathArray const & c = cell(index(row, col));
528                         asc  = max(asc,  c.ascent());
529                         desc = max(desc, c.descent());
530                 }
531                 rowinfo_[row].ascent_  = asc;
532                 rowinfo_[row].descent_ = desc;
533         }
534         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
535         rowinfo_[nrows()].ascent_  = 0;
536         rowinfo_[nrows()].descent_ = 0;
537
538         // compute vertical offsets
539         rowinfo_[0].offset_ = 0;
540         for (row_type row = 1; row <= nrows(); ++row) {
541                 rowinfo_[row].offset_  =
542                         rowinfo_[row - 1].offset_  +
543                         rowinfo_[row - 1].descent_ +
544                         //rowinfo_[row - 1].skipPixels() +
545                         1 + //rowsep() +
546                         //rowinfo_[row].lines_ * hlinesep() +
547                         rowinfo_[row].ascent_;
548         }
549
550         // adjust vertical offset
551         int h = 0;
552         switch (v_align_) {
553                 case 't':
554                         h = 0;
555                         break;
556                 case 'b':
557                         h = rowinfo_[nrows() - 1].offset_;
558                         break;
559                 default:
560                         h = rowinfo_[nrows() - 1].offset_ / 2;
561         }
562         for (row_type row = 0; row <= nrows(); ++row)
563                 rowinfo_[row].offset_ -= h;
564
565
566         // compute absolute sizes of horizontal structure
567         for (col_type col = 0; col < ncols(); ++col) {
568                 int wid = 0;
569                 for (row_type row = 0; row < nrows(); ++row)
570                         wid = max(wid, cell(index(row, col)).width());
571                 colinfo_[col].width_ = wid;
572         }
573         colinfo_[ncols()].width_  = 0;
574
575         // compute horizontal offsets
576         colinfo_[0].offset_ = border();
577         for (col_type col = 1; col <= ncols(); ++col) {
578                 colinfo_[col].offset_ =
579                         colinfo_[col - 1].offset_ +
580                         colinfo_[col - 1].width_ +
581                         colinfo_[col - 1].skip_ +
582                         1 ; //colsep() +
583                         //colinfo_[col].lines_ * vlinesep();
584         }
585
586
587         dim.wid  =  colinfo_[ncols() - 1].offset_
588                        + colinfo_[ncols() - 1].width_
589                  //+ vlinesep() * colinfo_[ncols()].lines_
590                        + 2;
591
592         dim.asc  = -rowinfo_[0].offset_
593                        + rowinfo_[0].ascent_
594                  //+ hlinesep() * rowinfo_[0].lines_
595                        + 1;
596
597         dim.des  =  rowinfo_[nrows() - 1].offset_
598                        + rowinfo_[nrows() - 1].descent_
599                  //+ hlinesep() * rowinfo_[nrows()].lines_
600                        + 1;
601 }
602
603
604 void InsetMathGrid::drawT(TextPainter & pain, int x, int y) const
605 {
606         for (idx_type idx = 0; idx < nargs(); ++idx)
607                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
608 }
609
610
611 string InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) const
612 {
613         string eol;
614
615         if (!rowinfo_[row].crskip_.zero())
616                 eol += '[' + rowinfo_[row].crskip_.asLatexString() + ']';
617
618         // make sure an upcoming '[' does not break anything
619         if (row + 1 < nrows()) {
620                 MathArray const & c = cell(index(row + 1, 0));
621                 if (c.size() && c.front()->getChar() == '[')
622                         //eol += "[0pt]";
623                         eol += "{}";
624         }
625
626         // only add \\ if necessary
627         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !emptyline))
628                 return string();
629
630         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
631 }
632
633
634 string InsetMathGrid::eocString(col_type col, col_type lastcol) const
635 {
636         if (col + 1 == lastcol)
637                 return string();
638         return " & ";
639 }
640
641
642 void InsetMathGrid::addRow(row_type row)
643 {
644         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
645         cells_.insert
646                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathArray());
647         cellinfo_.insert
648                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
649 }
650
651
652 void InsetMathGrid::appendRow()
653 {
654         rowinfo_.push_back(RowInfo());
655         //cells_.insert(cells_.end(), ncols(), MathArray());
656         for (col_type col = 0; col < ncols(); ++col) {
657                 cells_.push_back(cells_type::value_type());
658                 cellinfo_.push_back(CellInfo());
659         }
660 }
661
662
663 void InsetMathGrid::delRow(row_type row)
664 {
665         if (nrows() == 1)
666                 return;
667
668         cells_type::iterator it = cells_.begin() + row * ncols();
669         cells_.erase(it, it + ncols());
670
671         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
672         cellinfo_.erase(jt, jt + ncols());
673
674         rowinfo_.erase(rowinfo_.begin() + row);
675 }
676
677
678 void InsetMathGrid::copyRow(row_type row)
679 {
680         addRow(row);
681         for (col_type col = 0; col < ncols(); ++col)
682                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
683 }
684
685
686 void InsetMathGrid::swapRow(row_type row)
687 {
688         if (nrows() == 1)
689                 return;
690         if (row + 1 == nrows())
691                 --row;
692         for (col_type col = 0; col < ncols(); ++col)
693                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
694 }
695
696
697 void InsetMathGrid::addCol(col_type newcol)
698 {
699         const col_type nc = ncols();
700         const row_type nr = nrows();
701         cells_type new_cells((nc + 1) * nr);
702         vector<CellInfo> new_cellinfo((nc + 1) * nr);
703
704         for (row_type row = 0; row < nr; ++row)
705                 for (col_type col = 0; col < nc; ++col) {
706                         new_cells[row * (nc + 1) + col + (col > newcol)]
707                                 = cells_[row * nc + col];
708                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
709                                 = cellinfo_[row * nc + col];
710                 }
711         swap(cells_, new_cells);
712         swap(cellinfo_, new_cellinfo);
713
714         ColInfo inf;
715         inf.skip_  = defaultColSpace(newcol);
716         inf.align_ = defaultColAlign(newcol);
717         colinfo_.insert(colinfo_.begin() + newcol, inf);
718 }
719
720
721 void InsetMathGrid::delCol(col_type col)
722 {
723         if (ncols() == 1)
724                 return;
725
726         cells_type tmpcells;
727         vector<CellInfo> tmpcellinfo;
728         for (col_type i = 0; i < nargs(); ++i)
729                 if (i % ncols() != col) {
730                         tmpcells.push_back(cells_[i]);
731                         tmpcellinfo.push_back(cellinfo_[i]);
732                 }
733         swap(cells_, tmpcells);
734         swap(cellinfo_, tmpcellinfo);
735
736         colinfo_.erase(colinfo_.begin() + col);
737 }
738
739
740 void InsetMathGrid::copyCol(col_type col)
741 {
742         addCol(col);
743         for (row_type row = 0; row < nrows(); ++row)
744                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
745 }
746
747
748 void InsetMathGrid::swapCol(col_type col)
749 {
750         if (ncols() == 1)
751                 return;
752         if (col + 1 == ncols())
753                 --col;
754         for (row_type row = 0; row < nrows(); ++row)
755                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
756 }
757
758
759 int InsetMathGrid::cellXOffset(idx_type idx) const
760 {
761         col_type c = col(idx);
762         int x = colinfo_[c].offset_;
763         char align = colinfo_[c].align_;
764         if (align == 'r' || align == 'R')
765                 x += colinfo_[c].width_ - cell(idx).width();
766         if (align == 'c' || align == 'C')
767                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
768         return x;
769 }
770
771
772 int InsetMathGrid::cellYOffset(idx_type idx) const
773 {
774         return rowinfo_[row(idx)].offset_;
775 }
776
777
778 bool InsetMathGrid::idxUpDown(LCursor & cur, bool up) const
779 {
780         if (up) {
781                 if (cur.row() == 0)
782                         return false;
783                 cur.idx() -= ncols();
784         } else {
785                 if (cur.row() + 1 >= nrows())
786                         return false;
787                 cur.idx() += ncols();
788         }
789         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo(cur.bv()));
790         return true;
791 }
792
793
794 bool InsetMathGrid::idxLeft(LCursor & cur) const
795 {
796         // leave matrix if on the left hand edge
797         if (cur.col() == 0)
798                 return false;
799         --cur.idx();
800         cur.pos() = cur.lastpos();
801         return true;
802 }
803
804
805 bool InsetMathGrid::idxRight(LCursor & cur) const
806 {
807         // leave matrix if on the right hand edge
808         if (cur.col() + 1 == ncols())
809                 return false;
810         ++cur.idx();
811         cur.pos() = 0;
812         return true;
813 }
814
815
816 bool InsetMathGrid::idxFirst(LCursor & cur) const
817 {
818         switch (v_align_) {
819                 case 't':
820                         cur.idx() = 0;
821                         break;
822                 case 'b':
823                         cur.idx() = (nrows() - 1) * ncols();
824                         break;
825                 default:
826                         cur.idx() = ((nrows() - 1) / 2) * ncols();
827         }
828         cur.pos() = 0;
829         return true;
830 }
831
832
833 bool InsetMathGrid::idxLast(LCursor & cur) const
834 {
835         switch (v_align_) {
836                 case 't':
837                         cur.idx() = ncols() - 1;
838                         break;
839                 case 'b':
840                         cur.idx() = nargs() - 1;
841                         break;
842                 default:
843                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
844         }
845         cur.pos() = cur.lastpos();
846         return true;
847 }
848
849
850 bool InsetMathGrid::idxDelete(idx_type & idx)
851 {
852         // nothing to do if we have just one row
853         if (nrows() == 1)
854                 return false;
855
856         // nothing to do if we are in the middle of the last row of the inset
857         if (idx + ncols() > nargs())
858                 return false;
859
860         // try to delete entire sequence of ncols() empty cells if possible
861         for (idx_type i = idx; i < idx + ncols(); ++i)
862                 if (cell(i).size())
863                         return false;
864
865         // move cells if necessary
866         for (idx_type i = index(row(idx), 0); i < idx; ++i)
867                 swap(cell(i), cell(i + ncols()));
868
869         delRow(row(idx));
870
871         if (idx >= nargs())
872                 idx = nargs() - 1;
873
874         // undo effect of Ctrl-Tab (i.e. pull next cell)
875         //if (idx + 1 != nargs())
876         //      cell(idx).swap(cell(idx + 1));
877
878         // we handled the event..
879         return true;
880 }
881
882
883 // reimplement old behaviour when pressing Delete in the last position
884 // of a cell
885 void InsetMathGrid::idxGlue(idx_type idx)
886 {
887         col_type c = col(idx);
888         if (c + 1 == ncols()) {
889                 if (row(idx) + 1 != nrows()) {
890                         for (col_type cc = 0; cc < ncols(); ++cc)
891                                 cell(idx).append(cell(idx + cc + 1));
892                         delRow(row(idx) + 1);
893                 }
894         } else {
895                 cell(idx).append(cell(idx + 1));
896                 for (col_type cc = c + 2; cc < ncols(); ++cc)
897                         cell(idx - c + cc - 1) = cell(idx - c + cc);
898                 cell(idx - c + ncols() - 1).clear();
899         }
900 }
901
902
903 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
904 {
905         return rowinfo_[row];
906 }
907
908
909 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
910 {
911         return rowinfo_[row];
912 }
913
914
915 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
916 {
917         row_type const ri = row(idx);
918         row_type const r1 = min(row(from), row(to));
919         row_type const r2 = max(row(from), row(to));
920         col_type const ci = col(idx);
921         col_type const c1 = min(col(from), col(to));
922         col_type const c2 = max(col(from), col(to));
923         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
924 }
925
926
927
928 void InsetMathGrid::normalize(NormalStream & os) const
929 {
930         os << "[grid ";
931         for (row_type row = 0; row < nrows(); ++row) {
932                 os << "[row ";
933                 for (col_type col = 0; col < ncols(); ++col)
934                         os << "[cell " << cell(index(row, col)) << ']';
935                 os << ']';
936         }
937         os << ']';
938 }
939
940
941 void InsetMathGrid::mathmlize(MathMLStream & os) const
942 {
943         os << MTag("mtable");
944         for (row_type row = 0; row < nrows(); ++row) {
945                 os << MTag("mtr");
946                 for (col_type col = 0; col < ncols(); ++col)
947                         os << cell(index(row, col));
948                 os << ETag("mtr");
949         }
950         os << ETag("mtable");
951 }
952
953
954 void InsetMathGrid::write(WriteStream & os) const
955 {
956         string eol;
957         for (row_type row = 0; row < nrows(); ++row) {
958                 os << verboseHLine(rowinfo_[row].lines_);
959                 // don't write & and empty cells at end of line
960                 col_type lastcol = 0;
961                 bool emptyline = true;
962                 for (col_type col = 0; col < ncols(); ++col)
963                         if (!cell(index(row, col)).empty()) {
964                                 lastcol = col + 1;
965                                 emptyline = false;
966                         }
967                 for (col_type col = 0; col < lastcol; ++col)
968                         os << cell(index(row, col)) << eocString(col, lastcol);
969                 eol = eolString(row, emptyline, os.fragile());
970                 os << eol;
971                 // append newline only if line wasn't completely empty
972                 // and this was not the last line in the grid
973                 if (!emptyline && row + 1 < nrows())
974                         os << "\n";
975         }
976         string const s = verboseHLine(rowinfo_[nrows()].lines_);
977         if (!s.empty()) {
978                 if (eol.empty()) {
979                         if (os.fragile())
980                                 os << "\\protect";
981                         os << "\\\\";
982                 }
983                 os << s;
984         }
985 }
986
987
988 int InsetMathGrid::colsep() const
989 {
990         return 6;
991 }
992
993
994 int InsetMathGrid::rowsep() const
995 {
996         return 6;
997 }
998
999
1000 int InsetMathGrid::hlinesep() const
1001 {
1002         return 3;
1003 }
1004
1005
1006 int InsetMathGrid::vlinesep() const
1007 {
1008         return 3;
1009 }
1010
1011
1012 int InsetMathGrid::border() const
1013 {
1014         return 1;
1015 }
1016
1017
1018 void InsetMathGrid::splitCell(LCursor & cur)
1019 {
1020         if (cur.idx() == cur.lastidx())
1021                 return;
1022         MathArray ar = cur.cell();
1023         ar.erase(0, cur.pos());
1024         cur.cell().erase(cur.pos(), cur.lastpos());
1025         ++cur.idx();
1026         cur.pos() = 0;
1027         cur.cell().insert(0, ar);
1028 }
1029
1030
1031 void InsetMathGrid::doDispatch(LCursor & cur, FuncRequest & cmd)
1032 {
1033         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1034         switch (cmd.action) {
1035
1036         case LFUN_MOUSE_RELEASE:
1037                 //if (cmd.button() == mouse_button::button3) {
1038                 //      GridInsetMailer(*this).showDialog();
1039                 //      return DispatchResult(true, true);
1040                 //}
1041                 InsetMathNest::doDispatch(cur, cmd);
1042                 break;
1043
1044         case LFUN_INSET_DIALOG_UPDATE:
1045                 GridInsetMailer(*this).updateDialog(&cur.bv());
1046                 break;
1047
1048         // insert file functions
1049         case LFUN_LINE_DELETE:
1050                 // FIXME: We use recordUndoInset when a change reflects more
1051                 // than one cell, because recordUndo does not work for
1052                 // multiple cells. Unfortunately this puts the cursor in front
1053                 // of the inset after undo. This is (especilally for large
1054                 // grids) annoying.
1055                 recordUndoInset(cur);
1056                 //autocorrect_ = false;
1057                 //macroModeClose();
1058                 //if (selection_) {
1059                 //      selDel();
1060                 //      break;
1061                 //}
1062                 if (nrows() > 1)
1063                         delRow(cur.row());
1064                 if (cur.idx() > cur.lastidx())
1065                         cur.idx() = cur.lastidx();
1066                 if (cur.pos() > cur.lastpos())
1067                         cur.pos() = cur.lastpos();
1068                 break;
1069
1070         case LFUN_CELL_SPLIT:
1071                 recordUndo(cur);
1072                 splitCell(cur);
1073                 break;
1074
1075         case LFUN_CELL_BACKWARD:
1076                 // See below.
1077                 cur.selection() = false;
1078                 if (!idxPrev(cur)) {
1079                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1080                         cur.undispatched();
1081                 }
1082                 break;
1083
1084         case LFUN_CELL_FORWARD:
1085                 // Can't handle selection by additional 'shift' as this is
1086                 // hard bound to LFUN_CELL_BACKWARD
1087                 cur.selection() = false;
1088                 if (!idxNext(cur)) {
1089                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1090                         cur.undispatched();
1091                 }
1092                 break;
1093
1094         case LFUN_BREAK_LINE: {
1095                 recordUndoInset(cur);
1096                 row_type const r = cur.row();
1097                 addRow(r);
1098
1099                 // split line
1100                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1101                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1102
1103                 // split cell
1104                 splitCell(cur);
1105                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1106                 if (cur.idx() > 0)
1107                         --cur.idx();
1108                 cur.pos() = cur.lastpos();
1109
1110                 //mathcursor->normalize();
1111                 //cmd = FuncRequest(LFUN_FINISHED_LEFT);
1112                 break;
1113         }
1114
1115         case LFUN_TABULAR_FEATURE: {
1116                 recordUndoInset(cur);
1117                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1118                 istringstream is(to_utf8(cmd.argument()));
1119                 string s;
1120                 is >> s;
1121                 if (s == "valign-top")
1122                         valign('t');
1123                 else if (s == "valign-middle")
1124                         valign('c');
1125                 else if (s == "valign-bottom")
1126                         valign('b');
1127                 else if (s == "align-left")
1128                         halign('l', cur.col());
1129                 else if (s == "align-right")
1130                         halign('r', cur.col());
1131                 else if (s == "align-center")
1132                         halign('c', cur.col());
1133                 else if (s == "append-row")
1134                         for (int i = 0, n = extractInt(is); i < n; ++i)
1135                                 addRow(cur.row());
1136                 else if (s == "delete-row") {
1137                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1138                                 delRow(cur.row());
1139                                 if (cur.idx() >= nargs())
1140                                         cur.idx() -= ncols();
1141                         }
1142                         cur.pos() = 0; // trick, see below
1143                 }
1144                 else if (s == "copy-row") {
1145                         // Here (as later) we save the cursor col/row
1146                         // in order to restore it after operation.
1147                         row_type const r = cur.row();
1148                         col_type const c = cur.col();
1149                         for (int i = 0, n = extractInt(is); i < n; ++i)
1150                                 copyRow(cur.row());
1151                         cur.idx() = index(r, c);
1152                 }
1153                 else if (s == "swap-row") {
1154                         swapRow(cur.row());
1155                         // Trick to suppress same-idx-means-different-cell
1156                         // assertion crash:
1157                         cur.pos() = 0;
1158                 }
1159                 else if (s == "add-hline-above")
1160                         rowinfo_[cur.row()].lines_++;
1161                 else if (s == "add-hline-below")
1162                         rowinfo_[cur.row()+1].lines_++;
1163                 else if (s == "delete-hline-above")
1164                         rowinfo_[cur.row()].lines_--;
1165                 else if (s == "delete-hline-below")
1166                         rowinfo_[cur.row()+1].lines_--;
1167                 else if (s == "append-column") {
1168                         row_type const r = cur.row();
1169                         col_type const c = cur.col();
1170                         for (int i = 0, n = extractInt(is); i < n; ++i)
1171                                 addCol(cur.col());
1172                         cur.idx() = index(r, c);
1173                 }
1174                 else if (s == "delete-column") {
1175                         row_type const r = cur.row();
1176                         col_type const c = cur.col();
1177                         for (int i = 0, n = extractInt(is); i < n; ++i)
1178                                 delCol(col(cur.idx()));
1179                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1180                         cur.pos() = 0; // trick, see above
1181                 }
1182                 else if (s == "copy-column") {
1183                         row_type const r = cur.row();
1184                         col_type const c = cur.col();
1185                         copyCol(cur.col());
1186                         cur.idx() = index(r, c);
1187                 }
1188                 else if (s == "swap-column") {
1189                         swapCol(cur.col());
1190                         cur.pos() = 0; // trick, see above
1191                 }
1192                 else if (s == "add-vline-left")
1193                         colinfo_[cur.col()].lines_++;
1194                 else if (s == "add-vline-right")
1195                         colinfo_[cur.col()+1].lines_++;
1196                 else if (s == "delete-vline-left")
1197                         colinfo_[cur.col()].lines_--;
1198                 else if (s == "delete-vline-right")
1199                         colinfo_[cur.col()+1].lines_--;
1200                 else {
1201                         cur.undispatched();
1202                         break;
1203                 }
1204                 lyxerr << "returning FINISHED_LEFT" << endl;
1205                 break;
1206         }
1207
1208         case LFUN_PASTE: {
1209                 cur.message(_("Paste"));
1210                 cap::replaceSelection(cur);
1211                 istringstream is(to_utf8(cmd.argument()));
1212                 int n = 0;
1213                 is >> n;
1214                 InsetMathGrid grid(1, 1);
1215                 // FIXME UNICODE
1216                 mathed_parse_normal(grid,
1217                         to_utf8(lyx::cap::getSelection(cur.buffer(), n)));
1218                 if (grid.nargs() == 1) {
1219                         // single cell/part of cell
1220                         recordUndo(cur);
1221                         cur.cell().insert(cur.pos(), grid.cell(0));
1222                         cur.pos() += grid.cell(0).size();
1223                 } else {
1224                         // multiple cells
1225                         recordUndoInset(cur);
1226                         col_type const numcols =
1227                                 min(grid.ncols(), ncols() - col(cur.idx()));
1228                         row_type const numrows =
1229                                 min(grid.nrows(), nrows() - cur.row());
1230                         for (row_type r = 0; r < numrows; ++r) {
1231                                 for (col_type c = 0; c < numcols; ++c) {
1232                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1233                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1234                                 }
1235                                 // append the left over horizontal cells to the last column
1236                                 idx_type i = index(r + cur.row(), ncols() - 1);
1237                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1238                                         cell(i).append(grid.cell(grid.index(r, c)));
1239                         }
1240                         // append the left over vertical cells to the last _cell_
1241                         idx_type i = nargs() - 1;
1242                         for (row_type r = numrows; r < grid.nrows(); ++r)
1243                                 for (col_type c = 0; c < grid.ncols(); ++c)
1244                                         cell(i).append(grid.cell(grid.index(r, c)));
1245                 }
1246                 cur.clearSelection(); // bug 393
1247                 cur.bv().switchKeyMap();
1248                 finishUndo();
1249                 break;
1250         }
1251
1252         case LFUN_LINE_BEGIN_SELECT:
1253         case LFUN_LINE_BEGIN:
1254         case LFUN_WORD_BACKWARD_SELECT:
1255         case LFUN_WORD_BACKWARD:
1256                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
1257                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
1258                 cur.macroModeClose();
1259                 if (cur.pos() != 0) {
1260                         cur.pos() = 0;
1261                 } else if (cur.idx() % cur.ncols() != 0) {
1262                         cur.idx() -= cur.idx() % cur.ncols();
1263                         cur.pos() = 0;
1264                 } else if (cur.idx() != 0) {
1265                         cur.idx() = 0;
1266                         cur.pos() = 0;
1267                 } else {
1268                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1269                         cur.undispatched();
1270                 }
1271                 break;
1272
1273         case LFUN_WORD_FORWARD_SELECT:
1274         case LFUN_WORD_FORWARD:
1275         case LFUN_LINE_END_SELECT:
1276         case LFUN_LINE_END:
1277                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
1278                                 cmd.action == LFUN_LINE_END_SELECT);
1279                 cur.macroModeClose();
1280                 cur.clearTargetX();
1281                 if (cur.pos() != cur.lastpos()) {
1282                         cur.pos() = cur.lastpos();
1283                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1284                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1285                         cur.pos() = cur.lastpos();
1286                 } else if (cur.idx() != cur.lastidx()) {
1287                         cur.idx() = cur.lastidx();
1288                         cur.pos() = cur.lastpos();
1289                 } else {
1290                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1291                         cur.undispatched();
1292                 }
1293                 break;
1294
1295         default:
1296                 InsetMathNest::doDispatch(cur, cmd);
1297         }
1298 }
1299
1300
1301 bool InsetMathGrid::getStatus(LCursor & cur, FuncRequest const & cmd,
1302                 FuncStatus & status) const
1303 {
1304         switch (cmd.action) {
1305         case LFUN_TABULAR_FEATURE: {
1306                 string const s = to_utf8(cmd.argument());
1307                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1308                         status.enabled(false);
1309                         status.message(from_utf8(N_("Only one row")));
1310                         return true;
1311                 }
1312                 if (ncols() <= 1 &&
1313                     (s == "delete-column" || s == "swap-column")) {
1314                         status.enabled(false);
1315                         status.message(from_utf8(N_("Only one column")));
1316                         return true;
1317                 }
1318                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1319                      s == "delete-hline-above") ||
1320                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1321                      s == "delete-hline-below")) {
1322                         status.enabled(false);
1323                         status.message(from_utf8(N_("No hline to delete")));
1324                         return true;
1325                 }
1326
1327                 if ((colinfo_[cur.col()].lines_ == 0 &&
1328                      s == "delete-vline-left") ||
1329                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1330                      s == "delete-vline-right")) {
1331                         status.enabled(false);
1332                         status.message(from_utf8(N_("No vline to delete")));
1333                         return true;
1334                 }
1335                 if (s == "valign-top" || s == "valign-middle" ||
1336                     s == "valign-bottom" || s == "align-left" ||
1337                     s == "align-right" || s == "align-center" ||
1338                     s == "append-row" || s == "delete-row" ||
1339                     s == "copy-row" || s == "swap-row" ||
1340                     s == "add-hline-above" || s == "add-hline-below" ||
1341                     s == "delete-hline-above" || s == "delete-hline-below" ||
1342                     s == "append-column" || s == "delete-column" ||
1343                     s == "copy-column" || s == "swap-column" ||
1344                     s == "add-vline-left" || s == "add-vline-right" ||
1345                     s == "delete-vline-left" || s == "delete-vline-right")
1346                         status.enabled(true);
1347                 else {
1348                         status.enabled(false);
1349                         status.message(bformat(
1350                                 from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1351                 }
1352
1353                 status.setOnOff(s == "align-left"    && halign(cur.col()) == 'l'
1354                            || s == "align-right"   && halign(cur.col()) == 'r'
1355                            || s == "align-center"  && halign(cur.col()) == 'c'
1356                            || s == "valign-top"    && valign() == 't'
1357                            || s == "valign-bottom" && valign() == 'b'
1358                            || s == "valign-middle" && valign() == 'm');
1359
1360 #if 0
1361                 // FIXME: What did this code do?
1362                 // Please check whether it is still needed!
1363                 // should be more precise
1364                 if (v_align_ == '\0') {
1365                         status.enable(true);
1366                         break;
1367                 }
1368                 if (cmd.argument().empty()) {
1369                         status.enable(false);
1370                         break;
1371                 }
1372                 if (!support::contains("tcb", cmd.argument()[0])) {
1373                         status.enable(false);
1374                         break;
1375                 }
1376                 status.setOnOff(cmd.argument()[0] == v_align_);
1377                 status.enabled(true);
1378 #endif
1379                 return true;
1380         }
1381
1382         case LFUN_CELL_SPLIT:
1383                 status.enabled(true);
1384                 return true;
1385
1386         case LFUN_CELL_BACKWARD:
1387         case LFUN_CELL_FORWARD:
1388                 status.enabled(true);
1389                 return true;
1390
1391         default:
1392                 return InsetMathNest::getStatus(cur, cmd, status);
1393         }
1394 }
1395
1396
1397 } // namespace lyx