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