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