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