]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
fix http://bugzilla.lyx.org/show_bug.cgi?id=4756
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "InsetTabular.h"
21
22 #include "buffer_funcs.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Counters.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Language.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "OutputParams.h"
40 #include "paragraph_funcs.h"
41 #include "Paragraph.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/assert.h"
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/docstream.h"
57 #include "support/FileName.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
155         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
156         { Tabular::SET_BOOKTABS, "set-booktabs" },
157         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
158         { Tabular::SET_TOP_SPACE, "set-top-space" },
159         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
160         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
161         { Tabular::SET_BORDER_LINES, "set-border-lines" },
162         { Tabular::LAST_ACTION, "" }
163 };
164
165
166 class FeatureEqual : public unary_function<TabularFeature, bool> {
167 public:
168         FeatureEqual(Tabular::Feature feature)
169                 : feature_(feature) {}
170         bool operator()(TabularFeature const & tf) const {
171                 return tf.action == feature_;
172         }
173 private:
174         Tabular::Feature feature_;
175 };
176
177
178 template <class T>
179 string const write_attribute(string const & name, T const & t)
180 {
181         string const s = tostr(t);
182         return s.empty() ? s : " " + name + "=\"" + s + "\"";
183 }
184
185 template <>
186 string const write_attribute(string const & name, string const & t)
187 {
188         return t.empty() ? t : " " + name + "=\"" + t + "\"";
189 }
190
191
192 template <>
193 string const write_attribute(string const & name, docstring const & t)
194 {
195         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
196 }
197
198
199 template <>
200 string const write_attribute(string const & name, bool const & b)
201 {
202         // we write only true attribute values so we remove a bit of the
203         // file format bloat for tabulars.
204         return b ? write_attribute(name, convert<string>(b)) : string();
205 }
206
207
208 template <>
209 string const write_attribute(string const & name, int const & i)
210 {
211         // we write only true attribute values so we remove a bit of the
212         // file format bloat for tabulars.
213         return i ? write_attribute(name, convert<string>(i)) : string();
214 }
215
216
217 template <>
218 string const write_attribute(string const & name, Tabular::idx_type const & i)
219 {
220         // we write only true attribute values so we remove a bit of the
221         // file format bloat for tabulars.
222         return i ? write_attribute(name, convert<string>(i)) : string();
223 }
224
225
226 template <>
227 string const write_attribute(string const & name, Length const & value)
228 {
229         // we write only the value if we really have one same reson as above.
230         return value.zero() ? string() : write_attribute(name, value.asString());
231 }
232
233
234 string const tostr(LyXAlignment const & num)
235 {
236         switch (num) {
237         case LYX_ALIGN_NONE:
238                 return "none";
239         case LYX_ALIGN_BLOCK:
240                 return "block";
241         case LYX_ALIGN_LEFT:
242                 return "left";
243         case LYX_ALIGN_CENTER:
244                 return "center";
245         case LYX_ALIGN_RIGHT:
246                 return "right";
247         case LYX_ALIGN_LAYOUT:
248                 return "layout";
249         case LYX_ALIGN_SPECIAL:
250                 return "special";
251         }
252         return string();
253 }
254
255
256 string const tostr(Tabular::VAlignment const & num)
257 {
258         switch (num) {
259         case Tabular::LYX_VALIGN_TOP:
260                 return "top";
261         case Tabular::LYX_VALIGN_MIDDLE:
262                 return "middle";
263         case Tabular::LYX_VALIGN_BOTTOM:
264                 return "bottom";
265         }
266         return string();
267 }
268
269
270 string const tostr(Tabular::BoxType const & num)
271 {
272         switch (num) {
273         case Tabular::BOX_NONE:
274                 return "none";
275         case Tabular::BOX_PARBOX:
276                 return "parbox";
277         case Tabular::BOX_MINIPAGE:
278                 return "minipage";
279         }
280         return string();
281 }
282
283
284 // I would have liked a fromstr template a lot better. (Lgb)
285 bool string2type(string const str, LyXAlignment & num)
286 {
287         if (str == "none")
288                 num = LYX_ALIGN_NONE;
289         else if (str == "block")
290                 num = LYX_ALIGN_BLOCK;
291         else if (str == "left")
292                 num = LYX_ALIGN_LEFT;
293         else if (str == "center")
294                 num = LYX_ALIGN_CENTER;
295         else if (str == "right")
296                 num = LYX_ALIGN_RIGHT;
297         else
298                 return false;
299         return true;
300 }
301
302
303 bool string2type(string const str, Tabular::VAlignment & num)
304 {
305         if (str == "top")
306                 num = Tabular::LYX_VALIGN_TOP;
307         else if (str == "middle" )
308                 num = Tabular::LYX_VALIGN_MIDDLE;
309         else if (str == "bottom")
310                 num = Tabular::LYX_VALIGN_BOTTOM;
311         else
312                 return false;
313         return true;
314 }
315
316
317 bool string2type(string const str, Tabular::BoxType & num)
318 {
319         if (str == "none")
320                 num = Tabular::BOX_NONE;
321         else if (str == "parbox")
322                 num = Tabular::BOX_PARBOX;
323         else if (str == "minipage")
324                 num = Tabular::BOX_MINIPAGE;
325         else
326                 return false;
327         return true;
328 }
329
330
331 bool string2type(string const str, bool & num)
332 {
333         if (str == "true")
334                 num = true;
335         else if (str == "false")
336                 num = false;
337         else
338                 return false;
339         return true;
340 }
341
342
343 bool getTokenValue(string const & str, char const * token, string & ret)
344 {
345         ret.erase();
346         size_t token_length = strlen(token);
347         size_t pos = str.find(token);
348
349         if (pos == string::npos || pos + token_length + 1 >= str.length()
350                 || str[pos + token_length] != '=')
351                 return false;
352         pos += token_length + 1;
353         char ch = str[pos];
354         if (ch != '"' && ch != '\'') { // only read till next space
355                 ret += ch;
356                 ch = ' ';
357         }
358         while (pos < str.length() - 1 && str[++pos] != ch)
359                 ret += str[pos];
360
361         return true;
362 }
363
364
365 bool getTokenValue(string const & str, char const * token, docstring & ret)
366 {
367         string tmp;
368         bool const success = getTokenValue(str, token, tmp);
369         ret = from_utf8(tmp);
370         return success;
371 }
372
373
374 bool getTokenValue(string const & str, char const * token, int & num)
375 {
376         string tmp;
377         num = 0;
378         if (!getTokenValue(str, token, tmp))
379                 return false;
380         num = convert<int>(tmp);
381         return true;
382 }
383
384
385 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
386 {
387         string tmp;
388         return getTokenValue(str, token, tmp) && string2type(tmp, num);
389 }
390
391
392 bool getTokenValue(string const & str, char const * token,
393                                    Tabular::VAlignment & num)
394 {
395         string tmp;
396         return getTokenValue(str, token, tmp) && string2type(tmp, num);
397 }
398
399
400 bool getTokenValue(string const & str, char const * token,
401                                    Tabular::BoxType & num)
402 {
403         string tmp;
404         return getTokenValue(str, token, tmp) && string2type(tmp, num);
405 }
406
407
408 bool getTokenValue(string const & str, char const * token, bool & flag)
409 {
410         // set the flag always to false as this should be the default for bools
411         // not in the file-format.
412         flag = false;
413         string tmp;
414         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
415 }
416
417
418 bool getTokenValue(string const & str, char const * token, Length & len)
419 {
420         // set the length to be zero() as default as this it should be if not
421         // in the file format.
422         len = Length();
423         string tmp;
424         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
425 }
426
427
428 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
429 {
430         len = Length();
431         flag = false;
432         string tmp;
433         if (!getTokenValue(str, token, tmp))
434                 return false;
435         if (tmp == "default") {
436                 flag = true;
437                 return  true;
438         }
439         return isValidLength(tmp, &len);
440 }
441
442
443 void l_getline(istream & is, string & str)
444 {
445         str.erase();
446         while (str.empty()) {
447                 getline(is, str);
448                 if (!str.empty() && str[str.length() - 1] == '\r')
449                         str.erase(str.length() - 1);
450         }
451 }
452
453 } // namespace
454
455
456 string const featureAsString(Tabular::Feature feature)
457 {
458         TabularFeature * end = tabularFeature +
459                 sizeof(tabularFeature) / sizeof(TabularFeature);
460         TabularFeature * it = find_if(tabularFeature, end,
461                                            FeatureEqual(feature));
462         return (it == end) ? string() : it->feature;
463 }
464
465
466
467 /////////////////////////////////////////////////////////////////////
468 //
469 // Tabular
470 //
471 /////////////////////////////////////////////////////////////////////
472
473
474 Tabular::CellData::CellData(Buffer const & buf, Tabular const & table)
475         : cellno(0),
476           width(0),
477           multicolumn(Tabular::CELL_NORMAL),
478           alignment(LYX_ALIGN_CENTER),
479           valignment(LYX_VALIGN_TOP),
480           top_line(false),
481           bottom_line(false),
482           left_line(false),
483           right_line(false),
484           usebox(BOX_NONE),
485           rotate(false),
486           inset(new InsetTableCell(buf, this, &table))
487 {
488         inset->setBuffer(const_cast<Buffer &>(buf));
489         inset->paragraphs().back().setLayout(buf.params().documentClass().emptyLayout());
490 }
491
492
493 Tabular::CellData::CellData(CellData const & cs)
494         : cellno(cs.cellno),
495           width(cs.width),
496           multicolumn(cs.multicolumn),
497           alignment(cs.alignment),
498           valignment(cs.valignment),
499           top_line(cs.top_line),
500           bottom_line(cs.bottom_line),
501           left_line(cs.left_line),
502           right_line(cs.right_line),
503           usebox(cs.usebox),
504           rotate(cs.rotate),
505           align_special(cs.align_special),
506           p_width(cs.p_width),
507           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
508 {
509         inset->setCellData(this);
510 }
511
512
513 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
514 {
515         swap(cs);
516         return *this;
517 }
518
519
520 void Tabular::CellData::swap(CellData & rhs)
521 {
522         std::swap(cellno, rhs.cellno);
523         std::swap(width, rhs.width);
524         std::swap(multicolumn, rhs.multicolumn);
525         std::swap(alignment, rhs.alignment);
526         std::swap(valignment, rhs.valignment);
527         std::swap(top_line, rhs.top_line);
528         std::swap(bottom_line, rhs.bottom_line);
529         std::swap(left_line, rhs.left_line);
530         std::swap(right_line, rhs.right_line);
531         std::swap(usebox, rhs.usebox);
532         std::swap(rotate, rhs.rotate);
533         std::swap(align_special, rhs.align_special);
534         p_width.swap(rhs.p_width);
535         inset.swap(rhs.inset);
536 }
537
538
539 Tabular::RowData::RowData()
540         : ascent(0),
541           descent(0),
542           top_space_default(false),
543           bottom_space_default(false),
544           interline_space_default(false),
545           endhead(false),
546           endfirsthead(false),
547           endfoot(false),
548           endlastfoot(false),
549           newpage(false)
550 {}
551
552
553 Tabular::ColumnData::ColumnData()
554         : alignment(LYX_ALIGN_CENTER),
555           valignment(LYX_VALIGN_TOP),
556           width(0)
557 {
558 }
559
560
561 Tabular::ltType::ltType()
562         : topDL(false),
563           bottomDL(false),
564           empty(false)
565 {}
566
567
568 Tabular::Tabular()
569 {
570         // unusable now!
571 }
572
573
574 Tabular::Tabular(Buffer const & buffer, row_type rows_arg, col_type columns_arg)
575 {
576         init(buffer, rows_arg, columns_arg);
577 }
578
579
580 // activates all lines and sets all widths to 0
581 void Tabular::init(Buffer const & buf, row_type rows_arg,
582                       col_type columns_arg)
583 {
584         buffer_ = &buf;
585         row_info = row_vector(rows_arg);
586         column_info = column_vector(columns_arg);
587         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf, *this)));
588         row_info.reserve(10);
589         column_info.reserve(10);
590         cell_info.reserve(100);
591         updateIndexes();
592         is_long_tabular = false;
593         rotate = false;
594         use_booktabs = false;
595         // set silly default lines
596         for (row_type i = 0; i < rowCount(); ++i)
597                 for (col_type j = 0; j < columnCount(); ++j) {
598                         cell_info[i][j].top_line = true;
599                         cell_info[i][j].left_line = true;
600                         cell_info[i][j].bottom_line = i == 0 || i == rowCount() - 1;
601                         cell_info[i][j].right_line = j == columnCount() - 1;
602                 }
603 }
604
605
606 void Tabular::appendRow(idx_type const cell)
607 {
608         BufferParams const & bp = buffer().params();
609         row_type const row = cellRow(cell);
610
611         row_vector::iterator rit = row_info.begin() + row;
612         row_info.insert(rit, RowData());
613         // now set the values of the row before
614         row_info[row] = row_info[row + 1];
615
616         row_type const nrows = rowCount();
617         col_type const ncols = columnCount();
618
619         cell_vvector old(nrows - 1);
620         for (row_type i = 0; i < nrows - 1; ++i)
621                 swap(cell_info[i], old[i]);
622
623         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer(), *this)));
624
625         for (row_type i = 0; i <= row; ++i)
626                 swap(cell_info[i], old[i]);
627         for (row_type i = row + 2; i < nrows; ++i)
628                 swap(cell_info[i], old[i - 1]);
629
630         updateIndexes();
631         for (col_type c = 0; c < ncols; ++c) {
632                 // inherit line settings
633                 idx_type const i = cellIndex(row + 1, c);
634                 idx_type const j = cellIndex(row, c);
635                 setLeftLine(i, isPartOfMultiColumn(row, c) ? false : leftLine(j));
636                 if (cell_info[row][c].multicolumn == CELL_NORMAL || c == ncols - 1
637                         || (c + 1 < ncols 
638                         && cell_info[row][c].multicolumn != CELL_NORMAL
639                         && cell_info[row][c + 1].multicolumn == CELL_NORMAL))
640                         setRightLine(i, rightLine(j));
641                 else
642                         setRightLine(i, false);
643                 // mark track changes
644                 if (bp.trackChanges)
645                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
646         }
647 }
648
649
650 void Tabular::deleteRow(row_type const row)
651 {
652         // Not allowed to delete last row
653         if (rowCount() == 1)
654                 return;
655
656         row_info.erase(row_info.begin() + row);
657         cell_info.erase(cell_info.begin() + row);
658         updateIndexes();
659 }
660
661
662 void Tabular::copyRow(row_type const row)
663 {
664         row_info.insert(row_info.begin() + row, row_info[row]);
665         cell_info.insert(cell_info.begin() + row, cell_info[row]);
666
667         if (buffer().params().trackChanges)
668                 for (col_type j = 0; j < columnCount(); ++j)
669                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
670
671         updateIndexes();
672 }
673
674
675 void Tabular::appendColumn(idx_type const cell)
676 {
677         col_type const column = cellColumn(cell);
678         column_vector::iterator cit = column_info.begin() + column + 1;
679         column_info.insert(cit, ColumnData());
680         row_type const nrows = rowCount();
681         col_type const ncols = columnCount();
682         // set the column values of the column before
683         column_info[column + 1] = column_info[column];
684
685         for (row_type r = 0; r < nrows; ++r) {
686                 cell_info[r].insert(cell_info[r].begin() + column + 1, 
687                         CellData(buffer(), *this));
688                 col_type c = column + 2;
689                 while (c < ncols 
690                         && cell_info[r][c].multicolumn == CELL_PART_OF_MULTICOLUMN) {
691                         cell_info[r][c].multicolumn = CELL_NORMAL;
692                         ++c;
693                 }
694         }
695         updateIndexes();
696         for (row_type r = 0; r < nrows; ++r) {
697                 // inherit line settings
698                 idx_type const i = cellIndex(r, column + 1);
699                 idx_type const j = cellIndex(r, column);
700                 setBottomLine(i, bottomLine(j));
701                 setTopLine(i, topLine(j));
702                 //
703                 cellInfo(i).inset->clear();
704                 if (buffer().params().trackChanges)
705                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
706         }
707 }
708
709
710 void Tabular::deleteColumn(col_type const column)
711 {
712         // Not allowed to delete last column
713         if (columnCount() == 1)
714                 return;
715
716         column_info.erase(column_info.begin() + column);
717         for (row_type i = 0; i < rowCount(); ++i) {
718                 // Care about multicolumn cells
719                 if (column + 1 < columnCount() &&
720                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
721                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
722                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
723                 }
724                 cell_info[i].erase(cell_info[i].begin() + column);
725         }
726         updateIndexes();
727 }
728
729
730 void Tabular::copyColumn(col_type const column)
731 {
732         BufferParams const & bp = buffer().params();
733         column_info.insert(column_info.begin() + column, column_info[column]);
734
735         for (row_type i = 0; i < rowCount(); ++i)
736                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
737
738         if (bp.trackChanges)
739                 for (row_type i = 0; i < rowCount(); ++i)
740                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
741         updateIndexes();
742 }
743
744
745 void Tabular::updateIndexes()
746 {
747         col_type ncols = columnCount();
748         row_type nrows = rowCount();
749         numberofcells = 0;
750         for (row_type row = 0; row < nrows; ++row)
751                 for (col_type column = 0; column < ncols; ++column) {
752                         if (!isPartOfMultiColumn(row, column))
753                                 ++numberofcells;
754                         cell_info[row][column].cellno = numberofcells - 1;
755                 }
756
757         rowofcell.resize(numberofcells);
758         columnofcell.resize(numberofcells);
759         idx_type i = 0;
760         for (row_type row = 0; row < nrows; ++row)
761                 for (col_type column = 0; column < ncols; ++column) {
762                         if (isPartOfMultiColumn(row, column))
763                                 continue;
764                         rowofcell[i] = row;
765                         columnofcell[i] = column;
766                         ++i;
767                 }
768 }
769
770
771 Tabular::idx_type Tabular::cellCount() const
772 {
773         return numberofcells;
774 }
775
776
777 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
778 {
779         row_type const row = cellRow(cell);
780         idx_type result = 0;
781         for (col_type i = 0; i < columnCount(); ++i)
782                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
783                         ++result;
784         return result;
785 }
786
787
788 bool Tabular::topLine(idx_type const cell) const
789 {
790         return cellInfo(cell).top_line;
791 }
792
793
794 bool Tabular::bottomLine(idx_type const cell) const
795 {
796         return cellInfo(cell).bottom_line;
797 }
798
799
800 bool Tabular::leftLine(idx_type cell) const
801 {
802         if (use_booktabs)
803                 return false;
804         return cellInfo(cell).left_line;
805 }
806
807
808 bool Tabular::rightLine(idx_type cell) const
809 {
810         if (use_booktabs)
811                 return false;
812         return cellInfo(cell).right_line;
813 }
814
815
816 bool Tabular::topAlreadyDrawn(idx_type cell) const
817 {
818         row_type row = cellRow(cell);
819         if (row == 0)
820                 return false;
821         idx_type i = cellIndex(row - 1, cellColumn(cell));
822         return !rowTopLine(row) && bottomLine(i);
823 }
824
825
826 bool Tabular::leftAlreadyDrawn(idx_type cell) const
827 {
828         col_type col = cellColumn(cell);
829         if (col == 0)
830                 return false;
831         idx_type i = cellIndex(cellRow(cell), col - 1);
832         return rightLine(i) && !leftLine(cell);
833 }
834
835
836 bool Tabular::isLastRow(idx_type cell) const
837 {
838         return cellRow(cell) == rowCount() - 1;
839 }
840
841
842 int Tabular::getAdditionalHeight(row_type row) const
843 {
844         if (!row || row >= rowCount())
845                 return 0;
846
847         int const interline_space = row_info[row - 1].interline_space_default ?
848                 default_line_space :
849                 row_info[row - 1].interline_space.inPixels(width());
850         if (rowTopLine(row) && rowBottomLine(row - 1))
851                 return interline_space + WIDTH_OF_LINE;
852         return interline_space;
853 }
854
855
856 int Tabular::getAdditionalWidth(idx_type cell) const
857 {
858         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
859         if (rightLine(cell) 
860                 && nextcol < columnCount() && leftLine(cellIndex(cellRow(cell), nextcol)))
861                 return WIDTH_OF_LINE;
862         return 0;
863 }
864
865
866 int Tabular::columnWidth(idx_type cell) const
867 {
868         int w = 0;
869         col_type const span = columnSpan(cell);
870         col_type const col = cellColumn(cell);
871         for(col_type c = col; c < col + span ; ++c)
872                 w += column_info[c].width;
873         return w;
874 }
875
876
877 bool Tabular::updateColumnWidths()
878 {
879         col_type const ncols = columnCount();
880         row_type const nrows = rowCount();
881         bool update = false;
882         // for each col get max of single col cells
883         for(col_type c = 0; c < ncols; ++c) {
884                 int new_width = 0;
885                 for(row_type r = 0; r < nrows; ++r) {
886                         idx_type const i = cellIndex(r, c);
887                         if (columnSpan(i) == 1)
888                                 new_width = max(new_width, cellInfo(i).width);
889                 }
890
891                 if (column_info[c].width != new_width) {
892                         column_info[c].width = new_width;
893                         update = true;
894                 }
895         }
896         // update col widths to fit merged cells
897         for(col_type c = 0; c < ncols; ++c)
898                 for(row_type r = 0; r < nrows; ++r) {
899                         idx_type const i = cellIndex(r, c);
900                         int const span = columnSpan(i);
901                         if (span == 1 || c > cellColumn(i))
902                                 continue;
903
904                         int old_width = 0;
905                         for(col_type j = c; j < c + span ; ++j)
906                                 old_width += column_info[j].width;
907
908                         if (cellInfo(i).width > old_width) {
909                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
910                                 update = true;
911                         }
912                 }
913
914         return update;
915 }
916
917
918 int Tabular::width() const
919 {
920         col_type const ncols = columnCount();
921         int width = 0;
922         for (col_type i = 0; i < ncols; ++i)
923                 width += column_info[i].width;
924         return width;
925 }
926
927
928 void Tabular::setCellWidth(idx_type cell, int new_width)
929 {
930         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
931                 + getAdditionalWidth(cell);
932 }
933
934
935 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
936                               bool onlycolumn)
937 {
938         if (!isMultiColumn(cell) || onlycolumn)
939                 column_info[cellColumn(cell)].alignment = align;
940         if (!onlycolumn)
941                 cellInfo(cell).alignment = align;
942 }
943
944
945 void Tabular::setVAlignment(idx_type cell, VAlignment align,
946                                bool onlycolumn)
947 {
948         if (!isMultiColumn(cell) || onlycolumn)
949                 column_info[cellColumn(cell)].valignment = align;
950         if (!onlycolumn)
951                 cellInfo(cell).valignment = align;
952 }
953
954
955 namespace {
956
957 /**
958  * Allow line and paragraph breaks for fixed width cells or disallow them,
959  * merge cell paragraphs and reset layout to standard for variable width
960  * cells.
961  */
962 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
963 {
964         inset->setAutoBreakRows(fixedWidth);
965         if (fixedWidth)
966                 return;
967
968         // merge all paragraphs to one
969         BufferParams const & bp = cur.bv().buffer().params();
970         while (inset->paragraphs().size() > 1)
971                 mergeParagraph(bp, inset->paragraphs(), 0);
972
973         // reset layout
974         cur.push(*inset);
975         // undo information has already been recorded
976         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
977                         bp.documentClass().emptyLayoutName());
978         cur.pop();
979 }
980
981 }
982
983
984 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
985                 Length const & width)
986 {
987         col_type const j = cellColumn(cell);
988
989         column_info[j].p_width = width;
990         for (row_type i = 0; i < rowCount(); ++i) {
991                 idx_type const cell = cellIndex(i, j);
992                 // because of multicolumns
993                 toggleFixedWidth(cur, cellInset(cell).get(),
994                                  !getPWidth(cell).zero());
995         }
996         // cur paragraph can become invalid after paragraphs were merged
997         if (cur.pit() > cur.lastpit())
998                 cur.pit() = cur.lastpit();
999         // cur position can become invalid after newlines were removed
1000         if (cur.pos() > cur.lastpos())
1001                 cur.pos() = cur.lastpos();
1002 }
1003
1004
1005 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1006                 Length const & width)
1007 {
1008         if (!isMultiColumn(cell))
1009                 return false;
1010
1011         cellInfo(cell).p_width = width;
1012         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1013         // cur paragraph can become invalid after paragraphs were merged
1014         if (cur.pit() > cur.lastpit())
1015                 cur.pit() = cur.lastpit();
1016         // cur position can become invalid after newlines were removed
1017         if (cur.pos() > cur.lastpos())
1018                 cur.pos() = cur.lastpos();
1019         return true;
1020 }
1021
1022
1023 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1024                                  Tabular::Feature what)
1025 {
1026         if (what == SET_SPECIAL_MULTI)
1027                 cellInfo(cell).align_special = special;
1028         else
1029                 column_info[cellColumn(cell)].align_special = special;
1030 }
1031
1032
1033 void Tabular::setAllLines(idx_type cell, bool line)
1034 {
1035         setTopLine(cell, line);
1036         setBottomLine(cell, line);
1037         setRightLine(cell, line);
1038         setLeftLine(cell, line);
1039 }
1040
1041
1042 void Tabular::setTopLine(idx_type i, bool line)
1043 {
1044         cellInfo(i).top_line = line;
1045 }
1046
1047
1048 void Tabular::setBottomLine(idx_type i, bool line)
1049 {
1050         cellInfo(i).bottom_line = line;
1051 }
1052
1053
1054 void Tabular::setLeftLine(idx_type cell, bool line)
1055 {
1056         cellInfo(cell).left_line = line;
1057 }
1058
1059
1060 void Tabular::setRightLine(idx_type cell, bool line)
1061 {
1062         cellInfo(cell).right_line = line;
1063 }
1064
1065 bool Tabular::rowTopLine(row_type r) const
1066 {
1067         idx_type i0 = getFirstCellInRow(r);
1068         idx_type i1 = getLastCellInRow(r);
1069         bool all_rows_set = true;
1070         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1071                 all_rows_set = cellInfo(j).top_line;
1072         return all_rows_set;
1073 }
1074
1075
1076 bool Tabular::rowBottomLine(row_type r) const
1077 {
1078         idx_type i0 = getFirstCellInRow(r);
1079         idx_type i1 = getLastCellInRow(r);
1080         bool all_rows_set = true;
1081         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1082                 all_rows_set = cellInfo(j).bottom_line;
1083         return all_rows_set;
1084 }
1085
1086
1087 bool Tabular::columnLeftLine(col_type c) const
1088 {
1089         bool all_cols_set = true;
1090         row_type const nrows = rowCount();
1091         for (row_type r = 0; all_cols_set && r < nrows; ++r) {
1092                 idx_type i = cellIndex(r, c);
1093                 if (c == cellColumn(i))
1094                         all_cols_set = cellInfo(i).left_line;
1095         }
1096         return all_cols_set;
1097 }
1098
1099
1100 bool Tabular::columnRightLine(col_type c) const
1101 {
1102         bool all_cols_set = true;
1103         row_type const nrows = rowCount();
1104         for (row_type r = 0; all_cols_set && r < nrows; ++r) {
1105                 idx_type i = cellIndex(r, c);
1106                 if (c == cellColumn(i) + columnSpan(i) - 1)
1107                         all_cols_set = cellInfo(i).right_line;
1108         }
1109         return all_cols_set;
1110 }
1111
1112
1113 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1114 {
1115         if (!onlycolumn && isMultiColumn(cell))
1116                 return cellInfo(cell).alignment;
1117         return column_info[cellColumn(cell)].alignment;
1118 }
1119
1120
1121 Tabular::VAlignment
1122 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1123 {
1124         if (!onlycolumn && isMultiColumn(cell))
1125                 return cellInfo(cell).valignment;
1126         return column_info[cellColumn(cell)].valignment;
1127 }
1128
1129
1130 Length const Tabular::getPWidth(idx_type cell) const
1131 {
1132         if (isMultiColumn(cell))
1133                 return cellInfo(cell).p_width;
1134         return column_info[cellColumn(cell)].p_width;
1135 }
1136
1137
1138 Length const Tabular::getColumnPWidth(idx_type cell) const
1139 {
1140         return column_info[cellColumn(cell)].p_width;
1141 }
1142
1143
1144 Length const Tabular::getMColumnPWidth(idx_type cell) const
1145 {
1146         if (isMultiColumn(cell))
1147                 return cellInfo(cell).p_width;
1148         return Length();
1149 }
1150
1151
1152 docstring const Tabular::getAlignSpecial(idx_type cell, int what) const
1153 {
1154         if (what == SET_SPECIAL_MULTI)
1155                 return cellInfo(cell).align_special;
1156         return column_info[cellColumn(cell)].align_special;
1157 }
1158
1159
1160 int Tabular::cellWidth(idx_type cell) const
1161 {
1162         return cellInfo(cell).width;
1163 }
1164
1165
1166 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1167 {
1168         int x = 0;
1169
1170         switch (getAlignment(cell)) {
1171         case LYX_ALIGN_CENTER:
1172                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1173                 break;
1174         case LYX_ALIGN_RIGHT:
1175                 x += columnWidth(cell) - cellWidth(cell);
1176                 // + getAdditionalWidth(cell);
1177                 break;
1178         default:
1179                 // LYX_ALIGN_LEFT: nothing :-)
1180                 break;
1181         }
1182
1183         // the LaTeX Way :-(
1184         x += WIDTH_OF_LINE;
1185         return x;
1186 }
1187
1188
1189 bool Tabular::isFirstCellInRow(idx_type cell) const
1190 {
1191         return cellColumn(cell) == 0;
1192 }
1193
1194
1195 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1196 {
1197         if (row > rowCount() - 1)
1198                 row = rowCount() - 1;
1199         return cell_info[row][0].cellno;
1200 }
1201
1202
1203 bool Tabular::isLastCellInRow(idx_type cell) const
1204 {
1205         return cellRightColumn(cell) == columnCount() - 1;
1206 }
1207
1208
1209 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1210 {
1211         if (row > rowCount() - 1)
1212                 row = rowCount() - 1;
1213         return cell_info[row][columnCount() - 1].cellno;
1214 }
1215
1216
1217 Tabular::row_type Tabular::cellRow(idx_type cell) const
1218 {
1219         if (cell >= cellCount())
1220                 return rowCount() - 1;
1221         if (cell == npos)
1222                 return 0;
1223         return rowofcell[cell];
1224 }
1225
1226
1227 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1228 {
1229         if (cell >= cellCount())
1230                 return columnCount() - 1;
1231         if (cell == npos)
1232                 return 0;
1233         return columnofcell[cell];
1234 }
1235
1236
1237 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1238 {
1239         row_type const row = cellRow(cell);
1240         col_type column = cellColumn(cell);
1241         while (column < columnCount() - 1 &&
1242                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1243                 ++column;
1244         return column;
1245 }
1246
1247
1248 void Tabular::write(ostream & os) const
1249 {
1250         // header line
1251         os << "<lyxtabular"
1252            << write_attribute("version", 3)
1253            << write_attribute("rows", rowCount())
1254            << write_attribute("columns", columnCount())
1255            << ">\n";
1256         // global longtable options
1257         os << "<features"
1258            << write_attribute("rotate", rotate)
1259            << write_attribute("booktabs", use_booktabs)
1260            << write_attribute("islongtable", is_long_tabular)
1261            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1262            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1263            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1264            << write_attribute("headTopDL", endhead.topDL)
1265            << write_attribute("headBottomDL", endhead.bottomDL)
1266            << write_attribute("footTopDL", endfoot.topDL)
1267            << write_attribute("footBottomDL", endfoot.bottomDL)
1268            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1269            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1270            << write_attribute("lastFootEmpty", endlastfoot.empty)
1271            << ">\n";
1272         for (col_type j = 0; j < columnCount(); ++j) {
1273                 os << "<column"
1274                    << write_attribute("alignment", column_info[j].alignment)
1275                    << write_attribute("valignment", column_info[j].valignment)
1276                    << write_attribute("width", column_info[j].p_width.asString())
1277                    << write_attribute("special", column_info[j].align_special)
1278                    << ">\n";
1279         }
1280         for (row_type i = 0; i < rowCount(); ++i) {
1281                 static const string def("default");
1282                 os << "<row";
1283                 if (row_info[i].top_space_default)
1284                         os << write_attribute("topspace", def);
1285                 else
1286                         os << write_attribute("topspace", row_info[i].top_space);
1287                 if (row_info[i].bottom_space_default)
1288                         os << write_attribute("bottomspace", def);
1289                 else
1290                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1291                 if (row_info[i].interline_space_default)
1292                         os << write_attribute("interlinespace", def);
1293                 else
1294                         os << write_attribute("interlinespace", row_info[i].interline_space);
1295                 os << write_attribute("endhead", row_info[i].endhead)
1296                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1297                    << write_attribute("endfoot", row_info[i].endfoot)
1298                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1299                    << write_attribute("newpage", row_info[i].newpage)
1300                    << ">\n";
1301                 for (col_type j = 0; j < columnCount(); ++j) {
1302                         os << "<cell"
1303                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1304                            << write_attribute("alignment", cell_info[i][j].alignment)
1305                            << write_attribute("valignment", cell_info[i][j].valignment)
1306                            << write_attribute("topline", cell_info[i][j].top_line)
1307                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1308                            << write_attribute("leftline", cell_info[i][j].left_line)
1309                            << write_attribute("rightline", cell_info[i][j].right_line)
1310                            << write_attribute("rotate", cell_info[i][j].rotate)
1311                            << write_attribute("usebox", cell_info[i][j].usebox)
1312                            << write_attribute("width", cell_info[i][j].p_width)
1313                            << write_attribute("special", cell_info[i][j].align_special)
1314                            << ">\n";
1315                         os << "\\begin_inset ";
1316                         cell_info[i][j].inset->write(os);
1317                         os << "\n\\end_inset\n"
1318                            << "</cell>\n";
1319                 }
1320                 os << "</row>\n";
1321         }
1322         os << "</lyxtabular>\n";
1323 }
1324
1325
1326 void Tabular::read(Lexer & lex)
1327 {
1328         string line;
1329         istream & is = lex.getStream();
1330
1331         l_getline(is, line);
1332         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1333                 LASSERT(false, /**/);
1334                 return;
1335         }
1336
1337         int version;
1338         if (!getTokenValue(line, "version", version))
1339                 return;
1340         LASSERT(version >= 2, /**/);
1341
1342         int rows_arg;
1343         if (!getTokenValue(line, "rows", rows_arg))
1344                 return;
1345         int columns_arg;
1346         if (!getTokenValue(line, "columns", columns_arg))
1347                 return;
1348         init(buffer(), rows_arg, columns_arg);
1349         l_getline(is, line);
1350         if (!prefixIs(line, "<features")) {
1351                 lyxerr << "Wrong tabular format (expected <features ...> got"
1352                        << line << ')' << endl;
1353                 return;
1354         }
1355         getTokenValue(line, "rotate", rotate);
1356         getTokenValue(line, "booktabs", use_booktabs);
1357         getTokenValue(line, "islongtable", is_long_tabular);
1358         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1359         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1360         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1361         getTokenValue(line, "headTopDL", endhead.topDL);
1362         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1363         getTokenValue(line, "footTopDL", endfoot.topDL);
1364         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1365         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1366         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1367         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1368
1369         for (col_type j = 0; j < columnCount(); ++j) {
1370                 l_getline(is,line);
1371                 if (!prefixIs(line,"<column")) {
1372                         lyxerr << "Wrong tabular format (expected <column ...> got"
1373                                << line << ')' << endl;
1374                         return;
1375                 }
1376                 getTokenValue(line, "alignment", column_info[j].alignment);
1377                 getTokenValue(line, "valignment", column_info[j].valignment);
1378                 getTokenValue(line, "width", column_info[j].p_width);
1379                 getTokenValue(line, "special", column_info[j].align_special);
1380         }
1381
1382         for (row_type i = 0; i < rowCount(); ++i) {
1383                 l_getline(is, line);
1384                 if (!prefixIs(line, "<row")) {
1385                         lyxerr << "Wrong tabular format (expected <row ...> got"
1386                                << line << ')' << endl;
1387                         return;
1388                 }
1389                 getTokenValue(line, "topspace", row_info[i].top_space,
1390                               row_info[i].top_space_default);
1391                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1392                               row_info[i].bottom_space_default);
1393                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1394                               row_info[i].interline_space_default);
1395                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1396                 getTokenValue(line, "endhead", row_info[i].endhead);
1397                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1398                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1399                 getTokenValue(line, "newpage", row_info[i].newpage);
1400                 for (col_type j = 0; j < columnCount(); ++j) {
1401                         l_getline(is, line);
1402                         if (!prefixIs(line, "<cell")) {
1403                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1404                                        << line << ')' << endl;
1405                                 return;
1406                         }
1407                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1408                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1409                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1410                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1411                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1412                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1413                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1414                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1415                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1416                         getTokenValue(line, "width", cell_info[i][j].p_width);
1417                         getTokenValue(line, "special", cell_info[i][j].align_special);
1418                         l_getline(is, line);
1419                         if (prefixIs(line, "\\begin_inset")) {
1420                                 cell_info[i][j].inset->read(lex);
1421                                 l_getline(is, line);
1422                         }
1423                         if (!prefixIs(line, "</cell>")) {
1424                                 lyxerr << "Wrong tabular format (expected </cell> got"
1425                                        << line << ')' << endl;
1426                                 return;
1427                         }
1428                 }
1429                 l_getline(is, line);
1430                 if (!prefixIs(line, "</row>")) {
1431                         lyxerr << "Wrong tabular format (expected </row> got"
1432                                << line << ')' << endl;
1433                         return;
1434                 }
1435         }
1436         while (!prefixIs(line, "</lyxtabular>")) {
1437                 l_getline(is, line);
1438         }
1439         updateIndexes();
1440 }
1441
1442
1443 bool Tabular::isMultiColumn(idx_type cell) const
1444 {
1445         return cellInfo(cell).multicolumn != CELL_NORMAL;
1446 }
1447
1448
1449 bool Tabular::isMultiColumnReal(idx_type cell) const
1450 {
1451         return cellColumn(cell) != cellRightColumn(cell) &&
1452                         cellInfo(cell).multicolumn != CELL_NORMAL;
1453 }
1454
1455
1456 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1457 {
1458         return cell_info[cellRow(cell)][cellColumn(cell)];
1459 }
1460
1461
1462 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1463 {
1464         CellData & cs = cellInfo(cell);
1465         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1466         cs.alignment = column_info[cellColumn(cell)].alignment;
1467         setRightLine(cell, rightLine(cell + number - 1));
1468         for (idx_type i = 1; i < number; ++i) {
1469                 CellData & cs1 = cellInfo(cell + i);
1470                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1471                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1472                 cs1.inset->clear();
1473         }
1474         updateIndexes();
1475 }
1476
1477
1478 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1479 {
1480         row_type const row = cellRow(cell);
1481         col_type const ncols = columnCount();
1482         idx_type result = 1;
1483         col_type column = cellColumn(cell) + 1;
1484         while (column < ncols && isPartOfMultiColumn(row, column)) {
1485                 ++result;
1486                 ++column;
1487         }
1488         return result;
1489 }
1490
1491
1492 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1493 {
1494         row_type const row = cellRow(cell);
1495         col_type column = cellColumn(cell);
1496
1497         idx_type result = 0;
1498
1499         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1500                 cell_info[row][column].multicolumn = CELL_NORMAL;
1501                 ++column;
1502                 while (column < columnCount() &&
1503                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1504                 {
1505                         cell_info[row][column].multicolumn = CELL_NORMAL;
1506                         ++column;
1507                         ++result;
1508                 }
1509         }
1510         updateIndexes();
1511         return result;
1512 }
1513
1514
1515 void Tabular::setBookTabs(bool what)
1516 {
1517         use_booktabs = what;
1518 }
1519
1520
1521 bool Tabular::useBookTabs() const
1522 {
1523         return use_booktabs;
1524 }
1525
1526
1527 void Tabular::setLongTabular(bool what)
1528 {
1529         is_long_tabular = what;
1530 }
1531
1532
1533 bool Tabular::isLongTabular() const
1534 {
1535         return is_long_tabular;
1536 }
1537
1538
1539 void Tabular::setRotateTabular(bool flag)
1540 {
1541         rotate = flag;
1542 }
1543
1544
1545 bool Tabular::getRotateTabular() const
1546 {
1547         return rotate;
1548 }
1549
1550
1551 void Tabular::setRotateCell(idx_type cell, bool flag)
1552 {
1553         cellInfo(cell).rotate = flag;
1554 }
1555
1556
1557 bool Tabular::getRotateCell(idx_type cell) const
1558 {
1559         return cellInfo(cell).rotate;
1560 }
1561
1562
1563 bool Tabular::needRotating() const
1564 {
1565         if (rotate)
1566                 return true;
1567         for (row_type i = 0; i < rowCount(); ++i)
1568                 for (col_type j = 0; j < columnCount(); ++j)
1569                         if (cell_info[i][j].rotate)
1570                                 return true;
1571         return false;
1572 }
1573
1574
1575 bool Tabular::isLastCell(idx_type cell) const
1576 {
1577         if (cell + 1 < cellCount())
1578                 return false;
1579         return true;
1580 }
1581
1582
1583 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1584 {
1585         if (cellRow(cell) > 0)
1586                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1587         return cell;
1588 }
1589
1590
1591 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1592 {
1593         if (cellRow(cell) + 1 < rowCount())
1594                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1595         return cell;
1596 }
1597
1598
1599 Tabular::idx_type Tabular::cellIndex(row_type row,
1600                                                col_type column) const
1601 {
1602         BOOST_ASSERT(column != npos && column < columnCount() &&
1603                      row    != npos && row    < rowCount());
1604         return cell_info[row][column].cellno;
1605 }
1606
1607
1608 void Tabular::setUsebox(idx_type cell, BoxType type)
1609 {
1610         cellInfo(cell).usebox = type;
1611 }
1612
1613
1614 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1615 {
1616         if (column_info[cellColumn(cell)].p_width.zero() &&
1617                 !(isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1618                 return BOX_NONE;
1619         if (cellInfo(cell).usebox > 1)
1620                 return cellInfo(cell).usebox;
1621         return useParbox(cell);
1622 }
1623
1624
1625 ///
1626 //  This are functions used for the longtable support
1627 ///
1628 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1629                            bool first)
1630 {
1631         if (first) {
1632                 endfirsthead = hd;
1633                 if (hd.set)
1634                         row_info[row].endfirsthead = flag;
1635         } else {
1636                 endhead = hd;
1637                 if (hd.set)
1638                         row_info[row].endhead = flag;
1639         }
1640 }
1641
1642
1643 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1644 {
1645         hd = endhead;
1646         hd.set = haveLTHead();
1647         return row_info[row].endhead;
1648 }
1649
1650
1651 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1652 {
1653         hd = endfirsthead;
1654         hd.set = haveLTFirstHead();
1655         return row_info[row].endfirsthead;
1656 }
1657
1658
1659 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1660                            bool last)
1661 {
1662         if (last) {
1663                 endlastfoot = fd;
1664                 if (fd.set)
1665                         row_info[row].endlastfoot = flag;
1666         } else {
1667                 endfoot = fd;
1668                 if (fd.set)
1669                         row_info[row].endfoot = flag;
1670         }
1671 }
1672
1673
1674 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1675 {
1676         fd = endfoot;
1677         fd.set = haveLTFoot();
1678         return row_info[row].endfoot;
1679 }
1680
1681
1682 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1683 {
1684         fd = endlastfoot;
1685         fd.set = haveLTLastFoot();
1686         return row_info[row].endlastfoot;
1687 }
1688
1689
1690 void Tabular::setLTNewPage(row_type row, bool what)
1691 {
1692         row_info[row].newpage = what;
1693 }
1694
1695
1696 bool Tabular::getLTNewPage(row_type row) const
1697 {
1698         return row_info[row].newpage;
1699 }
1700
1701
1702 bool Tabular::haveLTHead() const
1703 {
1704         for (row_type i = 0; i < rowCount(); ++i)
1705                 if (row_info[i].endhead)
1706                         return true;
1707         return false;
1708 }
1709
1710
1711 bool Tabular::haveLTFirstHead() const
1712 {
1713         if (endfirsthead.empty)
1714                 return false;
1715         for (row_type i = 0; i < rowCount(); ++i)
1716                 if (row_info[i].endfirsthead)
1717                         return true;
1718         return false;
1719 }
1720
1721
1722 bool Tabular::haveLTFoot() const
1723 {
1724         for (row_type i = 0; i < rowCount(); ++i)
1725                 if (row_info[i].endfoot)
1726                         return true;
1727         return false;
1728 }
1729
1730
1731 bool Tabular::haveLTLastFoot() const
1732 {
1733         if (endlastfoot.empty)
1734                 return false;
1735         for (row_type i = 0; i < rowCount(); ++i)
1736                 if (row_info[i].endlastfoot)
1737                         return true;
1738         return false;
1739 }
1740
1741
1742 // end longtable support functions
1743
1744 void Tabular::setRowAscent(row_type row, int height)
1745 {
1746         if (row >= rowCount() || row_info[row].ascent == height)
1747                 return;
1748         row_info[row].ascent = height;
1749 }
1750
1751
1752 void Tabular::setRowDescent(row_type row, int height)
1753 {
1754         if (row >= rowCount() || row_info[row].descent == height)
1755                 return;
1756         row_info[row].descent = height;
1757 }
1758
1759
1760 int Tabular::rowAscent(row_type row) const
1761 {
1762         if (row >= rowCount())
1763                 return 0;
1764         return row_info[row].ascent;
1765 }
1766
1767
1768 int Tabular::rowDescent(row_type row) const
1769 {
1770         LASSERT(row < rowCount(), /**/);
1771         return row_info[row].descent;
1772 }
1773
1774
1775 int Tabular::height() const
1776 {
1777         int height = 0;
1778         for (row_type row = 0; row < rowCount(); ++row)
1779                 height += rowAscent(row) + rowDescent(row) +
1780                         getAdditionalHeight(row);
1781         return height;
1782 }
1783
1784
1785 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1786 {
1787         LASSERT(row < rowCount(), /**/);
1788         LASSERT(column < columnCount(), /**/);
1789         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1790 }
1791
1792
1793 int Tabular::TeXTopHLine(odocstream & os, row_type row) const
1794 {
1795         // FIXME: assert or return 0 as in TeXBottomHLine()?
1796         LASSERT(row != npos, /**/);
1797         LASSERT(row < rowCount(), /**/);
1798
1799         idx_type const fcell = getFirstCellInRow(row);
1800         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1801         idx_type tmp = 0;
1802
1803         for (idx_type i = fcell; i < n; ++i) {
1804                 if (topLine(i))
1805                         ++tmp;
1806         }
1807         if (use_booktabs && row == 0) {
1808                 if (topLine(fcell))
1809                         os << "\\toprule ";
1810         } else if (tmp == n - fcell) {
1811                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1812         } else if (tmp) {
1813                 for (idx_type i = fcell; i < n; ++i) {
1814                         if (topLine(i)) {
1815                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1816                                    << cellColumn(i) + 1
1817                                    << '-'
1818                                    << cellRightColumn(i) + 1
1819                                    << "} ";
1820                         }
1821                 }
1822         } else {
1823                 return 0;
1824         }
1825         os << "\n";
1826         return 1;
1827 }
1828
1829
1830 int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
1831 {
1832         // FIXME: return 0 or assert as in TeXTopHLine()?
1833         if (row == npos || row >= rowCount())
1834                 return 0;
1835
1836         idx_type const fcell = getFirstCellInRow(row);
1837         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1838         idx_type tmp = 0;
1839
1840         for (idx_type i = fcell; i < n; ++i) {
1841                 if (bottomLine(i))
1842                         ++tmp;
1843         }
1844         if (use_booktabs && row == rowCount() - 1) {
1845                 if (bottomLine(fcell))
1846                         os << "\\bottomrule";
1847         } else if (tmp == n - fcell) {
1848                 os << (use_booktabs ? "\\midrule" : "\\hline");
1849         } else if (tmp) {
1850                 for (idx_type i = fcell; i < n; ++i) {
1851                         if (bottomLine(i)) {
1852                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1853                                    << cellColumn(i) + 1
1854                                    << '-'
1855                                    << cellRightColumn(i) + 1
1856                                    << "} ";
1857                         }
1858                 }
1859         } else {
1860                 return 0;
1861         }
1862         os << "\n";
1863         return 1;
1864 }
1865
1866
1867 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1868 {
1869         int ret = 0;
1870
1871         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1872         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1873         // figure out how to set the lines
1874         // we always set double lines to the right of the cell
1875         row_type const r = cellRow(cell);
1876         col_type const c = cellColumn(cell);
1877         col_type const nextcol = c + columnSpan(cell);
1878         bool prevcellright = c > 0 && rightLine(cellIndex(r, c - 1));
1879         bool forceleft = ismulticol && !prevcellright && leftLine(cell);
1880         bool nextcolleft = nextcol < columnCount() && columnLeftLine(nextcol);
1881         bool coldouble = columnRightLine(c) && nextcolleft;
1882         bool nextcellleft = nextcol < columnCount() 
1883                 && leftLine(cellIndex(r, nextcol));
1884         bool celldouble = rightLine(cell) && nextcellleft;
1885         bool doubleright = celldouble && (isMultiColumn(cell) || !coldouble);
1886         ismulticol = isMultiColumn(cell) 
1887                 || (leftLine(cell) && !columnLeftLine(c))
1888                 || (rightLine(cell) && !columnRightLine(c))
1889                 || (!celldouble && coldouble) || doubleright || forceleft;
1890         if (ismulticol) {
1891                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
1892                 if (leftLine(cell) || forceleft)
1893                         os << '|';
1894                 if (!cellInfo(cell).align_special.empty()) {
1895                         os << cellInfo(cell).align_special;
1896                 } else {
1897                         if (!getPWidth(cell).zero()) {
1898                                 switch (valign) {
1899                                 case LYX_VALIGN_TOP:
1900                                         os << 'p';
1901                                         break;
1902                                 case LYX_VALIGN_MIDDLE:
1903                                         os << 'm';
1904                                         break;
1905                                 case LYX_VALIGN_BOTTOM:
1906                                         os << 'b';
1907                                         break;
1908                                 }
1909                                 os << '{'
1910                                    << from_ascii(getPWidth(cell).asLatexString())
1911                                    << '}';
1912                         } else {
1913                                 switch (align) {
1914                                 case LYX_ALIGN_LEFT:
1915                                         os << 'l';
1916                                         break;
1917                                 case LYX_ALIGN_RIGHT:
1918                                         os << 'r';
1919                                         break;
1920                                 default:
1921                                         os << 'c';
1922                                         break;
1923                                 }
1924                         } // end if else !getPWidth
1925                 } // end if else !cellinfo_of_cell
1926                 if (rightLine(cell))
1927                         os << '|';
1928                 if (doubleright)
1929                         // add extra vertical line if we want a double one
1930                         os << '|';
1931                 os << "}{";
1932                 }
1933         if (getRotateCell(cell)) {
1934                 os << "\\begin{sideways}\n";
1935                 ++ret;
1936         }
1937         if (getUsebox(cell) == BOX_PARBOX) {
1938                 os << "\\parbox[";
1939                 switch (valign) {
1940                 case LYX_VALIGN_TOP:
1941                         os << 't';
1942                         break;
1943                 case LYX_VALIGN_MIDDLE:
1944                         os << 'c';
1945                         break;
1946                 case LYX_VALIGN_BOTTOM:
1947                         os << 'b';
1948                         break;
1949                 }
1950                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1951                    << "}{";
1952         } else if (getUsebox(cell) == BOX_MINIPAGE) {
1953                 os << "\\begin{minipage}[";
1954                 switch (valign) {
1955                 case LYX_VALIGN_TOP:
1956                         os << 't';
1957                         break;
1958                 case LYX_VALIGN_MIDDLE:
1959                         os << 'm';
1960                         break;
1961                 case LYX_VALIGN_BOTTOM:
1962                         os << 'b';
1963                         break;
1964                 }
1965                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1966                    << "}\n";
1967                 ++ret;
1968         }
1969         return ret;
1970 }
1971
1972
1973 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
1974 {
1975         int ret = 0;
1976
1977         // usual cells
1978         if (getUsebox(cell) == BOX_PARBOX)
1979                 os << '}';
1980         else if (getUsebox(cell) == BOX_MINIPAGE) {
1981                 os << "%\n\\end{minipage}";
1982                 ret += 2;
1983         }
1984         if (getRotateCell(cell)) {
1985                 os << "%\n\\end{sideways}";
1986                 ++ret;
1987         }
1988         if (ismulticol) {
1989                 os << '}';
1990         }
1991         return ret;
1992 }
1993
1994
1995 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
1996                                          OutputParams const & runparams) const
1997 {
1998         if (!is_long_tabular)
1999                 return 0;
2000
2001         int ret = 0;
2002         // output header info
2003         if (haveLTHead()) {
2004                 if (endhead.topDL) {
2005                         os << "\\hline\n";
2006                         ++ret;
2007                 }
2008                 for (row_type i = 0; i < rowCount(); ++i) {
2009                         if (row_info[i].endhead) {
2010                                 ret += TeXRow(os, i, runparams);
2011                         }
2012                 }
2013                 if (endhead.bottomDL) {
2014                         os << "\\hline\n";
2015                         ++ret;
2016                 }
2017                 os << "\\endhead\n";
2018                 ++ret;
2019                 if (endfirsthead.empty) {
2020                         os << "\\endfirsthead\n";
2021                         ++ret;
2022                 }
2023         }
2024         // output firstheader info
2025         if (haveLTFirstHead()) {
2026                 if (endfirsthead.topDL) {
2027                         os << "\\hline\n";
2028                         ++ret;
2029                 }
2030                 for (row_type i = 0; i < rowCount(); ++i) {
2031                         if (row_info[i].endfirsthead) {
2032                                 ret += TeXRow(os, i, runparams);
2033                         }
2034                 }
2035                 if (endfirsthead.bottomDL) {
2036                         os << "\\hline\n";
2037                         ++ret;
2038                 }
2039                 os << "\\endfirsthead\n";
2040                 ++ret;
2041         }
2042         // output footer info
2043         if (haveLTFoot()) {
2044                 if (endfoot.topDL) {
2045                         os << "\\hline\n";
2046                         ++ret;
2047                 }
2048                 for (row_type i = 0; i < rowCount(); ++i) {
2049                         if (row_info[i].endfoot) {
2050                                 ret += TeXRow(os, i, runparams);
2051                         }
2052                 }
2053                 if (endfoot.bottomDL) {
2054                         os << "\\hline\n";
2055                         ++ret;
2056                 }
2057                 os << "\\endfoot\n";
2058                 ++ret;
2059                 if (endlastfoot.empty) {
2060                         os << "\\endlastfoot\n";
2061                         ++ret;
2062                 }
2063         }
2064         // output lastfooter info
2065         if (haveLTLastFoot()) {
2066                 if (endlastfoot.topDL) {
2067                         os << "\\hline\n";
2068                         ++ret;
2069                 }
2070                 for (row_type i = 0; i < rowCount(); ++i) {
2071                         if (row_info[i].endlastfoot) {
2072                                 ret += TeXRow(os, i, runparams);
2073                         }
2074                 }
2075                 if (endlastfoot.bottomDL) {
2076                         os << "\\hline\n";
2077                         ++ret;
2078                 }
2079                 os << "\\endlastfoot\n";
2080                 ++ret;
2081         }
2082         return ret;
2083 }
2084
2085
2086 bool Tabular::isValidRow(row_type row) const
2087 {
2088         if (!is_long_tabular)
2089                 return true;
2090         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2091                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2092 }
2093
2094
2095 int Tabular::TeXRow(odocstream & os, row_type i,
2096                        OutputParams const & runparams) const
2097 {
2098         idx_type cell = cellIndex(i, 0);
2099         int ret = TeXTopHLine(os, i);
2100         if (row_info[i].top_space_default) {
2101                 if (use_booktabs)
2102                         os << "\\addlinespace\n";
2103                 else
2104                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2105                 ++ret;
2106         } else if(!row_info[i].top_space.zero()) {
2107                 if (use_booktabs)
2108                         os << "\\addlinespace["
2109                            << from_ascii(row_info[i].top_space.asLatexString())
2110                            << "]\n";
2111                 else {
2112                         os << "\\noalign{\\vskip"
2113                            << from_ascii(row_info[i].top_space.asLatexString())
2114                            << "}\n";
2115                 }
2116                 ++ret;
2117         }
2118         bool ismulticol = false;
2119         for (col_type j = 0; j < columnCount(); ++j) {
2120                 if (isPartOfMultiColumn(i, j))
2121                         continue;
2122                 ret += TeXCellPreamble(os, cell, ismulticol);
2123                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2124
2125                 Paragraph const & par = inset->paragraphs().front();
2126                 bool rtl = par.isRTL(buffer().params())
2127                         && !par.empty()
2128                         && getPWidth(cell).zero();
2129
2130                 if (rtl) {
2131                         if (par.getParLanguage(buffer().params())->lang() ==
2132                         "farsi")
2133                                 os << "\\textFR{";
2134                         else if (par.getParLanguage(buffer().params())->lang() == "arabic_arabi")
2135                                 os << "\\textAR{";
2136                         // currently, remaning RTL languages are arabic_arabtex and hebrew
2137                         else
2138                                 os << "\\R{";
2139                 }
2140                 ret += inset->latex(os, runparams);
2141                 if (rtl)
2142                         os << '}';
2143
2144                 ret += TeXCellPostamble(os, cell, ismulticol);
2145                 if (!isLastCellInRow(cell)) { // not last cell in row
2146                         os << " & ";
2147                 }
2148                 ++cell;
2149         }
2150         os << "\\tabularnewline";
2151         if (row_info[i].bottom_space_default) {
2152                 if (use_booktabs)
2153                         os << "\\addlinespace";
2154                 else
2155                         os << "[\\doublerulesep]";
2156         } else if (!row_info[i].bottom_space.zero()) {
2157                 if (use_booktabs)
2158                         os << "\\addlinespace";
2159                 os << '['
2160                    << from_ascii(row_info[i].bottom_space.asLatexString())
2161                    << ']';
2162         }
2163         os << '\n';
2164         ++ret;
2165         ret += TeXBottomHLine(os, i);
2166         if (row_info[i].interline_space_default) {
2167                 if (use_booktabs)
2168                         os << "\\addlinespace\n";
2169                 else
2170                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2171                 ++ret;
2172         } else if (!row_info[i].interline_space.zero()) {
2173                 if (use_booktabs)
2174                         os << "\\addlinespace["
2175                            << from_ascii(row_info[i].interline_space.asLatexString())
2176                            << "]\n";
2177                 else
2178                         os << "\\noalign{\\vskip"
2179                            << from_ascii(row_info[i].interline_space.asLatexString())
2180                            << "}\n";
2181                 ++ret;
2182         }
2183         return ret;
2184 }
2185
2186
2187 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2188 {
2189         int ret = 0;
2190
2191         //+---------------------------------------------------------------------
2192         //+                      first the opening preamble                    +
2193         //+---------------------------------------------------------------------
2194
2195         if (rotate) {
2196                 os << "\\begin{sideways}\n";
2197                 ++ret;
2198         }
2199         if (is_long_tabular)
2200                 os << "\\begin{longtable}{";
2201         else
2202                 os << "\\begin{tabular}{";
2203
2204         for (col_type i = 0; i < columnCount(); ++i) {
2205                 if (!use_booktabs && columnLeftLine(i))
2206                         os << '|';
2207                 if (!column_info[i].align_special.empty()) {
2208                         os << column_info[i].align_special;
2209                 } else {
2210                         if (!column_info[i].p_width.zero()) {
2211                                 switch (column_info[i].alignment) {
2212                                 case LYX_ALIGN_LEFT:
2213                                         os << ">{\\raggedright}";
2214                                         break;
2215                                 case LYX_ALIGN_RIGHT:
2216                                         os << ">{\\raggedleft}";
2217                                         break;
2218                                 case LYX_ALIGN_CENTER:
2219                                         os << ">{\\centering}";
2220                                         break;
2221                                 case LYX_ALIGN_NONE:
2222                                 case LYX_ALIGN_BLOCK:
2223                                 case LYX_ALIGN_LAYOUT:
2224                                 case LYX_ALIGN_SPECIAL:
2225                                         break;
2226                                 }
2227
2228                                 switch (column_info[i].valignment) {
2229                                 case LYX_VALIGN_TOP:
2230                                         os << 'p';
2231                                         break;
2232                                 case LYX_VALIGN_MIDDLE:
2233                                         os << 'm';
2234                                         break;
2235                                 case LYX_VALIGN_BOTTOM:
2236                                         os << 'b';
2237                                         break;
2238                         }
2239                                 os << '{'
2240                                    << from_ascii(column_info[i].p_width.asLatexString())
2241                                    << '}';
2242                         } else {
2243                                 switch (column_info[i].alignment) {
2244                                 case LYX_ALIGN_LEFT:
2245                                         os << 'l';
2246                                         break;
2247                                 case LYX_ALIGN_RIGHT:
2248                                         os << 'r';
2249                                         break;
2250                                 default:
2251                                         os << 'c';
2252                                         break;
2253                                 }
2254                         } // end if else !column_info[i].p_width
2255                 } // end if else !column_info[i].align_special
2256                 if (!use_booktabs && columnRightLine(i))
2257                         os << '|';
2258         }
2259         os << "}\n";
2260         ++ret;
2261
2262         ret += TeXLongtableHeaderFooter(os, runparams);
2263
2264         //+---------------------------------------------------------------------
2265         //+                      the single row and columns (cells)            +
2266         //+---------------------------------------------------------------------
2267
2268         for (row_type i = 0; i < rowCount(); ++i) {
2269                 if (isValidRow(i)) {
2270                         ret += TeXRow(os, i, runparams);
2271                         if (is_long_tabular && row_info[i].newpage) {
2272                                 os << "\\newpage\n";
2273                                 ++ret;
2274                         }
2275                 }
2276         }
2277
2278         //+---------------------------------------------------------------------
2279         //+                      the closing of the tabular                    +
2280         //+---------------------------------------------------------------------
2281
2282         if (is_long_tabular)
2283                 os << "\\end{longtable}";
2284         else
2285                 os << "\\end{tabular}";
2286         if (rotate) {
2287                 os << "\n\\end{sideways}";
2288                 ++ret;
2289         }
2290
2291         return ret;
2292 }
2293
2294
2295 int Tabular::docbookRow(odocstream & os, row_type row,
2296                            OutputParams const & runparams) const
2297 {
2298         int ret = 0;
2299         idx_type cell = getFirstCellInRow(row);
2300
2301         os << "<row>\n";
2302         for (col_type j = 0; j < columnCount(); ++j) {
2303                 if (isPartOfMultiColumn(row, j))
2304                         continue;
2305
2306                 os << "<entry align=\"";
2307                 switch (getAlignment(cell)) {
2308                 case LYX_ALIGN_LEFT:
2309                         os << "left";
2310                         break;
2311                 case LYX_ALIGN_RIGHT:
2312                         os << "right";
2313                         break;
2314                 default:
2315                         os << "center";
2316                         break;
2317                 }
2318
2319                 os << "\" valign=\"";
2320                 switch (getVAlignment(cell)) {
2321                 case LYX_VALIGN_TOP:
2322                         os << "top";
2323                         break;
2324                 case LYX_VALIGN_BOTTOM:
2325                         os << "bottom";
2326                         break;
2327                 case LYX_VALIGN_MIDDLE:
2328                         os << "middle";
2329                 }
2330                 os << '"';
2331
2332                 if (isMultiColumn(cell)) {
2333                         os << " namest=\"col" << j << "\" ";
2334                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2335                 }
2336
2337                 os << '>';
2338                 ret += cellInset(cell)->docbook(os, runparams);
2339                 os << "</entry>\n";
2340                 ++cell;
2341         }
2342         os << "</row>\n";
2343         return ret;
2344 }
2345
2346
2347 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2348 {
2349         int ret = 0;
2350
2351         //+---------------------------------------------------------------------
2352         //+                      first the opening preamble                    +
2353         //+---------------------------------------------------------------------
2354
2355         os << "<tgroup cols=\"" << columnCount()
2356            << "\" colsep=\"1\" rowsep=\"1\">\n";
2357
2358         for (col_type i = 0; i < columnCount(); ++i) {
2359                 os << "<colspec colname=\"col" << i << "\" align=\"";
2360                 switch (column_info[i].alignment) {
2361                 case LYX_ALIGN_LEFT:
2362                         os << "left";
2363                         break;
2364                 case LYX_ALIGN_RIGHT:
2365                         os << "right";
2366                         break;
2367                 default:
2368                         os << "center";
2369                         break;
2370                 }
2371                 os << '"';
2372                 if (runparams.flavor == OutputParams::XML)
2373                         os << '/';
2374                 os << ">\n";
2375                 ++ret;
2376         }
2377
2378         //+---------------------------------------------------------------------
2379         //+                      Long Tabular case                             +
2380         //+---------------------------------------------------------------------
2381
2382         // output header info
2383         if (haveLTHead() || haveLTFirstHead()) {
2384                 os << "<thead>\n";
2385                 ++ret;
2386                 for (row_type i = 0; i < rowCount(); ++i) {
2387                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2388                                 ret += docbookRow(os, i, runparams);
2389                         }
2390                 }
2391                 os << "</thead>\n";
2392                 ++ret;
2393         }
2394         // output footer info
2395         if (haveLTFoot() || haveLTLastFoot()) {
2396                 os << "<tfoot>\n";
2397                 ++ret;
2398                 for (row_type i = 0; i < rowCount(); ++i) {
2399                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2400                                 ret += docbookRow(os, i, runparams);
2401                         }
2402                 }
2403                 os << "</tfoot>\n";
2404                 ++ret;
2405         }
2406
2407         //+---------------------------------------------------------------------
2408         //+                      the single row and columns (cells)            +
2409         //+---------------------------------------------------------------------
2410
2411         os << "<tbody>\n";
2412         ++ret;
2413         for (row_type i = 0; i < rowCount(); ++i) {
2414                 if (isValidRow(i)) {
2415                         ret += docbookRow(os, i, runparams);
2416                 }
2417         }
2418         os << "</tbody>\n";
2419         ++ret;
2420         //+---------------------------------------------------------------------
2421         //+                      the closing of the tabular                    +
2422         //+---------------------------------------------------------------------
2423
2424         os << "</tgroup>";
2425         ++ret;
2426
2427         return ret;
2428 }
2429
2430
2431 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2432                                    vector<unsigned int> const & clen) const
2433 {
2434         idx_type const fcell = getFirstCellInRow(row);
2435         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2436         idx_type tmp = 0;
2437
2438         for (idx_type i = fcell; i < n; ++i) {
2439                 if (topLine(i)) {
2440                         ++tmp;
2441                         break;
2442                 }
2443         }
2444         if (!tmp)
2445                 return false;
2446
2447         char_type ch;
2448         for (idx_type i = fcell; i < n; ++i) {
2449                 if (topLine(i)) {
2450                         if (leftLine(i))
2451                                 os << "+-";
2452                         else
2453                                 os << "--";
2454                         ch = '-';
2455                 } else {
2456                         os << "  ";
2457                         ch = ' ';
2458                 }
2459                 col_type column = cellColumn(i);
2460                 int len = clen[column];
2461                 while (column < columnCount() - 1
2462                        && isPartOfMultiColumn(row, ++column))
2463                         len += clen[column] + 4;
2464                 os << docstring(len, ch);
2465                 if (topLine(i)) {
2466                         if (rightLine(i))
2467                                 os << "-+";
2468                         else
2469                                 os << "--";
2470                 } else {
2471                         os << "  ";
2472                 }
2473         }
2474         os << endl;
2475         return true;
2476 }
2477
2478
2479 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2480                                       vector<unsigned int> const & clen) const
2481 {
2482         idx_type const fcell = getFirstCellInRow(row);
2483         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2484         idx_type tmp = 0;
2485
2486         for (idx_type i = fcell; i < n; ++i) {
2487                 if (bottomLine(i)) {
2488                         ++tmp;
2489                         break;
2490                 }
2491         }
2492         if (!tmp)
2493                 return false;
2494
2495         char_type ch;
2496         for (idx_type i = fcell; i < n; ++i) {
2497                 if (bottomLine(i)) {
2498                         if (leftLine(i))
2499                                 os << "+-";
2500                         else
2501                                 os << "--";
2502                         ch = '-';
2503                 } else {
2504                         os << "  ";
2505                         ch = ' ';
2506                 }
2507                 col_type column = cellColumn(i);
2508                 int len = clen[column];
2509                 while (column < columnCount() -1
2510                        && isPartOfMultiColumn(row, ++column))
2511                         len += clen[column] + 4;
2512                 os << docstring(len, ch);
2513                 if (bottomLine(i)) {
2514                         if (rightLine(i))
2515                                 os << "-+";
2516                         else
2517                                 os << "--";
2518                 } else {
2519                         os << "  ";
2520                 }
2521         }
2522         os << endl;
2523         return true;
2524 }
2525
2526
2527 void Tabular::plaintextPrintCell(odocstream & os,
2528                                OutputParams const & runparams,
2529                                idx_type cell, row_type row, col_type column,
2530                                vector<unsigned int> const & clen,
2531                                bool onlydata) const
2532 {
2533         odocstringstream sstr;
2534         cellInset(cell)->plaintext(sstr, runparams);
2535
2536         if (onlydata) {
2537                 os << sstr.str();
2538                 return;
2539         }
2540
2541         if (leftLine(cell))
2542                 os << "| ";
2543         else
2544                 os << "  ";
2545
2546         unsigned int len1 = sstr.str().length();
2547         unsigned int len2 = clen[column];
2548         while (column < columnCount() -1
2549                && isPartOfMultiColumn(row, ++column))
2550                 len2 += clen[column] + 4;
2551         len2 -= len1;
2552
2553         switch (getAlignment(cell)) {
2554         default:
2555         case LYX_ALIGN_LEFT:
2556                 len1 = 0;
2557                 break;
2558         case LYX_ALIGN_RIGHT:
2559                 len1 = len2;
2560                 len2 = 0;
2561                 break;
2562         case LYX_ALIGN_CENTER:
2563                 len1 = len2 / 2;
2564                 len2 -= len1;
2565                 break;
2566         }
2567
2568         os << docstring(len1, ' ') << sstr.str()
2569            << docstring(len2, ' ');
2570
2571         if (rightLine(cell))
2572                 os << " |";
2573         else
2574                 os << "  ";
2575 }
2576
2577
2578 void Tabular::plaintext(odocstream & os,
2579                            OutputParams const & runparams, int const depth,
2580                            bool onlydata, char_type delim) const
2581 {
2582         // first calculate the width of the single columns
2583         vector<unsigned int> clen(columnCount());
2584
2585         if (!onlydata) {
2586                 // first all non (real) multicolumn cells!
2587                 for (col_type j = 0; j < columnCount(); ++j) {
2588                         clen[j] = 0;
2589                         for (row_type i = 0; i < rowCount(); ++i) {
2590                                 idx_type cell = cellIndex(i, j);
2591                                 if (isMultiColumnReal(cell))
2592                                         continue;
2593                                 odocstringstream sstr;
2594                                 cellInset(cell)->plaintext(sstr, runparams);
2595                                 if (clen[j] < sstr.str().length())
2596                                         clen[j] = sstr.str().length();
2597                         }
2598                 }
2599                 // then all (real) multicolumn cells!
2600                 for (col_type j = 0; j < columnCount(); ++j) {
2601                         for (row_type i = 0; i < rowCount(); ++i) {
2602                                 idx_type cell = cellIndex(i, j);
2603                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2604                                         continue;
2605                                 odocstringstream sstr;
2606                                 cellInset(cell)->plaintext(sstr, runparams);
2607                                 int len = int(sstr.str().length());
2608                                 idx_type const n = columnSpan(cell);
2609                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2610                                         len -= clen[k];
2611                                 if (len > int(clen[j + n - 1]))
2612                                         clen[j + n - 1] = len;
2613                         }
2614                 }
2615         }
2616         idx_type cell = 0;
2617         for (row_type i = 0; i < rowCount(); ++i) {
2618                 if (!onlydata && plaintextTopHLine(os, i, clen))
2619                         os << docstring(depth * 2, ' ');
2620                 for (col_type j = 0; j < columnCount(); ++j) {
2621                         if (isPartOfMultiColumn(i, j))
2622                                 continue;
2623                         if (onlydata && j > 0)
2624                                 // we don't use operator<< for single UCS4 character.
2625                                 // see explanation in docstream.h
2626                                 os.put(delim);
2627                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2628                         ++cell;
2629                 }
2630                 os << endl;
2631                 if (!onlydata) {
2632                         os << docstring(depth * 2, ' ');
2633                         if (plaintextBottomHLine(os, i, clen))
2634                                 os << docstring(depth * 2, ' ');
2635                 }
2636         }
2637 }
2638
2639
2640 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2641 {
2642         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2643 }
2644
2645
2646 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2647                                                col_type column) const
2648 {
2649         return cell_info[row][column].inset;
2650 }
2651
2652
2653 void Tabular::setCellInset(row_type row, col_type column,
2654                               shared_ptr<InsetTableCell> ins) const
2655 {
2656         CellData & cd = cell_info[row][column];
2657         cd.inset = ins;
2658         // reset the InsetTableCell's pointers
2659         ins->setCellData(&cd);
2660         ins->setTabular(this);
2661 }
2662
2663
2664 Tabular::idx_type
2665 Tabular::cellFromInset(Inset const * inset) const
2666 {
2667         // is this inset part of the tabular?
2668         if (!inset) {
2669                 lyxerr << "Error: this is not a cell of the tabular!" << endl;
2670                 LASSERT(false, /**/);
2671         }
2672
2673         for (idx_type cell = 0, n = cellCount(); cell < n; ++cell)
2674                 if (cellInset(cell).get() == inset) {
2675                         LYXERR(Debug::INSETTEXT, "Tabular::cellFromInset: "
2676                                 << "cell=" << cell);
2677                         return cell;
2678                 }
2679
2680         // We should have found a cell at this point
2681         lyxerr << "Tabular::cellFromInset: Cell of inset "
2682                 << inset << " not found!" << endl;
2683         LASSERT(false, /**/);
2684         // shut up compiler
2685         return 0;
2686 }
2687
2688
2689 void Tabular::validate(LaTeXFeatures & features) const
2690 {
2691         features.require("NeedTabularnewline");
2692         if (useBookTabs())
2693                 features.require("booktabs");
2694         if (isLongTabular())
2695                 features.require("longtable");
2696         if (needRotating())
2697                 features.require("rotating");
2698         for (idx_type cell = 0; cell < cellCount(); ++cell) {
2699                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2700                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2701                         features.require("array");
2702                 cellInset(cell)->validate(features);
2703         }
2704 }
2705
2706
2707 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2708 {
2709         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2710         ParagraphList::const_iterator cit = parlist.begin();
2711         ParagraphList::const_iterator end = parlist.end();
2712
2713         for (; cit != end; ++cit)
2714                 for (int i = 0; i < cit->size(); ++i)
2715                         if (cit->isNewline(i))
2716                                 return BOX_PARBOX;
2717
2718         return BOX_NONE;
2719 }
2720
2721
2722 /////////////////////////////////////////////////////////////////////
2723 //
2724 // InsetTableCell
2725 //
2726 /////////////////////////////////////////////////////////////////////
2727
2728 InsetTableCell::InsetTableCell(Buffer const & buf,
2729         Tabular::CellData const * cell, Tabular const * table)
2730         : InsetText(buf), cell_data_(cell), table_(table)
2731 {}
2732
2733
2734 bool InsetTableCell::forceEmptyLayout(idx_type) const
2735 {
2736         LASSERT(table_, /**/);
2737         LASSERT(cell_data_, /**/);
2738         return table_->getPWidth(cell_data_->cellno).zero();
2739 }
2740
2741 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2742 {
2743         LASSERT(table_, /**/);
2744         LASSERT(cell_data_, /**/);
2745         return !table_->getPWidth(cell_data_->cellno).zero();
2746 }
2747
2748 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2749         FuncStatus & status) const
2750 {
2751         bool enabled;
2752         switch (cmd.action) {
2753         case LFUN_LAYOUT:
2754                 enabled = !forceEmptyLayout();
2755                 break;
2756         case LFUN_LAYOUT_PARAGRAPH:
2757                 enabled = allowParagraphCustomization();
2758                 break;
2759         default:
2760                 return InsetText::getStatus(cur, cmd, status);
2761         }
2762         status.enabled(enabled);
2763         return true;
2764 }
2765
2766 /////////////////////////////////////////////////////////////////////
2767 //
2768 // InsetTabular
2769 //
2770 /////////////////////////////////////////////////////////////////////
2771
2772 InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
2773                            col_type columns)
2774         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2775         rowselect_(false), colselect_(false)
2776 {
2777         setBuffer(const_cast<Buffer &>(buf)); // FIXME: remove later
2778 }
2779
2780
2781 InsetTabular::InsetTabular(InsetTabular const & tab)
2782         : Inset(tab), tabular(tab.tabular),  scx_(0)
2783 {
2784         setBuffer(const_cast<Buffer &>(tab.buffer())); // FIXME: remove later
2785 }
2786
2787
2788 InsetTabular::~InsetTabular()
2789 {
2790         hideDialogs("tabular", this);
2791 }
2792
2793
2794 bool InsetTabular::insetAllowed(InsetCode code) const
2795 {
2796         if (code == MATHMACRO_CODE)
2797                 return false;
2798
2799         return true;
2800 }
2801
2802
2803 void InsetTabular::write(ostream & os) const
2804 {
2805         os << "Tabular" << endl;
2806         tabular.write(os);
2807 }
2808
2809
2810 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
2811 {
2812         // FIXME: depending on the selection state, we could offer a different menu.
2813         return from_ascii("context-tabular");
2814 }
2815
2816
2817 void InsetTabular::read(Lexer & lex)
2818 {
2819         //bool const old_format = (lex.getString() == "\\LyXTable");
2820
2821         tabular.read(lex);
2822
2823         //if (old_format)
2824         //      return;
2825
2826         lex.next();
2827         string token = lex.getString();
2828         while (lex && token != "\\end_inset") {
2829                 lex.next();
2830                 token = lex.getString();
2831         }
2832         if (!lex)
2833                 lex.printError("Missing \\end_inset at this point. ");
2834 }
2835
2836
2837 int InsetTabular::rowFromY(Cursor & cur, int y) const
2838 {
2839         // top y coordinate of tabular
2840         int h = yo(cur.bv()) - tabular.rowAscent(0);
2841         size_t nrows = tabular.rowCount();
2842         row_type r = 0;
2843         for (; r < nrows && y > h; ++r) {
2844                 h += tabular.rowAscent(r);
2845                 h += tabular.rowDescent(r);
2846                 h += tabular.getAdditionalHeight(r);
2847         }
2848         return r - 1;
2849 }
2850
2851
2852 int InsetTabular::columnFromX(Cursor & cur, int x) const
2853 {
2854         // left x coordinate of tabular
2855         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
2856         size_t ncols = tabular.columnCount();
2857         col_type c = 0;
2858         for (; c < ncols && x > w; ++c)
2859                 w += tabular.columnWidth(c);
2860         return c - 1;
2861 }
2862
2863
2864 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2865 {
2866         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2867         //      mi.base.textwidth << "\n";
2868         if (!mi.base.bv) {
2869                 LYXERR0("need bv");
2870                 LASSERT(false, /**/);
2871         }
2872
2873         row_type i = 0;
2874         for (idx_type cell = 0; i < tabular.rowCount(); ++i) {
2875                 int maxAsc = 0;
2876                 int maxDesc = 0;
2877                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
2878                         if (tabular.isPartOfMultiColumn(i, j))
2879                                 // Multicolumn cell, but not first one
2880                                 continue;
2881                         Dimension dim;
2882                         MetricsInfo m = mi;
2883                         Length p_width;
2884                         if (tabular.cell_info[i][j].multicolumn ==
2885                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2886                                 p_width = tabular.cellInfo(cell).p_width;
2887                         else
2888                                 p_width = tabular.column_info[j].p_width;
2889                         if (!p_width.zero())
2890                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2891                         tabular.cellInset(cell)->metrics(m, dim);
2892                         if (!p_width.zero())
2893                                 dim.wid = m.base.textwidth;
2894                         tabular.setCellWidth(cell, dim.wid);
2895                         maxAsc  = max(maxAsc, dim.asc);
2896                         maxDesc = max(maxDesc, dim.des);
2897                         ++cell;
2898                 }
2899                 int const top_space = tabular.row_info[i].top_space_default ?
2900                         default_line_space :
2901                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2902                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2903                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2904                         default_line_space :
2905                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2906                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2907         }
2908         tabular.updateColumnWidths();
2909         dim.asc = tabular.rowAscent(0);
2910         dim.des = tabular.height() - dim.asc;
2911         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
2912 }
2913
2914
2915 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
2916 {
2917         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
2918         BufferView * bv = pi.base.bv;
2919
2920         // FIXME: As the full backrgound is painted in drawSelection(),
2921         // we have no choice but to do a full repaint for the Text cells.
2922         pi.full_repaint = true;
2923
2924         resetPos(bv->cursor());
2925
2926         x += scx_;
2927         x += ADD_TO_TABULAR_WIDTH;
2928
2929         bool const original_drawing_state = pi.pain.isDrawingEnabled();
2930
2931         idx_type idx = 0;
2932         first_visible_cell = Tabular::npos;
2933         for (row_type i = 0; i < tabular.rowCount(); ++i) {
2934                 int nx = x;
2935                 int const a = tabular.rowAscent(i);
2936                 int const d = tabular.rowDescent(i);
2937                 idx = tabular.cellIndex(i, 0);
2938                 for (col_type j = 0; j < tabular.columnCount(); ++j) {
2939                         if (tabular.isPartOfMultiColumn(i, j))
2940                                 continue;
2941                         if (first_visible_cell == Tabular::npos)
2942                                 first_visible_cell = idx;
2943
2944                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
2945                         // Cache the Inset position.
2946                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
2947                         if (nx + tabular.columnWidth(idx) < 0
2948                             || nx > bv->workWidth()
2949                             || y + d < 0
2950                             || y - a > bv->workHeight()) {
2951                                 pi.pain.setDrawingEnabled(false);
2952                                 cell(idx)->draw(pi, cx, y);
2953                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2954                                 pi.pain.setDrawingEnabled(original_drawing_state);
2955                         } else {
2956                                 cell(idx)->draw(pi, cx, y);
2957                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2958                         }
2959                         nx += tabular.columnWidth(idx);
2960                         ++idx;
2961                 }
2962
2963                 if (i + 1 < tabular.rowCount())
2964                         y += d + tabular.rowAscent(i + 1) +
2965                                 tabular.getAdditionalHeight(i + 1);
2966         }
2967 }
2968
2969
2970 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
2971 {
2972         Cursor & cur = pi.base.bv->cursor();
2973
2974         x += scx_ + ADD_TO_TABULAR_WIDTH;
2975
2976         // FIXME: it is wrong to completely paint the background
2977         // if we want to do single row painting.
2978
2979         // Paint background of current tabular
2980         int const w = tabular.width();
2981         int const h = tabular.height();
2982         int yy = y - tabular.rowAscent(0);
2983         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
2984
2985         if (!cur.selection())
2986                 return;
2987         if (&cur.inset() != this)
2988                 return;
2989
2990         //resetPos(cur);
2991
2992
2993         if (tablemode(cur)) {
2994                 row_type rs, re;
2995                 col_type cs, ce;
2996                 getSelection(cur, rs, re, cs, ce);
2997                 y -= tabular.rowAscent(0);
2998                 for (row_type j = 0; j < tabular.rowCount(); ++j) {
2999                         int const a = tabular.rowAscent(j);
3000                         int const h = a + tabular.rowDescent(j);
3001                         int xx = x;
3002                         y += tabular.getAdditionalHeight(j);
3003                         for (col_type i = 0; i < tabular.columnCount(); ++i) {
3004                                 if (tabular.isPartOfMultiColumn(j, i))
3005                                         continue;
3006                                 idx_type const cell =
3007                                         tabular.cellIndex(j, i);
3008                                 int const w = tabular.columnWidth(cell);
3009                                 if (i >= cs && i <= ce && j >= rs && j <= re)
3010                                         pi.pain.fillRectangle(xx, y, w, h,
3011                                                               Color_selection);
3012                                 xx += w;
3013                         }
3014                         y += h;
3015                 }
3016
3017         } else {
3018                 x += cellXPos(cur.idx());
3019                 x += tabular.getBeginningOfTextInCell(cur.idx());
3020                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3021         }
3022 }
3023
3024
3025 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3026                                  row_type row, idx_type cell, bool erased) const
3027 {
3028         int x2 = x + tabular.columnWidth(cell);
3029         bool on_off = false;
3030         ColorCode col = Color_tabularline;
3031         ColorCode onoffcol = Color_tabularonoffline;
3032
3033         if (erased) {
3034                 col = Color_deletedtext;
3035                 onoffcol = Color_deletedtext;
3036         }
3037
3038         if (!tabular.topAlreadyDrawn(cell)) {
3039                 on_off = !tabular.topLine(cell);
3040                 pain.line(x, y - tabular.rowAscent(row),
3041                           x2, y -  tabular.rowAscent(row),
3042                           on_off ? onoffcol : col,
3043                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3044         }
3045         on_off = !tabular.bottomLine(cell);
3046         pain.line(x, y + tabular.rowDescent(row),
3047                   x2, y + tabular.rowDescent(row),
3048                   on_off ? onoffcol : col,
3049                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3050         if (!tabular.leftAlreadyDrawn(cell)) {
3051                 on_off = !tabular.leftLine(cell);
3052                 pain.line(x, y -  tabular.rowAscent(row),
3053                           x, y +  tabular.rowDescent(row),
3054                           on_off ? onoffcol : col,
3055                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3056         }
3057         on_off = !tabular.rightLine(cell);
3058         pain.line(x2 - tabular.getAdditionalWidth(cell),
3059                   y -  tabular.rowAscent(row),
3060                   x2 - tabular.getAdditionalWidth(cell),
3061                   y +  tabular.rowDescent(row),
3062                   on_off ? onoffcol : col,
3063                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3064 }
3065
3066
3067 docstring InsetTabular::editMessage() const
3068 {
3069         return _("Opened table");
3070 }
3071
3072
3073 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3074 {
3075         //lyxerr << "InsetTabular::edit: " << this << endl;
3076         cur.finishUndo();
3077         cur.selection() = false;
3078         cur.push(*this);
3079         if (front) {
3080                 if (isRightToLeft(cur))
3081                         cur.idx() = tabular.getLastCellInRow(0);
3082                 else
3083                         cur.idx() = 0;
3084                 cur.pit() = 0;
3085                 cur.pos() = 0;
3086         } else {
3087                 if (isRightToLeft(cur))
3088                         cur.idx() = tabular.getFirstCellInRow(tabular.rowCount() - 1);
3089                 else
3090                         cur.idx() = tabular.cellCount() - 1;
3091                 cur.pit() = 0;
3092                 cur.pos() = cur.lastpos(); // FIXME crude guess
3093         }
3094         // FIXME: this accesses the position cache before it is initialized
3095         //resetPos(cur);
3096         //cur.bv().fitCursor();
3097 }
3098
3099
3100 void InsetTabular::updateLabels(ParIterator const & it)
3101 {
3102         // In a longtable, tell captions what the current float is
3103         Counters & cnts = buffer().params().documentClass().counters();
3104         string const saveflt = cnts.current_float();
3105         if (tabular.isLongTabular())
3106                 cnts.current_float("table");
3107
3108         ParIterator it2 = it;
3109         it2.forwardPos();
3110         size_t const end = it2.nargs();
3111         for ( ; it2.idx() < end; it2.top().forwardIdx())
3112                 lyx::updateLabels(buffer(), it2);
3113
3114         //reset afterwards
3115         if (tabular.isLongTabular())
3116                 cnts.current_float(saveflt);
3117 }
3118
3119
3120 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3121 {
3122         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3123                              << "\n  cur:" << cur);
3124         CursorSlice sl = cur.top();
3125         Cursor & bvcur = cur.bv().cursor();
3126
3127         switch (cmd.action) {
3128
3129         case LFUN_MOUSE_PRESS: {
3130                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3131                 // select row
3132                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3133                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3134                         row_type r = rowFromY(cur, cmd.y);
3135                         cur.idx() = tabular.getFirstCellInRow(r);
3136                         cur.pos() = 0;
3137                         cur.resetAnchor();
3138                         cur.idx() = tabular.getLastCellInRow(r);
3139                         cur.pos() = cur.lastpos();
3140                         cur.selection() = true;
3141                         bvcur = cur; 
3142                         rowselect_ = true;
3143                         break;
3144                 }
3145                 // select column
3146                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3147                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3148                         || cmd.y > y0 + tabular.height()) {
3149                         col_type c = columnFromX(cur, cmd.x);
3150                         cur.idx() = tabular.cellIndex(0, c);
3151                         cur.pos() = 0;
3152                         cur.resetAnchor();
3153                         cur.idx() = tabular.cellIndex(tabular.rowCount() - 1, c);
3154                         cur.pos() = cur.lastpos();
3155                         cur.selection() = true;
3156                         bvcur = cur; 
3157                         colselect_ = true;
3158                         break;
3159                 }
3160                 // do not reset cursor/selection if we have selected
3161                 // some cells (bug 2715).
3162                 if (cmd.button() == mouse_button::button3
3163                     && &bvcur.selBegin().inset() == this 
3164                     && tablemode(bvcur)) 
3165                         ;
3166                 else
3167                         // Let InsetTableCell do it
3168                         cell(cur.idx())->dispatch(cur, cmd);
3169                 break;
3170         }
3171         case LFUN_MOUSE_MOTION:
3172                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3173                 if (cmd.button() == mouse_button::button1) {
3174                         // only accept motions to places not deeper nested than the real anchor
3175                         if (!bvcur.anchor_.hasPart(cur)) {
3176                                 cur.undispatched();
3177                                 break;
3178                         }
3179                         // select (additional) row
3180                         if (rowselect_) {
3181                                 row_type r = rowFromY(cur, cmd.y);
3182                                 cur.idx() = tabular.getLastCellInRow(r);
3183                                 bvcur.setCursor(cur);
3184                                 bvcur.selection() = true;
3185                                 break;
3186                         }
3187                         // select (additional) column
3188                         if (colselect_) {
3189                                 col_type c = columnFromX(cur, cmd.x);
3190                                 cur.idx() = tabular.cellIndex(tabular.rowCount() - 1, c);
3191                                 bvcur.setCursor(cur);
3192                                 bvcur.selection() = true;
3193                                 break;
3194                         }
3195                         // only update if selection changes
3196                         if (bvcur.idx() == cur.idx() &&
3197                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3198                                 cur.noUpdate();
3199                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3200                         bvcur.setCursor(cur);
3201                         bvcur.selection() = true;
3202                 }
3203                 break;
3204
3205         case LFUN_MOUSE_RELEASE:
3206                 rowselect_ = false;
3207                 colselect_ = false;
3208                 break;
3209
3210         case LFUN_CELL_BACKWARD:
3211                 movePrevCell(cur);
3212                 cur.selection() = false;
3213                 break;
3214
3215         case LFUN_CELL_FORWARD:
3216                 moveNextCell(cur);
3217                 cur.selection() = false;
3218                 break;
3219         case LFUN_CHAR_FORWARD_SELECT:
3220         case LFUN_CHAR_FORWARD:
3221         case LFUN_CHAR_BACKWARD_SELECT:
3222         case LFUN_CHAR_BACKWARD:
3223         case LFUN_CHAR_RIGHT_SELECT:
3224         case LFUN_CHAR_RIGHT:
3225         case LFUN_CHAR_LEFT_SELECT:
3226         case LFUN_CHAR_LEFT: {
3227
3228                 // determine whether we move to next or previous cell, where to enter 
3229                 // the new cell from, and which command to "finish" (i.e., exit the
3230                 // inset) with:
3231                 bool next_cell;
3232                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3233                 FuncCode finish_lfun;
3234
3235                 if (cmd.action == LFUN_CHAR_FORWARD 
3236                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3237                         next_cell = true;
3238                         finish_lfun = LFUN_FINISHED_FORWARD;
3239                 }
3240                 else if (cmd.action == LFUN_CHAR_BACKWARD
3241                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3242                         next_cell = false;
3243                         finish_lfun = LFUN_FINISHED_BACKWARD;
3244                 }
3245                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3246                 // table's direction.
3247                 else {
3248                         bool right = (cmd.action == LFUN_CHAR_RIGHT
3249                                                         || cmd.action == LFUN_CHAR_RIGHT_SELECT);
3250                         next_cell = (isRightToLeft(cur) != right);
3251                         
3252                         if (lyxrc.visual_cursor) {
3253                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3254                         }
3255
3256                         if (right)
3257                                 finish_lfun = LFUN_FINISHED_RIGHT;
3258                         else
3259                                 finish_lfun = LFUN_FINISHED_LEFT;
3260                 }
3261                 
3262
3263                 // finally, now that we know what we want to do, do it!
3264                 cell(cur.idx())->dispatch(cur, cmd);
3265                 if (!cur.result().dispatched()) {
3266                         // move to next/prev cell, as appropriate
3267                         LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3268                                 << " cell from: " << int(entry_from));
3269                         if (next_cell)
3270                                 moveNextCell(cur, entry_from);
3271                         else
3272                                 movePrevCell(cur, entry_from);
3273                         // if we're exiting the table, call the appropriate FINISHED lfun
3274                         if (sl == cur.top())
3275                                 cmd = FuncRequest(finish_lfun);
3276                         else
3277                                 cur.dispatched();
3278                 }
3279                 break;
3280
3281         }
3282
3283         case LFUN_DOWN_SELECT:
3284         case LFUN_DOWN:
3285                 cell(cur.idx())->dispatch(cur, cmd);
3286                 cur.dispatched(); // override the cell's decision
3287                 if (sl == cur.top())
3288                         // if our Text didn't do anything to the cursor
3289                         // then we try to put the cursor into the cell below
3290                         // setting also the right targetX.
3291                         if (tabular.cellRow(cur.idx()) != tabular.rowCount() - 1) {
3292                                 cur.idx() = tabular.cellBelow(cur.idx());
3293                                 cur.pit() = 0;
3294                                 TextMetrics const & tm =
3295                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3296                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3297                         }
3298                 if (sl == cur.top()) {
3299                         // we trick it to go to forward after leaving the
3300                         // tabular.
3301                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3302                         cur.undispatched();
3303                 }
3304                 break;
3305
3306         case LFUN_UP_SELECT:
3307         case LFUN_UP:
3308                 cell(cur.idx())->dispatch(cur, cmd);
3309                 cur.dispatched(); // override the cell's decision
3310                 if (sl == cur.top())
3311                         // if our Text didn't do anything to the cursor
3312                         // then we try to put the cursor into the cell above
3313                         // setting also the right targetX.
3314                         if (tabular.cellRow(cur.idx()) != 0) {
3315                                 cur.idx() = tabular.cellAbove(cur.idx());
3316                                 cur.pit() = cur.lastpit();
3317                                 Text const * text = cell(cur.idx())->getText(0);
3318                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3319                                 ParagraphMetrics const & pm =
3320                                         tm.parMetrics(cur.lastpit());
3321                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3322                         }
3323                 if (sl == cur.top()) {
3324                         cmd = FuncRequest(LFUN_UP);
3325                         cur.undispatched();
3326                 }
3327                 break;
3328
3329 //      case LFUN_SCREEN_DOWN: {
3330 //              //if (hasSelection())
3331 //              //      cur.selection() = false;
3332 //              col_type const col = tabular.cellColumn(cur.idx());
3333 //              int const t =   cur.bv().top_y() + cur.bv().height();
3334 //              if (t < yo() + tabular.getHeightOfTabular()) {
3335 //                      cur.bv().scrollDocView(t);
3336 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3337 //              } else {
3338 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3339 //              }
3340 //              cur.par() = 0;
3341 //              cur.pos() = 0;
3342 //              break;
3343 //      }
3344 //
3345 //      case LFUN_SCREEN_UP: {
3346 //              //if (hasSelection())
3347 //              //      cur.selection() = false;
3348 //              col_type const col = tabular.cellColumn(cur.idx());
3349 //              int const t =   cur.bv().top_y() + cur.bv().height();
3350 //              if (yo() < 0) {
3351 //                      cur.bv().scrollDocView(t);
3352 //                      if (yo() > 0)
3353 //                              cur.idx() = col;
3354 //                      else
3355 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3356 //              } else {
3357 //                      cur.idx() = col;
3358 //              }
3359 //              cur.par() = cur.lastpar();
3360 //              cur.pos() = cur.lastpos();
3361 //              break;
3362 //      }
3363
3364         case LFUN_LAYOUT_TABULAR:
3365                 cur.bv().showDialog("tabular", params2string(*this), this);
3366                 break;
3367
3368         case LFUN_INSET_DIALOG_UPDATE:
3369                 cur.bv().updateDialog("tabular", params2string(*this));
3370                 break;
3371
3372         case LFUN_TABULAR_FEATURE:
3373                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3374                         cur.undispatched();
3375                 break;
3376
3377         // insert file functions
3378         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3379         case LFUN_FILE_INSERT_PLAINTEXT: {
3380                 // FIXME UNICODE
3381                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3382                         FileName(to_utf8(cmd.argument())));
3383                 if (tmpstr.empty())
3384                         break;
3385                 cur.recordUndoInset(INSERT_UNDO);
3386                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3387                         // content has been replaced,
3388                         // so cursor might be invalid
3389                         cur.pos() = cur.lastpos();
3390                         cur.pit() = cur.lastpit();
3391                         bvcur.setCursor(cur);
3392                 } else
3393                         cur.undispatched();
3394                 break;
3395         }
3396
3397         case LFUN_CUT:
3398                 if (tablemode(cur)) {
3399                         if (copySelection(cur)) {
3400                                 cur.recordUndoInset(DELETE_UNDO);
3401                                 cutSelection(cur);
3402                         }
3403                 }
3404                 else
3405                         cell(cur.idx())->dispatch(cur, cmd);
3406                 break;
3407
3408         case LFUN_CHAR_DELETE_BACKWARD:
3409         case LFUN_CHAR_DELETE_FORWARD:
3410                 if (tablemode(cur)) {
3411                         cur.recordUndoInset(DELETE_UNDO);
3412                         cutSelection(cur);
3413                 }
3414                 else
3415                         cell(cur.idx())->dispatch(cur, cmd);
3416                 break;
3417
3418         case LFUN_COPY:
3419                 if (!cur.selection())
3420                         break;
3421                 if (tablemode(cur)) {
3422                         cur.finishUndo();
3423                         copySelection(cur);
3424                 } else
3425                         cell(cur.idx())->dispatch(cur, cmd);
3426                 break;
3427
3428         case LFUN_CLIPBOARD_PASTE:
3429         case LFUN_PRIMARY_SELECTION_PASTE: {
3430                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3431                         theClipboard().getAsText() :
3432                         theSelection().get();
3433                 if (clip.empty())
3434                         break;
3435                 // pass to InsertPlaintextString, but
3436                 // only if we have multi-cell content
3437                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3438                         cur.recordUndoInset(INSERT_UNDO);
3439                         if (insertPlaintextString(cur.bv(), clip, false)) {
3440                                 // content has been replaced,
3441                                 // so cursor might be invalid
3442                                 cur.pos() = cur.lastpos();
3443                                 cur.pit() = cur.lastpit();
3444                                 bvcur.setCursor(cur);
3445                                 break;
3446                         }
3447                 }
3448                 // Let the cell handle normal text
3449                 cell(cur.idx())->dispatch(cur, cmd);
3450                 break;
3451         }
3452
3453         case LFUN_PASTE:
3454                 if (tabularStackDirty() && theClipboard().isInternal() ||
3455                     !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
3456                         cur.recordUndoInset(INSERT_UNDO);
3457                         pasteClipboard(cur);
3458                         break;
3459                 }
3460                 cell(cur.idx())->dispatch(cur, cmd);
3461                 break;
3462
3463         case LFUN_FONT_EMPH:
3464         case LFUN_FONT_BOLD:
3465         case LFUN_FONT_ROMAN:
3466         case LFUN_FONT_NOUN:
3467         case LFUN_FONT_ITAL:
3468         case LFUN_FONT_FRAK:
3469         case LFUN_FONT_TYPEWRITER:
3470         case LFUN_FONT_SANS:
3471         case LFUN_FONT_FREE_APPLY:
3472         case LFUN_FONT_FREE_UPDATE:
3473         case LFUN_FONT_SIZE:
3474         case LFUN_FONT_UNDERLINE:
3475         case LFUN_LANGUAGE:
3476         case LFUN_WORD_CAPITALIZE:
3477         case LFUN_WORD_UPCASE:
3478         case LFUN_WORD_LOWCASE:
3479         case LFUN_CHARS_TRANSPOSE:
3480                 if (tablemode(cur)) {
3481                         row_type rs, re;
3482                         col_type cs, ce;
3483                         getSelection(cur, rs, re, cs, ce);
3484                         Cursor tmpcur = cur;
3485                         for (row_type i = rs; i <= re; ++i) {
3486                                 for (col_type j = cs; j <= ce; ++j) {
3487                                         // cursor follows cell:
3488                                         tmpcur.idx() = tabular.cellIndex(i, j);
3489                                         // select this cell only:
3490                                         tmpcur.pit() = 0;
3491                                         tmpcur.pos() = 0;
3492                                         tmpcur.resetAnchor();
3493                                         tmpcur.pit() = tmpcur.lastpit();
3494                                         tmpcur.pos() = tmpcur.top().lastpos();
3495                                         tmpcur.setCursor(tmpcur);
3496                                         tmpcur.setSelection();
3497                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3498                                 }
3499                         }
3500                         break;
3501                 } else {
3502                         cell(cur.idx())->dispatch(cur, cmd);
3503                         break;
3504                 }
3505         default:
3506                 // we try to handle this event in the insets dispatch function.
3507                 cell(cur.idx())->dispatch(cur, cmd);
3508                 break;
3509         }
3510 }
3511
3512
3513 // function sets an object as defined in func_status.h:
3514 // states OK, Unknown, Disabled, On, Off.
3515 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3516         FuncStatus & status) const
3517 {
3518         switch (cmd.action) {
3519         case LFUN_TABULAR_FEATURE: {
3520                 int action = Tabular::LAST_ACTION;
3521                 int i = 0;
3522                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3523                         string const tmp = tabularFeature[i].feature;
3524                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3525                                 action = tabularFeature[i].action;
3526                                 break;
3527                         }
3528                 }
3529                 if (action == Tabular::LAST_ACTION) {
3530                         status.clear();
3531                         status.unknown(true);
3532                         return true;
3533                 }
3534
3535                 string const argument
3536                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3537
3538                 row_type sel_row_start = 0;
3539                 row_type sel_row_end = 0;
3540                 col_type sel_col_start = 0;
3541                 col_type sel_col_end = 0;
3542                 Tabular::ltType dummyltt;
3543                 bool flag = true;
3544
3545                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3546
3547                 switch (action) {
3548                 case Tabular::SET_PWIDTH:
3549                 case Tabular::SET_MPWIDTH:
3550                 case Tabular::SET_SPECIAL_COLUMN:
3551                 case Tabular::SET_SPECIAL_MULTI:
3552                 case Tabular::APPEND_ROW:
3553                 case Tabular::APPEND_COLUMN:
3554                 case Tabular::DELETE_ROW:
3555                 case Tabular::DELETE_COLUMN:
3556                 case Tabular::COPY_ROW:
3557                 case Tabular::COPY_COLUMN:
3558                 case Tabular::SET_ALL_LINES:
3559                 case Tabular::UNSET_ALL_LINES:
3560                 case Tabular::SET_TOP_SPACE:
3561                 case Tabular::SET_BOTTOM_SPACE:
3562                 case Tabular::SET_INTERLINE_SPACE:
3563                 case Tabular::SET_BORDER_LINES:
3564                         status.clear();
3565                         return true;
3566
3567                 case Tabular::MULTICOLUMN:
3568                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3569                         break;
3570
3571                 case Tabular::TOGGLE_LINE_TOP:
3572                         status.setOnOff(tabular.topLine(cur.idx()));
3573                         break;
3574
3575                 case Tabular::TOGGLE_LINE_BOTTOM:
3576                         status.setOnOff(tabular.bottomLine(cur.idx()));
3577                         break;
3578
3579                 case Tabular::TOGGLE_LINE_LEFT:
3580                         status.setOnOff(tabular.leftLine(cur.idx()));
3581                         break;
3582
3583                 case Tabular::TOGGLE_LINE_RIGHT:
3584                         status.setOnOff(tabular.rightLine(cur.idx()));
3585                         break;
3586
3587                 case Tabular::M_ALIGN_LEFT:
3588                         flag = false;
3589                 case Tabular::ALIGN_LEFT:
3590                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3591                         break;
3592
3593                 case Tabular::M_ALIGN_RIGHT:
3594                         flag = false;
3595                 case Tabular::ALIGN_RIGHT:
3596                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3597                         break;
3598
3599                 case Tabular::M_ALIGN_CENTER:
3600                         flag = false;
3601                 case Tabular::ALIGN_CENTER:
3602                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3603                         break;
3604
3605                 case Tabular::ALIGN_BLOCK:
3606                         status.enabled(!tabular.getPWidth(cur.idx()).zero());
3607                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3608                         break;
3609
3610                 case Tabular::M_VALIGN_TOP:
3611                         flag = false;
3612                 case Tabular::VALIGN_TOP:
3613                         status.setOnOff(
3614                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3615                         break;
3616
3617                 case Tabular::M_VALIGN_BOTTOM:
3618                         flag = false;
3619                 case Tabular::VALIGN_BOTTOM:
3620                         status.setOnOff(
3621                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3622                         break;
3623
3624                 case Tabular::M_VALIGN_MIDDLE:
3625                         flag = false;
3626                 case Tabular::VALIGN_MIDDLE:
3627                         status.setOnOff(
3628                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3629                         break;
3630
3631                 case Tabular::SET_LONGTABULAR:
3632                         status.setOnOff(tabular.isLongTabular());
3633                         break;
3634
3635                 case Tabular::UNSET_LONGTABULAR:
3636                         status.setOnOff(!tabular.isLongTabular());
3637                         break;
3638
3639                 case Tabular::TOGGLE_ROTATE_TABULAR:
3640                 case Tabular::SET_ROTATE_TABULAR:
3641                         status.setOnOff(tabular.getRotateTabular());
3642                         break;
3643
3644                 case Tabular::UNSET_ROTATE_TABULAR:
3645                         status.setOnOff(!tabular.getRotateTabular());
3646                         break;
3647
3648                 case Tabular::TOGGLE_ROTATE_CELL:
3649                 case Tabular::SET_ROTATE_CELL:
3650                         status.setOnOff(!oneCellHasRotationState(false,
3651                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3652                         break;
3653
3654                 case Tabular::UNSET_ROTATE_CELL:
3655                         status.setOnOff(!oneCellHasRotationState(true,
3656                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3657                         break;
3658
3659                 case Tabular::SET_USEBOX:
3660                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3661                         break;
3662
3663                 case Tabular::SET_LTFIRSTHEAD:
3664                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3665                         break;
3666
3667                 case Tabular::UNSET_LTFIRSTHEAD:
3668                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3669                         break;
3670
3671                 case Tabular::SET_LTHEAD:
3672                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3673                         break;
3674
3675                 case Tabular::UNSET_LTHEAD:
3676                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3677                         break;
3678
3679                 case Tabular::SET_LTFOOT:
3680                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3681                         break;
3682
3683                 case Tabular::UNSET_LTFOOT:
3684                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3685                         break;
3686
3687                 case Tabular::SET_LTLASTFOOT:
3688                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3689                         break;
3690
3691                 case Tabular::UNSET_LTLASTFOOT:
3692                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3693                         break;
3694
3695                 case Tabular::SET_LTNEWPAGE:
3696                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3697                         break;
3698
3699                 case Tabular::SET_BOOKTABS:
3700                         status.setOnOff(tabular.useBookTabs());
3701                         break;
3702
3703                 case Tabular::UNSET_BOOKTABS:
3704                         status.setOnOff(!tabular.useBookTabs());
3705                         break;
3706
3707                 default:
3708                         status.clear();
3709                         status.enabled(false);
3710                         break;
3711                 }
3712                 return true;
3713         }
3714
3715         // These are only enabled inside tabular
3716         case LFUN_CELL_BACKWARD:
3717         case LFUN_CELL_FORWARD:
3718                 status.enabled(true);
3719                 return true;
3720
3721         // disable these with multiple cells selected
3722         case LFUN_INSET_INSERT:
3723         case LFUN_TABULAR_INSERT:
3724         case LFUN_FLEX_INSERT:
3725         case LFUN_FLOAT_INSERT:
3726         case LFUN_FLOAT_WIDE_INSERT:
3727         case LFUN_FOOTNOTE_INSERT:
3728         case LFUN_MARGINALNOTE_INSERT:
3729         case LFUN_MATH_INSERT:
3730         case LFUN_MATH_MODE:
3731         case LFUN_MATH_MUTATE:
3732         case LFUN_MATH_DISPLAY:
3733         case LFUN_NOTE_INSERT:
3734         case LFUN_OPTIONAL_INSERT:
3735         case LFUN_BOX_INSERT:
3736         case LFUN_BRANCH_INSERT:
3737         case LFUN_WRAP_INSERT:
3738         case LFUN_ERT_INSERT: {
3739                 if (tablemode(cur)) {
3740                         status.enabled(false);
3741                         return true;
3742                 } else
3743                         return cell(cur.idx())->getStatus(cur, cmd, status);
3744         }
3745
3746         // disable in non-fixed-width cells
3747         case LFUN_NEWLINE_INSERT:
3748         case LFUN_BREAK_PARAGRAPH:
3749         case LFUN_BREAK_PARAGRAPH_SKIP: {
3750                 if (tabular.getPWidth(cur.idx()).zero()) {
3751                         status.enabled(false);
3752                         return true;
3753                 } else
3754                         return cell(cur.idx())->getStatus(cur, cmd, status);
3755         }
3756
3757         case LFUN_PASTE:
3758                 if (tabularStackDirty() && theClipboard().isInternal()) {
3759                         status.enabled(true);
3760                         return true;
3761                 } else
3762                         return cell(cur.idx())->getStatus(cur, cmd, status);
3763
3764         case LFUN_INSET_MODIFY:
3765                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3766                         status.enabled(true);
3767                         return true;
3768                 }
3769                 // Fall through
3770
3771         default:
3772                 // we try to handle this event in the insets dispatch function.
3773                 return cell(cur.idx())->getStatus(cur, cmd, status);
3774         }
3775 }
3776
3777
3778 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
3779 {
3780         return tabular.latex(os, runparams);
3781 }
3782
3783
3784 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
3785 {
3786         os << '\n'; // output table on a new line
3787         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3788         tabular.plaintext(os, runparams, dp, false, 0);
3789         return PLAINTEXT_NEWLINE;
3790 }
3791
3792
3793 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
3794 {
3795         int ret = 0;
3796         Inset * master = 0;
3797
3798         // FIXME: Why not pass a proper DocIterator here?
3799 #if 0
3800         // if the table is inside a float it doesn't need the informaltable
3801         // wrapper. Search for it.
3802         for (master = owner(); master; master = master->owner())
3803                 if (master->lyxCode() == FLOAT_CODE)
3804                         break;
3805 #endif
3806
3807         if (!master) {
3808                 os << "<informaltable>";
3809                 ++ret;
3810         }
3811         ret += tabular.docbook(os, runparams);
3812         if (!master) {
3813                 os << "</informaltable>";
3814                 ++ret;
3815         }
3816         return ret;
3817 }
3818
3819
3820 void InsetTabular::validate(LaTeXFeatures & features) const
3821 {
3822         tabular.validate(features);
3823 }
3824
3825
3826 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
3827 {
3828         return tabular.cellInset(idx);
3829 }
3830
3831
3832 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
3833 {
3834         return tabular.cellInset(idx);
3835 }
3836
3837
3838 void InsetTabular::cursorPos(BufferView const & bv,
3839                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3840 {
3841         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3842
3843         // y offset     correction
3844         int const row = tabular.cellRow(sl.idx());
3845         for (int i = 0; i <= row; ++i) {
3846                 if (i != 0) {
3847                         y += tabular.rowAscent(i);
3848                         y += tabular.getAdditionalHeight(i);
3849                 }
3850                 if (i != row)
3851                         y += tabular.rowDescent(i);
3852         }
3853
3854         // x offset correction
3855         int const col = tabular.cellColumn(sl.idx());
3856         int idx = tabular.cellIndex(row, 0);
3857         for (int j = 0; j < col; ++j) {
3858                 if (tabular.isPartOfMultiColumn(row, j))
3859                         continue;
3860                 x += tabular.columnWidth(idx);
3861                 ++idx;
3862         }
3863         x += tabular.getBeginningOfTextInCell(idx);
3864         x += ADD_TO_TABULAR_WIDTH;
3865         x += scx_;
3866 }
3867
3868
3869 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3870 {
3871         int xx = 0;
3872         int yy = 0;
3873         Inset const & inset = *tabular.cellInset(cell);
3874         Point o = bv.coordCache().getInsets().xy(&inset);
3875         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3876         int const xend = xbeg + tabular.columnWidth(cell);
3877         row_type const row = tabular.cellRow(cell);
3878         int const ybeg = o.y_ - tabular.rowAscent(row) -
3879                          tabular.getAdditionalHeight(row);
3880         int const yend = o.y_ + tabular.rowDescent(row);
3881
3882         if (x < xbeg)
3883                 xx = xbeg - x;
3884         else if (x > xend)
3885                 xx = x - xend;
3886
3887         if (y < ybeg)
3888                 yy = ybeg - y;
3889         else if (y > yend)
3890                 yy = y - yend;
3891
3892         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3893         //       << " ybeg=" << ybeg << " yend=" << yend
3894         //       << " xx=" << xx << " yy=" << yy
3895         //       << " dist=" << xx + yy << endl;
3896         return xx + yy;
3897 }
3898
3899
3900 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3901 {
3902         //lyxerr << "InsetTabular::editXY: " << this << endl;
3903         cur.selection() = false;
3904         cur.push(*this);
3905         cur.idx() = getNearestCell(cur.bv(), x, y);
3906         resetPos(cur);
3907         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3908 }
3909
3910
3911 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3912 {
3913         cur.idx() = getNearestCell(cur.bv(), x, y);
3914         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3915 }
3916
3917
3918 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3919 {
3920         idx_type idx_min = 0;
3921         int dist_min = numeric_limits<int>::max();
3922         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3923                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
3924                         int const d = dist(bv, i, x, y);
3925                         if (d < dist_min) {
3926                                 dist_min = d;
3927                                 idx_min = i;
3928                         }
3929                 }
3930         }
3931         return idx_min;
3932 }
3933
3934
3935 int InsetTabular::cellXPos(idx_type const cell) const
3936 {
3937         idx_type c = cell;
3938
3939         for (; !tabular.isFirstCellInRow(c); --c)
3940                 ;
3941         int lx = 0;
3942         for (; c < cell; ++c)
3943                 lx += tabular.columnWidth(c);
3944
3945         return lx;
3946 }
3947
3948
3949 void InsetTabular::resetPos(Cursor & cur) const
3950 {
3951         BufferView & bv = cur.bv();
3952         int const maxwidth = bv.workWidth();
3953
3954         if (&cur.inset() != this) {
3955                 scx_ = 0;
3956         } else {
3957                 int const X1 = 0;
3958                 int const X2 = maxwidth;
3959                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3960                 int const x1 = xo(cur.bv()) + cellXPos(cur.idx()) + offset;
3961                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3962
3963                 if (x1 < X1)
3964                         scx_ = X1 + 20 - x1;
3965                 else if (x2 > X2)
3966                         scx_ = X2 - 20 - x2;
3967                 else
3968                         scx_ = 0;
3969         }
3970
3971         cur.updateFlags(Update::Force | Update::FitCursor);
3972 }
3973
3974
3975 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
3976 {
3977         if (isRightToLeft(cur)) {
3978                 if (tabular.isFirstCellInRow(cur.idx())) {
3979                         row_type const row = tabular.cellRow(cur.idx());
3980                         if (row == tabular.rowCount() - 1)
3981                                 return;
3982                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
3983                 } else {
3984                         if (cur.idx() == 0)
3985                                 return;
3986                         --cur.idx();
3987                 }
3988         } else {
3989                 if (tabular.isLastCell(cur.idx()))
3990                         return;
3991                 ++cur.idx();
3992         }
3993         cur.pit() = 0;
3994         cur.pos() = 0;
3995         cur.boundary(false);
3996
3997         // in visual mode, place cursor at extreme left or right
3998         
3999         switch(entry_from) {
4000
4001         case ENTRY_DIRECTION_RIGHT:
4002                 cur.posVisToRowExtremity(false /* !left */);
4003                 break;
4004         case ENTRY_DIRECTION_LEFT:
4005                 cur.posVisToRowExtremity(true /* left */);
4006                 break;
4007         case ENTRY_DIRECTION_IGNORE:
4008                 // nothing to do in this case
4009                 break;
4010
4011         }
4012
4013         resetPos(cur);
4014 }
4015
4016
4017 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4018 {
4019         if (isRightToLeft(cur)) {
4020                 if (tabular.isLastCellInRow(cur.idx())) {
4021                         row_type const row = tabular.cellRow(cur.idx());
4022                         if (row == 0)
4023                                 return;
4024                         cur.idx() = tabular.getFirstCellInRow(row);
4025                         cur.idx() = tabular.cellAbove(cur.idx());
4026                 } else {
4027                         if (tabular.isLastCell(cur.idx()))
4028                                 return;
4029                         ++cur.idx();
4030                 }
4031         } else {
4032                 if (cur.idx() == 0) // first cell
4033                         return;
4034                 --cur.idx();
4035         }
4036         cur.pit() = cur.lastpit();
4037         cur.pos() = cur.lastpos();
4038
4039         // in visual mode, place cursor at extreme left or right
4040         
4041         switch(entry_from) {
4042
4043         case ENTRY_DIRECTION_RIGHT:
4044                 cur.posVisToRowExtremity(false /* !left */);
4045                 break;
4046         case ENTRY_DIRECTION_LEFT:
4047                 cur.posVisToRowExtremity(true /* left */);
4048                 break;
4049         case ENTRY_DIRECTION_IGNORE:
4050                 // nothing to do in this case
4051                 break;
4052
4053         }
4054
4055         // FIXME: this accesses the position cache before it is initialized
4056         //resetPos(cur);
4057 }
4058
4059
4060 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4061 {
4062         Tabular::Feature action = Tabular::LAST_ACTION;
4063
4064         int i = 0;
4065         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4066                 string const tmp = tabularFeature[i].feature;
4067
4068                 if (tmp == what.substr(0, tmp.length())) {
4069                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4070                         //tabularFeatures[i].feature.length()))
4071                         action = tabularFeature[i].action;
4072                         break;
4073                 }
4074         }
4075         if (action == Tabular::LAST_ACTION)
4076                 return false;
4077
4078         string const val =
4079                 ltrim(what.substr(tabularFeature[i].feature.length()));
4080         tabularFeatures(cur, action, val);
4081         return true;
4082 }
4083
4084
4085 static void checkLongtableSpecial(Tabular::ltType & ltt,
4086                           string const & special, bool & flag)
4087 {
4088         if (special == "dl_above") {
4089                 ltt.topDL = flag;
4090                 ltt.set = false;
4091         } else if (special == "dl_below") {
4092                 ltt.bottomDL = flag;
4093                 ltt.set = false;
4094         } else if (special == "empty") {
4095                 ltt.empty = flag;
4096                 ltt.set = false;
4097         } else if (flag) {
4098                 ltt.empty = false;
4099                 ltt.set = true;
4100         }
4101 }
4102
4103 bool InsetTabular::oneCellHasRotationState(bool rotated,
4104                 row_type row_start, row_type row_end,
4105                 col_type col_start, col_type col_end) const {
4106
4107         for (row_type i = row_start; i <= row_end; ++i) {
4108                 for (col_type j = col_start; j <= col_end; ++j) {
4109                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4110                                 == rotated) {
4111                                 return true;
4112                         }
4113                 }
4114         }
4115         return false;
4116 }
4117
4118 void InsetTabular::tabularFeatures(Cursor & cur,
4119         Tabular::Feature feature, string const & value)
4120 {
4121         col_type sel_col_start;
4122         col_type sel_col_end;
4123         row_type sel_row_start;
4124         row_type sel_row_end;
4125         bool setLines = false;
4126         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4127         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4128
4129         switch (feature) {
4130
4131         case Tabular::M_ALIGN_LEFT:
4132         case Tabular::ALIGN_LEFT:
4133                 setAlign = LYX_ALIGN_LEFT;
4134                 break;
4135
4136         case Tabular::M_ALIGN_RIGHT:
4137         case Tabular::ALIGN_RIGHT:
4138                 setAlign = LYX_ALIGN_RIGHT;
4139                 break;
4140
4141         case Tabular::M_ALIGN_CENTER:
4142         case Tabular::ALIGN_CENTER:
4143                 setAlign = LYX_ALIGN_CENTER;
4144                 break;
4145
4146         case Tabular::ALIGN_BLOCK:
4147                 setAlign = LYX_ALIGN_BLOCK;
4148                 break;
4149
4150         case Tabular::M_VALIGN_TOP:
4151         case Tabular::VALIGN_TOP:
4152                 setVAlign = Tabular::LYX_VALIGN_TOP;
4153                 break;
4154
4155         case Tabular::M_VALIGN_BOTTOM:
4156         case Tabular::VALIGN_BOTTOM:
4157                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4158                 break;
4159
4160         case Tabular::M_VALIGN_MIDDLE:
4161         case Tabular::VALIGN_MIDDLE:
4162                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4163                 break;
4164
4165         default:
4166                 break;
4167         }
4168
4169         cur.recordUndoInset(ATOMIC_UNDO);
4170
4171         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4172         row_type const row = tabular.cellRow(cur.idx());
4173         col_type const column = tabular.cellColumn(cur.idx());
4174         bool flag = true;
4175         Tabular::ltType ltt;
4176
4177         switch (feature) {
4178
4179         case Tabular::SET_PWIDTH: {
4180                 Length const len(value);
4181                 tabular.setColumnPWidth(cur, cur.idx(), len);
4182                 if (len.zero()
4183                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4184                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4185                 break;
4186         }
4187
4188         case Tabular::SET_MPWIDTH:
4189                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4190                 break;
4191
4192         case Tabular::SET_SPECIAL_COLUMN:
4193         case Tabular::SET_SPECIAL_MULTI:
4194                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4195                 break;
4196
4197         case Tabular::APPEND_ROW:
4198                 // append the row into the tabular
4199                 tabular.appendRow(cur.idx());
4200                 break;
4201
4202         case Tabular::APPEND_COLUMN:
4203                 // append the column into the tabular
4204                 tabular.appendColumn(cur.idx());
4205                 cur.idx() = tabular.cellIndex(row, column);
4206                 break;
4207
4208         case Tabular::DELETE_ROW:
4209                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4210                         tabular.deleteRow(sel_row_start);
4211                 if (sel_row_start >= tabular.rowCount())
4212                         --sel_row_start;
4213                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4214                 cur.pit() = 0;
4215                 cur.pos() = 0;
4216                 cur.selection() = false;
4217                 break;
4218
4219         case Tabular::DELETE_COLUMN:
4220                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4221                         tabular.deleteColumn(sel_col_start);
4222                 if (sel_col_start >= tabular.columnCount())
4223                         --sel_col_start;
4224                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4225                 cur.pit() = 0;
4226                 cur.pos() = 0;
4227                 cur.selection() = false;
4228                 break;
4229
4230         case Tabular::COPY_ROW:
4231                 tabular.copyRow(row);
4232                 break;
4233
4234         case Tabular::COPY_COLUMN:
4235                 tabular.copyColumn(column);
4236                 cur.idx() = tabular.cellIndex(row, column);
4237                 break;
4238
4239         case Tabular::TOGGLE_LINE_TOP: {
4240                 bool lineSet = !tabular.topLine(cur.idx());
4241                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4242                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4243                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4244                 break;
4245         }
4246
4247         case Tabular::TOGGLE_LINE_BOTTOM: {
4248                 bool lineSet = !tabular.bottomLine(cur.idx());
4249                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4250                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4251                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4252                 break;
4253         }
4254
4255         case Tabular::TOGGLE_LINE_LEFT: {
4256                 bool lineSet = !tabular.leftLine(cur.idx());
4257                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4258                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4259                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4260                 break;
4261         }
4262
4263         case Tabular::TOGGLE_LINE_RIGHT: {
4264                 bool lineSet = !tabular.rightLine(cur.idx());
4265                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4266                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4267                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4268                 break;
4269         }
4270
4271         case Tabular::M_ALIGN_LEFT:
4272         case Tabular::M_ALIGN_RIGHT:
4273         case Tabular::M_ALIGN_CENTER:
4274                 flag = false;
4275         case Tabular::ALIGN_LEFT:
4276         case Tabular::ALIGN_RIGHT:
4277         case Tabular::ALIGN_CENTER:
4278         case Tabular::ALIGN_BLOCK:
4279                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4280                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4281                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4282                 break;
4283
4284         case Tabular::M_VALIGN_TOP:
4285         case Tabular::M_VALIGN_BOTTOM:
4286         case Tabular::M_VALIGN_MIDDLE:
4287                 flag = false;
4288         case Tabular::VALIGN_TOP:
4289         case Tabular::VALIGN_BOTTOM:
4290         case Tabular::VALIGN_MIDDLE:
4291                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4292                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4293                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4294                 break;
4295
4296         case Tabular::MULTICOLUMN: {
4297                 if (sel_row_start != sel_row_end) {
4298                         // FIXME: Need I say it ? This is horrible.
4299                         // FIXME UNICODE
4300                         Alert::error(_("Error setting multicolumn"),
4301                                      _("You cannot set multicolumn vertically."));
4302                         return;
4303                 }
4304                 if (!cur.selection()) {
4305                         // just multicol for one single cell
4306                         // check whether we are completely in a multicol
4307                         if (tabular.isMultiColumn(cur.idx()))
4308                                 tabular.unsetMultiColumn(cur.idx());
4309                         else
4310                                 tabular.setMultiColumn(cur.idx(), 1);
4311                         break;
4312                 }
4313                 // we have a selection so this means we just add all this
4314                 // cells to form a multicolumn cell
4315                 idx_type const s_start = cur.selBegin().idx();
4316                 idx_type const s_end = cur.selEnd().idx();
4317                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4318                 cur.idx() = s_start;
4319                 cur.pit() = 0;
4320                 cur.pos() = 0;
4321                 cur.selection() = false;
4322                 break;
4323         }
4324
4325         case Tabular::SET_ALL_LINES:
4326                 setLines = true;
4327         case Tabular::UNSET_ALL_LINES:
4328                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4329                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4330                                 tabular.setAllLines(
4331                                         tabular.cellIndex(i,j), setLines);
4332                 break;
4333
4334         case Tabular::SET_BORDER_LINES:
4335                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4336                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4337                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4338                 }
4339                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4340                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4341                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4342                 }
4343                 break;
4344
4345         case Tabular::SET_LONGTABULAR:
4346                 tabular.setLongTabular(true);
4347                 break;
4348
4349         case Tabular::UNSET_LONGTABULAR:
4350                 tabular.setLongTabular(false);
4351                 break;
4352
4353         case Tabular::SET_ROTATE_TABULAR:
4354                 tabular.setRotateTabular(true);
4355                 break;
4356
4357         case Tabular::UNSET_ROTATE_TABULAR:
4358                 tabular.setRotateTabular(false);
4359                 break;
4360
4361         case Tabular::TOGGLE_ROTATE_TABULAR:
4362                 tabular.setRotateTabular(!tabular.getRotateTabular());
4363                 break;
4364
4365         case Tabular::SET_ROTATE_CELL:
4366                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4367                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4368                                 tabular.setRotateCell(
4369                                         tabular.cellIndex(i, j), true);
4370                 break;
4371
4372         case Tabular::UNSET_ROTATE_CELL:
4373                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4374                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4375                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4376                 break;
4377
4378         case Tabular::TOGGLE_ROTATE_CELL:
4379                 {
4380                 bool oneNotRotated = oneCellHasRotationState(false,
4381                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4382
4383                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4384                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4385                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4386                                                                           oneNotRotated);
4387                 }
4388                 break;
4389
4390         case Tabular::SET_USEBOX: {
4391                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4392                 if (val == tabular.getUsebox(cur.idx()))
4393                         val = Tabular::BOX_NONE;
4394                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4395                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4396                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4397                 break;
4398         }
4399
4400         case Tabular::UNSET_LTFIRSTHEAD:
4401                 flag = false;
4402         case Tabular::SET_LTFIRSTHEAD:
4403                 tabular.getRowOfLTFirstHead(row, ltt);
4404                 checkLongtableSpecial(ltt, value, flag);
4405                 tabular.setLTHead(row, flag, ltt, true);
4406                 break;
4407
4408         case Tabular::UNSET_LTHEAD:
4409                 flag = false;
4410         case Tabular::SET_LTHEAD:
4411                 tabular.getRowOfLTHead(row, ltt);
4412                 checkLongtableSpecial(ltt, value, flag);
4413                 tabular.setLTHead(row, flag, ltt, false);
4414                 break;
4415
4416         case Tabular::UNSET_LTFOOT:
4417                 flag = false;
4418         case Tabular::SET_LTFOOT:
4419                 tabular.getRowOfLTFoot(row, ltt);
4420                 checkLongtableSpecial(ltt, value, flag);
4421                 tabular.setLTFoot(row, flag, ltt, false);
4422                 break;
4423
4424         case Tabular::UNSET_LTLASTFOOT:
4425                 flag = false;
4426         case Tabular::SET_LTLASTFOOT:
4427                 tabular.getRowOfLTLastFoot(row, ltt);
4428                 checkLongtableSpecial(ltt, value, flag);
4429                 tabular.setLTFoot(row, flag, ltt, true);
4430                 break;
4431
4432         case Tabular::SET_LTNEWPAGE:
4433                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4434                 break;
4435
4436         case Tabular::SET_BOOKTABS:
4437                 tabular.setBookTabs(true);
4438                 break;
4439
4440         case Tabular::UNSET_BOOKTABS:
4441                 tabular.setBookTabs(false);
4442                 break;
4443
4444         case Tabular::SET_TOP_SPACE: {
4445                 Length len;
4446                 if (value == "default")
4447                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4448                                 tabular.row_info[i].top_space_default = true;
4449                 else if (isValidLength(value, &len))
4450                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4451                                 tabular.row_info[i].top_space_default = false;
4452                                 tabular.row_info[i].top_space = len;
4453                         }
4454                 else
4455                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4456                                 tabular.row_info[i].top_space_default = false;
4457                                 tabular.row_info[i].top_space = len;
4458                         }
4459                 break;
4460         }
4461
4462         case Tabular::SET_BOTTOM_SPACE: {
4463                 Length len;
4464                 if (value == "default")
4465                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4466                                 tabular.row_info[i].bottom_space_default = true;
4467                 else if (isValidLength(value, &len))
4468                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4469                                 tabular.row_info[i].bottom_space_default = false;
4470                                 tabular.row_info[i].bottom_space = len;
4471                         }
4472                 else
4473                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4474                                 tabular.row_info[i].bottom_space_default = false;
4475                                 tabular.row_info[i].bottom_space = len;
4476                         }
4477                 break;
4478         }
4479
4480         case Tabular::SET_INTERLINE_SPACE: {
4481                 Length len;
4482                 if (value == "default")
4483                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4484                                 tabular.row_info[i].interline_space_default = true;
4485                 else if (isValidLength(value, &len))
4486                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4487                                 tabular.row_info[i].interline_space_default = false;
4488                                 tabular.row_info[i].interline_space = len;
4489                         }
4490                 else
4491                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4492                                 tabular.row_info[i].interline_space_default = false;
4493                                 tabular.row_info[i].interline_space = len;
4494                         }
4495                 break;
4496         }
4497
4498         // dummy stuff just to avoid warnings
4499         case Tabular::LAST_ACTION:
4500                 break;
4501         }
4502 }
4503
4504
4505 bool InsetTabular::showInsetDialog(BufferView * bv) const
4506 {
4507         bv->showDialog("tabular", params2string(*this),
4508                 const_cast<InsetTabular *>(this));
4509         return true;
4510 }
4511
4512
4513 void InsetTabular::openLayoutDialog(BufferView * bv) const
4514 {
4515         bv->showDialog("tabular", params2string(*this),
4516                 const_cast<InsetTabular *>(this));
4517 }
4518
4519
4520 bool InsetTabular::copySelection(Cursor & cur)
4521 {
4522         if (!cur.selection())
4523                 return false;
4524
4525         row_type rs, re;
4526         col_type cs, ce;
4527         getSelection(cur, rs, re, cs, ce);
4528
4529         paste_tabular.reset(new Tabular(tabular));
4530
4531         for (row_type i = 0; i < rs; ++i)
4532                 paste_tabular->deleteRow(0);
4533
4534         row_type const rows = re - rs + 1;
4535         while (paste_tabular->rowCount() > rows)
4536                 paste_tabular->deleteRow(rows);
4537
4538         for (col_type i = 0; i < cs; ++i)
4539                 paste_tabular->deleteColumn(0);
4540
4541         col_type const columns = ce - cs + 1;
4542         while (paste_tabular->columnCount() > columns)
4543                 paste_tabular->deleteColumn(columns);
4544
4545         // We clear all the InsetTableCell pointers, since they
4546         // might now become invalid and there is no point in having
4547         // them point to temporary things in paste_tabular.
4548         for (row_type i = 0; i < paste_tabular->rowCount(); ++i)
4549                 for (col_type j = 0; j < paste_tabular->columnCount(); ++j) {
4550                         paste_tabular->cellInset(i,j)->setCellData(0);
4551                         paste_tabular->cellInset(i,j)->setTabular(0);
4552                 }
4553
4554         odocstringstream os;
4555         OutputParams const runparams(0);
4556         paste_tabular->plaintext(os, runparams, 0, true, '\t');
4557         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4558         cap::copySelection(cur, os.str());
4559
4560         // mark tabular stack dirty
4561         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4562         // when we (hopefully) have a one-for-all paste mechanism.
4563         // This must be called after cap::copySelection.
4564         dirtyTabularStack(true);
4565
4566         return true;
4567 }
4568
4569
4570 bool InsetTabular::pasteClipboard(Cursor & cur)
4571 {
4572         if (!paste_tabular)
4573                 return false;
4574         col_type const actcol = tabular.cellColumn(cur.idx());
4575         row_type const actrow = tabular.cellRow(cur.idx());
4576         for (row_type r1 = 0, r2 = actrow;
4577              r1 < paste_tabular->rowCount() && r2 < tabular.rowCount();
4578              ++r1, ++r2) {
4579                 for (col_type c1 = 0, c2 = actcol;
4580                     c1 < paste_tabular->columnCount() && c2 < tabular.columnCount();
4581                     ++c1, ++c2) {
4582                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4583                             tabular.isPartOfMultiColumn(r2, c2))
4584                                 continue;
4585                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4586                                 --c2;
4587                                 continue;
4588                         }
4589                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4590                                 --c1;
4591                                 continue;
4592                         }
4593                         shared_ptr<InsetTableCell> inset(
4594                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
4595                         // note that setCellInset will call InsetTableCell::setCellData()
4596                         // and InsetTableCell::setTabular()
4597                         tabular.setCellInset(r2, c2, inset);
4598                         // FIXME: change tracking (MG)
4599                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4600                                                 Change::INSERTED : Change::UNCHANGED));
4601                         cur.pos() = 0;
4602                 }
4603         }
4604         return true;
4605 }
4606
4607
4608 void InsetTabular::cutSelection(Cursor & cur)
4609 {
4610         if (!cur.selection())
4611                 return;
4612
4613         row_type rs, re;
4614         col_type cs, ce;
4615         getSelection(cur, rs, re, cs, ce);
4616         for (row_type i = rs; i <= re; ++i) {
4617                 for (col_type j = cs; j <= ce; ++j) {
4618                         shared_ptr<InsetTableCell> t
4619                                 = cell(tabular.cellIndex(i, j));
4620                         if (cur.buffer().params().trackChanges)
4621                                 // FIXME: Change tracking (MG)
4622                                 t->setChange(Change(Change::DELETED));
4623                         else
4624                                 t->clear();
4625                 }
4626         }
4627
4628         // cursor position might be invalid now
4629         if (cur.pit() > cur.lastpit())
4630                 cur.pit() = cur.lastpit();
4631         if (cur.pos() > cur.lastpos())
4632                 cur.pos() = cur.lastpos();
4633         cur.clearSelection();
4634 }
4635
4636
4637 bool InsetTabular::isRightToLeft(Cursor & cur) const
4638 {
4639         LASSERT(cur.depth() > 1, /**/);
4640         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4641         pos_type const parentpos = cur[cur.depth() - 2].pos();
4642         return parentpar.getFontSettings(cur.bv().buffer().params(),
4643                                          parentpos).language()->rightToLeft();
4644 }
4645
4646
4647 void InsetTabular::getSelection(Cursor & cur,
4648         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4649 {
4650         CursorSlice const & beg = cur.selBegin();
4651         CursorSlice const & end = cur.selEnd();
4652         cs = tabular.cellColumn(beg.idx());
4653         ce = tabular.cellColumn(end.idx());
4654         if (cs > ce) {
4655                 ce = cs;
4656                 cs = tabular.cellColumn(end.idx());
4657         } else {
4658                 ce = tabular.cellRightColumn(end.idx());
4659         }
4660
4661         rs = tabular.cellRow(beg.idx());
4662         re = tabular.cellRow(end.idx());
4663         if (rs > re)
4664                 swap(rs, re);
4665 }
4666
4667
4668 Text * InsetTabular::getText(int idx) const
4669 {
4670         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4671 }
4672
4673
4674 void InsetTabular::setChange(Change const & change)
4675 {
4676         for (idx_type idx = 0; idx < nargs(); ++idx)
4677                 cell(idx)->setChange(change);
4678 }
4679
4680
4681 void InsetTabular::acceptChanges(BufferParams const & bparams)
4682 {
4683         for (idx_type idx = 0; idx < nargs(); ++idx)
4684                 cell(idx)->acceptChanges(bparams);
4685 }
4686
4687
4688 void InsetTabular::rejectChanges(BufferParams const & bparams)
4689 {
4690         for (idx_type idx = 0; idx < nargs(); ++idx)
4691                 cell(idx)->rejectChanges(bparams);
4692 }
4693
4694
4695 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4696 {
4697         return tabular.getPWidth(cell).zero();
4698 }
4699
4700
4701 bool InsetTabular::forceEmptyLayout(idx_type cell) const
4702 {
4703         return !tabular.getPWidth(cell).zero();
4704 }
4705
4706
4707 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4708                                      bool usePaste)
4709 {
4710         if (buf.length() <= 0)
4711                 return true;
4712
4713         col_type cols = 1;
4714         row_type rows = 1;
4715         col_type maxCols = 1;
4716         size_t const len = buf.length();
4717         size_t p = 0;
4718
4719         while (p < len &&
4720                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4721                 switch (buf[p]) {
4722                 case '\t':
4723                         ++cols;
4724                         break;
4725                 case '\n':
4726                         if (p + 1 < len)
4727                                 ++rows;
4728                         maxCols = max(cols, maxCols);
4729                         cols = 1;
4730                         break;
4731                 }
4732                 ++p;
4733         }
4734         maxCols = max(cols, maxCols);
4735         Tabular * loctab;
4736         idx_type cell = 0;
4737         col_type ocol = 0;
4738         row_type row = 0;
4739         if (usePaste) {
4740                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
4741                 loctab = paste_tabular.get();
4742                 cols = 0;
4743                 dirtyTabularStack(true);
4744         } else {
4745                 loctab = &tabular;
4746                 cell = bv.cursor().idx();
4747                 ocol = tabular.cellColumn(cell);
4748                 row = tabular.cellRow(cell);
4749         }
4750
4751         size_t op = 0;
4752         idx_type const cells = loctab->cellCount();
4753         p = 0;
4754         cols = ocol;
4755         rows = loctab->rowCount();
4756         col_type const columns = loctab->columnCount();
4757
4758         while (cell < cells && p < len && row < rows &&
4759                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4760         {
4761                 if (p >= len)
4762                         break;
4763                 switch (buf[p]) {
4764                 case '\t':
4765                         // we can only set this if we are not too far right
4766                         if (cols < columns) {
4767                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4768                                 Font const font = bv.textMetrics(&inset->text_).
4769                                         displayFont(0, 0);
4770                                 inset->setText(buf.substr(op, p - op), font,
4771                                                buffer().params().trackChanges);
4772                                 ++cols;
4773                                 ++cell;
4774                         }
4775                         break;
4776                 case '\n':
4777                         // we can only set this if we are not too far right
4778                         if (cols < columns) {
4779                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
4780                                 Font const font = bv.textMetrics(&inset->text_).
4781                                         displayFont(0, 0);
4782                                 inset->setText(buf.substr(op, p - op), font,
4783                                                buffer().params().trackChanges);
4784                         }
4785                         cols = ocol;
4786                         ++row;
4787                         if (row < rows)
4788                                 cell = loctab->cellIndex(row, cols);
4789                         break;
4790                 }
4791                 ++p;
4792                 op = p;
4793         }
4794         // check for the last cell if there is no trailing '\n'
4795         if (cell < cells && op < len) {
4796                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4797                 Font const font = bv.textMetrics(&inset->text_).displayFont(0, 0);
4798                 inset->setText(buf.substr(op, len - op), font,
4799                         buffer().params().trackChanges);
4800         }
4801         return true;
4802 }
4803
4804
4805 void InsetTabular::addPreview(PreviewLoader & loader) const
4806 {
4807         row_type const rows = tabular.rowCount();
4808         col_type const columns = tabular.columnCount();
4809         for (row_type i = 0; i < rows; ++i) {
4810                 for (col_type j = 0; j < columns; ++j)
4811                         tabular.cellInset(i, j)->addPreview(loader);
4812         }
4813 }
4814
4815
4816 bool InsetTabular::tablemode(Cursor & cur) const
4817 {
4818         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4819 }
4820
4821
4822 bool InsetTabular::completionSupported(Cursor const & cur) const
4823 {
4824         Cursor const & bvCur = cur.bv().cursor();
4825         if (&bvCur.inset() != this)
4826                 return false;
4827         return cur.text()->completionSupported(cur);
4828 }
4829
4830
4831 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
4832 {
4833         return completionSupported(cur);
4834 }
4835
4836
4837 bool InsetTabular::automaticInlineCompletion() const
4838 {
4839         return lyxrc.completion_inline_text;
4840 }
4841
4842
4843 bool InsetTabular::automaticPopupCompletion() const
4844 {
4845         return lyxrc.completion_popup_text;
4846 }
4847
4848
4849 bool InsetTabular::showCompletionCursor() const
4850 {
4851         return lyxrc.completion_cursor_text;
4852 }
4853
4854
4855 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
4856 {
4857         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
4858 }
4859
4860
4861 docstring InsetTabular::completionPrefix(Cursor const & cur) const
4862 {
4863         if (!completionSupported(cur))
4864                 return docstring();
4865         return cur.text()->completionPrefix(cur);
4866 }
4867
4868
4869 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
4870 {
4871         if (!completionSupported(cur))
4872                 return false;
4873
4874         return cur.text()->insertCompletion(cur, s, finished);
4875 }
4876
4877
4878 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
4879                                     Dimension & dim) const
4880 {
4881         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
4882         tm.completionPosAndDim(cur, x, y, dim);
4883 }
4884
4885
4886 void InsetTabular::string2params(string const & in, InsetTabular & inset)
4887 {
4888         istringstream data(in);
4889         Lexer lex;
4890         lex.setStream(data);
4891
4892         if (in.empty())
4893                 return;
4894
4895         string token;
4896         lex >> token;
4897         if (!lex || token != "tabular") {
4898                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
4899                 return;
4900         }
4901
4902         // This is part of the inset proper that is usually swallowed
4903         // by Buffer::readInset
4904         lex >> token;
4905         if (!lex || token != "Tabular") {
4906                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
4907                 return;
4908         }
4909
4910         inset.read(lex);
4911 }
4912
4913
4914 string InsetTabular::params2string(InsetTabular const & inset)
4915 {
4916         ostringstream data;
4917         data << "tabular" << ' ';
4918         inset.write(data);
4919         data << "\\end_inset\n";
4920         return data.str();
4921 }
4922
4923
4924 } // namespace lyx