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