]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
remove commented same_id functions, and also remove some const_casts
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14
15 #include "buffer.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
18 #include "debug.h"
19 #include "dimension.h"
20 #include "funcrequest.h"
21 #include "gettext.h"
22 #include "intl.h"
23 #include "LaTeXFeatures.h"
24 #include "LColor.h"
25 #include "Lsstream.h"
26 #include "lyxfont.h"
27 #include "lyxcursor.h"
28 #include "lyxfind.h"
29 #include "lyxlex.h"
30 #include "lyxrow.h"
31 #include "lyxrc.h"
32 #include "lyxtext.h"
33 #include "paragraph.h"
34 #include "ParagraphParameters.h"
35 #include "trans_mgr.h"
36 #include "undo_funcs.h"
37 #include "WordLangTuple.h"
38 #include "paragraph_funcs.h"
39 #include "sgml.h"
40 #include "rowpainter.h"
41 #include "insetnewline.h"
42 #include "Lsstream.h"
43
44 #include "frontends/Alert.h"
45 #include "frontends/Dialogs.h"
46 #include "frontends/font_metrics.h"
47 #include "frontends/LyXView.h"
48 #include "frontends/Painter.h"
49 #include "frontends/screen.h"
50
51 #include "support/textutils.h"
52 #include "support/LAssert.h"
53 #include "support/lstrings.h"
54 #include "support/lyxalgo.h" // lyx::count
55
56 #include <boost/bind.hpp>
57
58 #include <fstream>
59 #include <algorithm>
60 #include <cstdlib>
61 //#include <csignal>
62
63 using std::ostream;
64 using std::ifstream;
65 using std::endl;
66 using std::min;
67 using std::max;
68 using std::make_pair;
69 using std::vector;
70 using std::pair;
71 using std::for_each;
72
73 using lyx::pos_type;
74 using lyx::textclass_type;
75
76
77 // These functions should probably go into bufferview_funcs somehow (Jug)
78
79 void InsetText::saveLyXTextState(LyXText * t) const
80 {
81         // check if my paragraphs are still valid
82         ParagraphList::iterator it = const_cast<ParagraphList&>(paragraphs).begin();
83         ParagraphList::iterator end = const_cast<ParagraphList&>(paragraphs).end();
84         for (; it != end; ++it) {
85                 if (it == t->cursor.par())
86                         break;
87         }
88
89         if (it != end && t->cursor.pos() <= it->size()) {
90                 sstate.lpar = t->cursor.par();
91                 sstate.pos = t->cursor.pos();
92                 sstate.boundary = t->cursor.boundary();
93                 sstate.selstartpar = t->selection.start.par();
94                 sstate.selstartpos = t->selection.start.pos();
95                 sstate.selstartboundary = t->selection.start.boundary();
96                 sstate.selendpar = t->selection.end.par();
97                 sstate.selendpos = t->selection.end.pos();
98                 sstate.selendboundary = t->selection.end.boundary();
99                 sstate.selection = t->selection.set();
100                 sstate.mark_set = t->selection.mark();
101         } else {
102                 sstate.lpar = const_cast<ParagraphList&>(paragraphs).end();
103         }
104 }
105
106
107 void InsetText::restoreLyXTextState(LyXText * t) const
108 {
109         if (sstate.lpar == const_cast<ParagraphList&>(paragraphs).end())
110                 return;
111
112         t->selection.set(true);
113         /* at this point just to avoid the DEPM when setting the cursor */
114         t->selection.mark(sstate.mark_set);
115         if (sstate.selection) {
116                 t->setCursor(sstate.selstartpar, sstate.selstartpos,
117                              true, sstate.selstartboundary);
118                 t->selection.cursor = t->cursor;
119                 t->setCursor(sstate.selendpar, sstate.selendpos,
120                              true, sstate.selendboundary);
121                 t->setSelection();
122                 t->setCursor(sstate.lpar, sstate.pos);
123         } else {
124                 t->setCursor(sstate.lpar, sstate.pos, true, sstate.boundary);
125                 t->selection.cursor = t->cursor;
126                 t->selection.set(false);
127         }
128 }
129
130
131 InsetText::InnerCache::InnerCache(boost::shared_ptr<LyXText> t)
132 {
133         text = t;
134         remove = false;
135 }
136
137
138 InsetText::InsetText(BufferParams const & bp)
139         : UpdatableInset(), lt(0), in_update(false), do_resize(0),
140           do_reinit(false)
141 {
142         paragraphs.push_back(Paragraph());
143         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
144         if (bp.tracking_changes)
145                 paragraphs.begin()->trackChanges();
146         init(0);
147 }
148
149
150 InsetText::InsetText(InsetText const & in)
151         : UpdatableInset(in), lt(0), in_update(false), do_resize(0),
152           do_reinit(false)
153 {
154         init(&in);
155 }
156
157
158 InsetText & InsetText::operator=(InsetText const & it)
159 {
160         init(&it);
161         return * this;
162 }
163
164
165 void InsetText::init(InsetText const * ins)
166 {
167         if (ins) {
168                 setParagraphData(ins->paragraphs);
169                 autoBreakRows = ins->autoBreakRows;
170                 drawFrame_ = ins->drawFrame_;
171                 frame_color = ins->frame_color;
172         } else {
173                 for_each(paragraphs.begin(), paragraphs.end(),
174                          boost::bind(&Paragraph::setInsetOwner, _1, this));
175
176                 the_locking_inset = 0;
177                 drawFrame_ = NEVER;
178                 frame_color = LColor::insetframe;
179                 autoBreakRows = false;
180         }
181         top_y = 0;
182         old_max_width = 0;
183         no_selection = true;
184         need_update = FULL;
185         drawTextXOffset = 0;
186         drawTextYOffset = 0;
187         locked = false;
188         old_par = paragraphs.end();
189         last_drawn_width = -1;
190         cached_bview = 0;
191         sstate.lpar = paragraphs.end();
192         in_insetAllowed = false;
193 }
194
195
196 InsetText::~InsetText()
197 {
198         paragraphs.clear();
199 }
200
201
202 void InsetText::clear(bool just_mark_erased)
203 {
204         if (just_mark_erased) {
205                 ParagraphList::iterator it = paragraphs.begin();
206                 ParagraphList::iterator end = paragraphs.end();
207                 for (; it != end; ++it) {
208                         it->markErased();
209                 }
210                 need_update = FULL;
211                 return;
212         }
213
214         // This is a gross hack...
215         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
216
217         paragraphs.clear();
218         paragraphs.push_back(Paragraph());
219         paragraphs.begin()->setInsetOwner(this);
220         paragraphs.begin()->layout(old_layout);
221
222         reinitLyXText();
223         need_update = INIT;
224 }
225
226
227 Inset * InsetText::clone(Buffer const &) const
228 {
229         return new InsetText(*this);
230 }
231
232
233 void InsetText::write(Buffer const * buf, ostream & os) const
234 {
235         os << "Text\n";
236         writeParagraphData(buf, os);
237 }
238
239
240 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
241 {
242         ParagraphList::const_iterator it = paragraphs.begin();
243         ParagraphList::const_iterator end = paragraphs.end();
244         Paragraph::depth_type dth = 0;
245         for (; it != end; ++it) {
246                 it->write(buf, os, buf->params, dth);
247         }
248 }
249
250
251 void InsetText::read(Buffer const * buf, LyXLex & lex)
252 {
253         string token;
254         Paragraph::depth_type depth = 0;
255
256         clear(false);
257
258         if (buf->params.tracking_changes)
259                 paragraphs.begin()->trackChanges();
260
261         // delete the initial paragraph
262         paragraphs.clear();
263         ParagraphList::iterator pit = paragraphs.begin();
264
265         while (lex.isOK()) {
266                 lex.nextToken();
267                 token = lex.getString();
268                 if (token.empty())
269                         continue;
270                 if (token == "\\end_inset") {
271                         break;
272                 }
273
274                 if (token == "\\the_end") {
275                         lex.printError("\\the_end read in inset! Error in document!");
276                         return;
277                 }
278
279                 // FIXME: ugly.
280                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
281         }
282
283         pit = paragraphs.begin();
284         ParagraphList::iterator const end = paragraphs.end();
285         for (; pit != end; ++pit)
286                 pit->setInsetOwner(this);
287
288         if (token != "\\end_inset") {
289                 lex.printError("Missing \\end_inset at this point. "
290                                            "Read: `$$Token'");
291         }
292         need_update = FULL;
293 }
294
295
296 void InsetText::dimension(BufferView * bv, LyXFont const &,
297         Dimension & dim) const
298 {
299         LyXText * text = getLyXText(bv);
300         dim.asc = text->rows().begin()->ascent_of_text() + TEXT_TO_INSET_OFFSET;
301         dim.des = text->height - dim.asc + TEXT_TO_INSET_OFFSET;
302         dim.wid = max(textWidth(bv), int(text->width)) + 2 * TEXT_TO_INSET_OFFSET;
303         dim.wid = max(dim.wid, 10);
304         // cache it
305         dim_ = dim;
306 }
307
308
309 int InsetText::textWidth(BufferView * bv, bool fordraw) const
310 {
311         int w = autoBreakRows ? getMaxWidth(bv, this) : -1;
312
313         if (fordraw)
314                 return max(w - 2 * TEXT_TO_INSET_OFFSET,
315                            (int)getLyXText(bv)->width);
316
317         if (w < 0)
318                 return -1;
319
320         return w - 2 * TEXT_TO_INSET_OFFSET;
321 }
322
323
324 void InsetText::draw(BufferView * bv, LyXFont const & f,
325                      int baseline, float & x) const
326 {
327         if (nodraw())
328                 return;
329
330         // update our idea of where we are. Clearly, we should
331         // not have to know this information.
332         if (top_x != int(x))
333                 top_x = int(x);
334
335         int const start_x = int(x);
336
337         Painter & pain = bv->painter();
338
339         // call this method so that dim_ has the right value
340         dimension(bv, f, dim_);
341
342         // repaint the background if needed
343         if (backgroundColor() != LColor::background)
344                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
345
346         // no draw is necessary !!!
347         if ((drawFrame_ == LOCKED) && !locked && paragraphs.begin()->empty()) {
348                 top_baseline = baseline;
349                 x += width(bv, f);
350                 need_update = NONE;
351                 return;
352         }
353
354         if (!owner())
355                 x += static_cast<float>(scroll());
356
357         top_baseline = baseline;
358         top_y = baseline - dim_.asc;
359
360         if (last_drawn_width != dim_.wid) {
361                 need_update |= FULL;
362                 last_drawn_width = dim_.wid;
363         }
364
365         if (the_locking_inset && (cpar(bv) == inset_par)
366                 && (cpos(bv) == inset_pos)) {
367                 inset_x = cix(bv) - int(x) + drawTextXOffset;
368                 inset_y = ciy(bv) + drawTextYOffset;
369         }
370
371         bool clear = false;
372         if (!lt) {
373                 lt = getLyXText(bv);
374                 clear = true;
375         }
376         x += TEXT_TO_INSET_OFFSET;
377
378         RowList::iterator rowit = lt->rows().begin();
379         RowList::iterator end = lt->rows().end();
380
381         int y_offset = baseline - rowit->ascent_of_text();
382         int ph = pain.paperHeight();
383         int first = 0;
384         int y = y_offset;
385         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
386                 y += rowit->height();
387                 first += rowit->height();
388                 ++rowit;
389         }
390         if (y_offset < 0) {
391                 lt->top_y(-y_offset);
392                 first = y;
393                 y_offset = 0;
394         } else {
395                 lt->top_y(first);
396                 first = 0;
397         }
398
399         int yf = y_offset + first;
400         y = 0;
401
402         bv->hideCursor();
403
404         while ((rowit != end) && (yf < ph)) {
405                 RowPainter rp(*bv, *lt, rowit);
406                 rp.paint(y + y_offset + first, int(x), y + lt->top_y());
407                 y += rowit->height();
408                 yf += rowit->height();
409                 ++rowit;
410         }
411
412         lt->clearPaint();
413
414         if ((drawFrame_ == ALWAYS) || (drawFrame_ == LOCKED && locked)) {
415                 drawFrame(pain, int(start_x));
416         }
417
418         x += dim_.wid - TEXT_TO_INSET_OFFSET;
419
420         if (need_update != INIT) {
421                 need_update = NONE;
422         }
423         if (clear)
424                 lt = 0;
425 }
426
427
428 void InsetText::drawFrame(Painter & pain, int x) const
429 {
430         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
431         frame_x = x + ttoD2;
432         frame_y = top_baseline - dim_.asc + ttoD2;
433         frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
434         frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
435         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
436                        frame_color);
437 }
438
439
440 void InsetText::update(BufferView * bv, bool reinit)
441 {
442         if (in_update) {
443                 if (reinit && owner()) {
444                         reinitLyXText();
445                         owner()->update(bv, true);
446                 }
447                 return;
448         }
449         in_update = true;
450
451         if (reinit || need_update == INIT) {
452                 need_update = FULL;
453                 // we should put this call where we set need_update to INIT!
454                 reinitLyXText();
455                 if (owner())
456                         owner()->update(bv, true);
457                 in_update = false;
458
459                 int nw = getMaxWidth(bv, this);
460                 if (nw > 0 && old_max_width != nw) {
461                         need_update |= INIT;
462                         old_max_width = nw;
463                 }
464                 return;
465         }
466
467         if (!autoBreakRows &&
468             boost::next(paragraphs.begin()) != paragraphs.end())
469                 collapseParagraphs(bv);
470
471         if (the_locking_inset) {
472                 inset_x = cix(bv) - top_x + drawTextXOffset;
473                 inset_y = ciy(bv) + drawTextYOffset;
474                 the_locking_inset->update(bv, reinit);
475         }
476
477         bool clear = false;
478         if (!lt) {
479                 lt = getLyXText(bv);
480                 clear = true;
481         }
482         if ((need_update & CURSOR_PAR) && (lt->refreshStatus() == LyXText::REFRESH_NONE) &&
483                 the_locking_inset) {
484                 lt->updateInset(the_locking_inset);
485         }
486
487         if (lt->refreshStatus() == LyXText::REFRESH_AREA)
488                 need_update |= FULL;
489         if (clear)
490                 lt = 0;
491
492         in_update = false;
493
494         int nw = getMaxWidth(bv, this);
495         if (nw > 0 && old_max_width != nw) {
496                 need_update |= INIT;
497                 old_max_width = nw;
498         }
499 }
500
501
502 void InsetText::setUpdateStatus(BufferView * bv, int what) const
503 {
504         // this does nothing dangerous so use only a localized buffer
505         LyXText * llt = getLyXText(bv);
506
507         need_update |= what;
508         // we have to redraw us full if our LyXText REFRESH_AREA or
509         // if we don't break row so that we only have one row to update!
510         if ((llt->refreshStatus() == LyXText::REFRESH_AREA) ||
511             (!autoBreakRows &&
512              (llt->refreshStatus() == LyXText::REFRESH_ROW)))
513         {
514                 need_update |= FULL;
515         } else if (llt->refreshStatus() == LyXText::REFRESH_ROW) {
516                 need_update |= CURSOR_PAR;
517         }
518
519         // this to not draw a selection when we redraw all of it!
520         if (need_update & CURSOR && !(need_update & SELECTION)) {
521                 if (llt->selection.set())
522                         need_update = FULL;
523                 llt->clearSelection();
524         }
525 }
526
527
528 void InsetText::updateLocal(BufferView * bv, int what, bool mark_dirty)
529 {
530 #if 0
531         if (!autoBreakRows &&
532             boost::next(paragraphs.begin()) != paragraphs.end())
533                 collapseParagraphs(bv);
534 #else
535         if (!autoBreakRows && paragraphs.size() > 1)
536                 collapseParagraphs(bv);
537 #endif
538
539         bool clear = false;
540         if (!lt) {
541                 lt = getLyXText(bv);
542                 clear = true;
543         }
544         lt->fullRebreak();
545         setUpdateStatus(bv, what);
546         bool flag = mark_dirty ||
547                 (((need_update != CURSOR) && (need_update != NONE)) ||
548                  (lt->refreshStatus() != LyXText::REFRESH_NONE) || lt->selection.set());
549         if (!lt->selection.set())
550                 lt->selection.cursor = lt->cursor;
551
552         bv->fitCursor();
553
554         if (flag) {
555                 lt->postPaint(0);
556                 bv->updateInset(const_cast<InsetText *>(this));
557         }
558
559         if (clear)
560                 lt = 0;
561
562         if (need_update == CURSOR)
563                 need_update = NONE;
564         bv->owner()->view_state_changed();
565         bv->owner()->updateMenubar();
566         bv->owner()->updateToolbar();
567         if (old_par != cpar(bv)) {
568                 bv->owner()->setLayout(cpar(bv)->layout()->name());
569                 old_par = cpar(bv);
570         }
571 }
572
573
574 string const InsetText::editMessage() const
575 {
576         return _("Opened Text Inset");
577 }
578
579
580 void InsetText::insetUnlock(BufferView * bv)
581 {
582         if (the_locking_inset) {
583                 the_locking_inset->insetUnlock(bv);
584                 the_locking_inset = 0;
585                 updateLocal(bv, CURSOR_PAR, false);
586         }
587         no_selection = true;
588         locked = false;
589         int code = NONE;
590         bool clear = false;
591
592         if (!lt) {
593                 lt = getLyXText(bv);
594                 clear = true;
595         }
596         if (lt->selection.set()) {
597                 lt->clearSelection();
598                 code = FULL;
599         } else if (owner()) {
600                 bv->owner()->setLayout(owner()->getLyXText(bv)
601                                        ->cursor.par()->layout()->name());
602         } else
603                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
604         // hack for deleteEmptyParMech
605         if (!paragraphs.begin()->empty()) {
606                 lt->setCursor(paragraphs.begin(), 0);
607         } else if (boost::next(paragraphs.begin()) != paragraphs.end()) {
608                 lt->setCursor(boost::next(paragraphs.begin()), 0);
609         }
610         if (clear)
611                 lt = 0;
612 #if 0
613         updateLocal(bv, code, false);
614 #else
615         if (code != NONE)
616                 setUpdateStatus(bv, code);
617 #endif
618 }
619
620
621 void InsetText::lockInset(BufferView * bv)
622 {
623         locked = true;
624         the_locking_inset = 0;
625         inset_pos = inset_x = inset_y = 0;
626         inset_boundary = false;
627         inset_par = paragraphs.end();
628         old_par = paragraphs.end();
629         bool clear = false;
630         if (!lt) {
631                 lt = getLyXText(bv);
632                 clear = true;
633         }
634         lt->setCursor(paragraphs.begin(), 0);
635         lt->clearSelection();
636         finishUndo();
637         // If the inset is empty set the language of the current font to the
638         // language to the surronding text (if different).
639         if (paragraphs.begin()->empty() &&
640             boost::next(paragraphs.begin()) == paragraphs.end() &&
641                 bv->getParentLanguage(this) != lt->current_font.language()) {
642                 LyXFont font(LyXFont::ALL_IGNORE);
643                 font.setLanguage(bv->getParentLanguage(this));
644                 setFont(bv, font, false);
645         }
646         if (clear)
647                 lt = 0;
648         int code = CURSOR;
649         if (drawFrame_ == LOCKED)
650                 code = CURSOR|DRAW_FRAME;
651         setUpdateStatus(bv, code);
652 }
653
654
655 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
656 {
657         the_locking_inset = inset;
658         inset_x = cix(bv) - top_x + drawTextXOffset;
659         inset_y = ciy(bv) + drawTextYOffset;
660         inset_pos = cpos(bv);
661         inset_par = cpar(bv);
662         inset_boundary = cboundary(bv);
663         updateLocal(bv, CURSOR, false);
664 }
665
666
667 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
668 {
669         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
670                               << inset << "): ";
671         if (!inset)
672                 return false;
673         if (!the_locking_inset) {
674                 ParagraphList::iterator pit = paragraphs.begin();
675                 ParagraphList::iterator pend = paragraphs.end();
676
677                 int const id = inset->id();
678                 for (; pit != pend; ++pit) {
679                         InsetList::iterator it =
680                                 pit->insetlist.begin();
681                         InsetList::iterator const end =
682                                 pit->insetlist.end();
683                         for (; it != end; ++it) {
684                                 if (it.getInset() == inset) {
685                                         getLyXText(bv)->setCursorIntern(pit, it.getPos());
686                                         lockInset(bv, inset);
687                                         return true;
688                                 }
689                                 if (it.getInset()->getInsetFromID(id)) {
690                                         getLyXText(bv)->setCursorIntern(pit, it.getPos());
691                                         it.getInset()->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
692                                         return the_locking_inset->lockInsetInInset(bv, inset);
693                                 }
694                         }
695                 }
696                 return false;
697         }
698         if (inset == cpar(bv)->getInset(cpos(bv))) {
699                 lyxerr[Debug::INSETS] << "OK" << endl;
700                 lockInset(bv, inset);
701                 return true;
702         } else if (the_locking_inset && (the_locking_inset == inset)) {
703                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
704                         lyxerr[Debug::INSETS] << "OK" << endl;
705                         inset_x = cix(bv) - top_x + drawTextXOffset;
706                         inset_y = ciy(bv) + drawTextYOffset;
707                 } else {
708                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
709                 }
710         } else if (the_locking_inset) {
711                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
712                 return the_locking_inset->lockInsetInInset(bv, inset);
713         }
714         lyxerr[Debug::INSETS] << "NOT OK" << endl;
715         return false;
716 }
717
718
719 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
720                                    bool lr)
721 {
722         if (!the_locking_inset)
723                 return false;
724         if (the_locking_inset == inset) {
725                 the_locking_inset->insetUnlock(bv);
726                 getLyXText(bv)->updateInset(inset);
727                 the_locking_inset = 0;
728                 if (lr)
729                         moveRightIntern(bv, true, false);
730                 old_par = paragraphs.end(); // force layout setting
731                 if (scroll())
732                         scroll(bv, 0.0F);
733                 else
734                         updateLocal(bv, CURSOR, false);
735                 return true;
736         }
737         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
738 }
739
740
741 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
742 {
743         if (!autoBreakRows &&
744             boost::next(paragraphs.begin()) != paragraphs.end())
745                 collapseParagraphs(bv);
746         if (inset == this)
747                 return true;
748         bool clear = false;
749         if (!lt) {
750                 lt = getLyXText(bv);
751                 clear = true;
752         }
753         if (inset->owner() != this) {
754                 int ustat = CURSOR_PAR;
755                 bool found = false;
756                 UpdatableInset * tl_inset = the_locking_inset;
757                 if (tl_inset)
758                         found = tl_inset->updateInsetInInset(bv, inset);
759                 if (!found) {
760                         tl_inset = static_cast<UpdatableInset *>(inset);
761                         while(tl_inset->owner() && tl_inset->owner() != this)
762                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
763                         if (!tl_inset->owner())
764                                 return false;
765                         found = tl_inset->updateInsetInInset(bv, inset);
766                         ustat = FULL;
767                 }
768                 if (found)
769                         lt->updateInset(tl_inset);
770                 if (clear)
771                         lt = 0;
772                 if (found)
773                         setUpdateStatus(bv, ustat);
774                 return found;
775         }
776         bool found = lt->updateInset(inset);
777         if (clear)
778                 lt = 0;
779         if (found) {
780                 setUpdateStatus(bv, CURSOR_PAR);
781                 if (the_locking_inset &&
782                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
783                 {
784                         inset_x = cix(bv) - top_x + drawTextXOffset;
785                         inset_y = ciy(bv) + drawTextYOffset;
786                 }
787         }
788         return found;
789 }
790
791
792 void InsetText::lfunMousePress(FuncRequest const & cmd)
793 {
794         no_selection = true;
795
796         // use this to check mouse motion for selection!
797         mouse_x = cmd.x;
798         mouse_y = cmd.y;
799
800         BufferView * bv = cmd.view();
801         FuncRequest cmd1 = cmd;
802         cmd1.x -= inset_x;
803         cmd1.y -= inset_y;
804         if (!locked)
805                 lockInset(bv);
806
807         int tmp_x = cmd.x - drawTextXOffset;
808         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
809         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
810
811         if (the_locking_inset) {
812                 if (the_locking_inset == inset) {
813                         the_locking_inset->localDispatch(cmd1);
814                         return;
815                 }
816                 // otherwise only unlock the_locking_inset
817                 the_locking_inset->insetUnlock(bv);
818                 the_locking_inset = 0;
819         }
820         if (!inset)
821                 no_selection = false;
822
823         if (bv->theLockingInset()) {
824                 if (isHighlyEditableInset(inset)) {
825                         // We just have to lock the inset before calling a
826                         // PressEvent on it!
827                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
828                         if (!bv->lockInset(uinset)) {
829                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
830                         }
831                         inset->localDispatch(cmd1);
832                         if (the_locking_inset)
833                                 updateLocal(bv, CURSOR, false);
834                         return;
835                 }
836         }
837         if (!inset) {
838                 bool paste_internally = false;
839                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
840                         localDispatch(FuncRequest(bv, LFUN_COPY));
841                         paste_internally = true;
842                 }
843                 bool clear = false;
844                 if (!lt) {
845                         lt = getLyXText(bv);
846                         clear = true;
847                 }
848                 int old_top_y = lt->top_y();
849
850                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
851                                              cmd.y + dim_.asc);
852                 // set the selection cursor!
853                 lt->selection.cursor = lt->cursor;
854                 lt->cursor.x_fix(lt->cursor.x());
855
856                 if (lt->selection.set()) {
857                         lt->clearSelection();
858                         updateLocal(bv, FULL, false);
859                 } else {
860                         lt->clearSelection();
861                         updateLocal(bv, CURSOR, false);
862                 }
863
864                 if (clear)
865                         lt = 0;
866
867                 bv->owner()->setLayout(cpar(bv)->layout()->name());
868
869                 // we moved the view we cannot do mouse selection in this case!
870                 if (getLyXText(bv)->top_y() != old_top_y)
871                         no_selection = true;
872                 old_par = cpar(bv);
873                 // Insert primary selection with middle mouse
874                 // if there is a local selection in the current buffer,
875                 // insert this
876                 if (cmd.button() == mouse_button::button2) {
877                         if (paste_internally)
878                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
879                         else
880                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
881                 }
882         } else {
883                 getLyXText(bv)->clearSelection();
884         }
885 }
886
887
888 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
889 {
890         BufferView * bv = cmd.view();
891         FuncRequest cmd1 = cmd;
892         cmd1.x -= inset_x;
893         cmd1.y -= inset_y;
894
895         no_selection = true;
896         if (the_locking_inset)
897                 return the_locking_inset->localDispatch(cmd1);
898
899         int tmp_x = cmd.x - drawTextXOffset;
900         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
901         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
902         bool ret = false;
903         if (inset) {
904 // This code should probably be removed now. Simple insets
905 // (!highlyEditable) can actually take the localDispatch,
906 // and turn it into edit() if necessary. But we still
907 // need to deal properly with the whole relative vs.
908 // absolute mouse co-ords thing in a realiable, sensible way
909 #if 0
910                 if (isHighlyEditableInset(inset))
911                         ret = inset->localDispatch(cmd1);
912                 else {
913                         inset_x = cix(bv) - top_x + drawTextXOffset;
914                         inset_y = ciy(bv) + drawTextYOffset;
915                         cmd1.x = cmd.x - inset_x;
916                         cmd1.y = cmd.x - inset_y;
917                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
918                         ret = true;
919                 }
920 #endif
921                 ret = inset->localDispatch(cmd1);
922                 updateLocal(bv, CURSOR_PAR, false);
923
924         }
925         return ret;
926 }
927
928
929 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
930 {
931         FuncRequest cmd1 = cmd;
932         cmd1.x -= inset_x;
933         cmd1.y -= inset_y;
934
935         if (the_locking_inset) {
936                 the_locking_inset->localDispatch(cmd1);
937                 return;
938         }
939
940         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
941                 return;
942
943         BufferView * bv = cmd.view();
944         bool clear = false;
945         if (!lt) {
946                 lt = getLyXText(bv);
947                 clear = true;
948         }
949         LyXCursor cur = lt->cursor;
950         lt->setCursorFromCoordinates
951                 (cmd.x - drawTextXOffset, cmd.y + dim_.asc);
952         lt->cursor.x_fix(lt->cursor.x());
953         if (cur == lt->cursor) {
954                 if (clear)
955                         lt = 0;
956                 return;
957         }
958         lt->setSelection();
959         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
960                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
961         if (clear)
962                 lt = 0;
963         if (flag) {
964                 updateLocal(bv, SELECTION, false);
965         }
966 }
967
968
969 Inset::RESULT InsetText::localDispatch(FuncRequest const & cmd)
970 {
971         BufferView * bv = cmd.view();
972
973         if (cmd.action == LFUN_INSET_EDIT) {
974                 UpdatableInset::localDispatch(cmd);
975
976                 if (!bv->lockInset(this)) {
977                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
978                         return DISPATCHED;
979                 }
980
981                 locked = true;
982                 the_locking_inset = 0;
983                 inset_pos = inset_x = inset_y = 0;
984                 inset_boundary = false;
985                 inset_par = paragraphs.end();
986                 old_par = paragraphs.end();
987
988                 bool clear = false;
989                 if (!lt) {
990                         lt = getLyXText(bv);
991                         clear = true;
992                 }
993
994                 if (cmd.argument.size()) {
995                         if (cmd.argument == "left")
996                                 lt->setCursor(paragraphs.begin(), 0);
997                         else {
998                                 ParagraphList::iterator it = paragraphs.begin();
999                                 ParagraphList::iterator end = paragraphs.end();
1000                                 while (boost::next(it) != end)
1001                                         ++it;
1002                 //              int const pos = (p->size() ? p->size()-1 : p->size());
1003                                 lt->setCursor(it, it->size());
1004                         }
1005                 } else {
1006                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
1007                         // we put here -1 and not button as now the button in the
1008                         // edit call should not be needed we will fix this in 1.3.x
1009                         // cycle hopefully (Jug 20020509)
1010                         // FIXME: GUII I've changed this to none: probably WRONG
1011                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
1012                                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
1013                                                                         cmd.y + dim_.asc);
1014                                 lt->cursor.x_fix(lt->cursor.x());
1015                         }
1016                 }
1017
1018                 lt->clearSelection();
1019                 finishUndo();
1020
1021                 // If the inset is empty set the language of the current font to the
1022                 // language to the surronding text (if different).
1023                 if (paragraphs.begin()->empty() &&
1024                                 boost::next(paragraphs.begin()) == paragraphs.end()&&
1025                         bv->getParentLanguage(this) != lt->current_font.language())
1026                 {
1027                         LyXFont font(LyXFont::ALL_IGNORE);
1028                         font.setLanguage(bv->getParentLanguage(this));
1029                         setFont(bv, font, false);
1030                 }
1031
1032                 if (clear)
1033                         lt = 0;
1034                 int code = CURSOR;
1035                 if (drawFrame_ == LOCKED)
1036                         code = CURSOR | DRAW_FRAME;
1037
1038                 updateLocal(bv, code, false);
1039                 // Tell the paragraph dialog that we've entered an insettext.
1040                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1041                 return DISPATCHED;
1042         }
1043
1044
1045         switch (cmd.action) {
1046                 case LFUN_MOUSE_PRESS:
1047                         lfunMousePress(cmd);
1048                         return DISPATCHED;
1049                 case LFUN_MOUSE_MOTION:
1050                         lfunMouseMotion(cmd);
1051                         return DISPATCHED;
1052                 case LFUN_MOUSE_RELEASE:
1053                         return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
1054                 default:
1055                         break;
1056         }
1057
1058         bool was_empty = (paragraphs.begin()->empty() &&
1059                           boost::next(paragraphs.begin()) == paragraphs.end());
1060         no_selection = false;
1061         RESULT result = UpdatableInset::localDispatch(cmd);
1062         if (result != UNDISPATCHED)
1063                 return DISPATCHED;
1064
1065         result = DISPATCHED;
1066         if (cmd.action < 0 && cmd.argument.empty())
1067                 return FINISHED;
1068
1069         if (the_locking_inset) {
1070                 result = the_locking_inset->localDispatch(cmd);
1071                 if (result == DISPATCHED_NOUPDATE)
1072                         return result;
1073                 else if (result == DISPATCHED) {
1074                         updateLocal(bv, CURSOR_PAR, false);
1075                         return result;
1076                 } else if (result >= FINISHED) {
1077                         switch (result) {
1078                         case FINISHED_RIGHT:
1079                                 moveRightIntern(bv, false, false);
1080                                 result = DISPATCHED;
1081                                 break;
1082                         case FINISHED_UP:
1083                                 if ((result = moveUp(bv)) >= FINISHED) {
1084                                         updateLocal(bv, CURSOR, false);
1085                                         bv->unlockInset(this);
1086                                 }
1087                                 break;
1088                         case FINISHED_DOWN:
1089                                 if ((result = moveDown(bv)) >= FINISHED) {
1090                                         updateLocal(bv, CURSOR, false);
1091                                         bv->unlockInset(this);
1092                                 }
1093                                 break;
1094                         default:
1095                                 result = DISPATCHED;
1096                                 break;
1097                         }
1098                         the_locking_inset = 0;
1099                         updateLocal(bv, CURSOR, false);
1100                         // make sure status gets reset immediately
1101                         bv->owner()->clearMessage();
1102                         return result;
1103                 }
1104         }
1105         bool clear = false;
1106         if (!lt) {
1107                 lt = getLyXText(bv);
1108                 clear = true;
1109         }
1110         int updwhat = 0;
1111         int updflag = false;
1112
1113         // what type of update to do on a cursor movement
1114         int cursor_update = CURSOR;
1115
1116         if (lt->selection.set())
1117                 cursor_update = SELECTION;
1118
1119         switch (cmd.action) {
1120
1121         // Normal chars
1122         case LFUN_SELFINSERT:
1123                 if (bv->buffer()->isReadonly()) {
1124 //          setErrorMessage(N_("Document is read only"));
1125                         break;
1126                 }
1127                 if (!cmd.argument.empty()) {
1128                         /* Automatically delete the currently selected
1129                          * text and replace it with what is being
1130                          * typed in now. Depends on lyxrc settings
1131                          * "auto_region_delete", which defaults to
1132                          * true (on). */
1133 #if 0
1134                         // This should not be needed here and is also WRONG!
1135                         setUndo(bv, Undo::INSERT, lt->cursor.par());
1136 #endif
1137                         bv->switchKeyMap();
1138                         if (lyxrc.auto_region_delete) {
1139                                 if (lt->selection.set()) {
1140                                         lt->cutSelection(false, false);
1141                                 }
1142                         }
1143                         lt->clearSelection();
1144                         for (string::size_type i = 0; i < cmd.argument.length(); ++i) {
1145                                 bv->owner()->getIntl().getTransManager().
1146                                         TranslateAndInsert(cmd.argument[i], lt);
1147                         }
1148                 }
1149                 lt->selection.cursor = lt->cursor;
1150                 updwhat = CURSOR | CURSOR_PAR;
1151                 updflag = true;
1152                 result = DISPATCHED_NOUPDATE;
1153                 break;
1154
1155         // cursor movements that need special handling
1156
1157         case LFUN_RIGHT:
1158                 result = moveRight(bv);
1159                 finishUndo();
1160                 updwhat = cursor_update;
1161                 break;
1162         case LFUN_LEFT:
1163                 finishUndo();
1164                 result = moveLeft(bv);
1165                 updwhat = cursor_update;
1166                 break;
1167         case LFUN_DOWN:
1168                 finishUndo();
1169                 result = moveDown(bv);
1170                 updwhat = cursor_update;
1171                 break;
1172         case LFUN_UP:
1173                 finishUndo();
1174                 result = moveUp(bv);
1175                 updwhat = cursor_update;
1176                 break;
1177
1178         case LFUN_PRIOR:
1179                 if (crow(bv) == lt->rows().begin())
1180                         result = FINISHED_UP;
1181                 else {
1182                         lt->cursorPrevious();
1183                         lt->clearSelection();
1184                         result = DISPATCHED_NOUPDATE;
1185                 }
1186                 updwhat = cursor_update;
1187                 break;
1188
1189         case LFUN_NEXT:
1190                 if (boost::next(crow(bv)) == lt->rows().end())
1191                         result = FINISHED_DOWN;
1192                 else {
1193                         lt->cursorNext();
1194                         lt->clearSelection();
1195                         result = DISPATCHED_NOUPDATE;
1196                 }
1197                 updwhat = cursor_update;
1198                 break;
1199
1200         case LFUN_BACKSPACE: {
1201                 if (lt->selection.set())
1202                         lt->cutSelection(true, false);
1203                 else
1204                         lt->backspace();
1205                 updwhat = CURSOR_PAR;
1206                 updflag = true;
1207                 break;
1208         }
1209
1210         case LFUN_DELETE: {
1211                 if (lt->selection.set()) {
1212                         lt->cutSelection(true, false);
1213                 } else {
1214                         lt->Delete();
1215                 }
1216                 updwhat = CURSOR_PAR;
1217                 updflag = true;
1218                 break;
1219         }
1220
1221         case LFUN_CUT: {
1222                 lt->cutSelection(bv);
1223                 updwhat = CURSOR_PAR;
1224                 updflag = true;
1225                 break;
1226         }
1227
1228         case LFUN_COPY:
1229                 finishUndo();
1230                 lt->copySelection();
1231                 updwhat = CURSOR_PAR;
1232                 break;
1233
1234         case LFUN_PASTESELECTION:
1235         {
1236                 string const clip(bv->getClipboard());
1237
1238                 if (clip.empty())
1239                         break;
1240                 if (cmd.argument == "paragraph") {
1241                         lt->insertStringAsParagraphs(clip);
1242                 } else {
1243                         lt->insertStringAsLines(clip);
1244                 }
1245                 // bug 393
1246                 lt->clearSelection();
1247
1248                 updwhat = CURSOR_PAR;
1249                 updflag = true;
1250                 break;
1251         }
1252
1253         case LFUN_PASTE: {
1254                 if (!autoBreakRows) {
1255                         if (CutAndPaste::nrOfParagraphs() > 1) {
1256 #ifdef WITH_WARNINGS
1257 #warning FIXME horrendously bad UI
1258 #endif
1259                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
1260                                 break;
1261                         }
1262                 }
1263
1264                 lt->pasteSelection();
1265                 // bug 393
1266                 lt->clearSelection();
1267                 updwhat = CURSOR_PAR;
1268                 updflag = true;
1269                 break;
1270         }
1271
1272         case LFUN_BREAKPARAGRAPH:
1273                 if (!autoBreakRows) {
1274                         result = DISPATCHED;
1275                         break;
1276                 }
1277                 lt->breakParagraph(paragraphs, 0);
1278                 updwhat = CURSOR | FULL;
1279                 updflag = true;
1280                 break;
1281
1282         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1283                 if (!autoBreakRows) {
1284                         result = DISPATCHED;
1285                         break;
1286                 }
1287                 lt->breakParagraph(paragraphs, 1);
1288                 updwhat = CURSOR | FULL;
1289                 updflag = true;
1290                 break;
1291
1292         case LFUN_BREAKLINE: {
1293                 if (!autoBreakRows) {
1294                         result = DISPATCHED;
1295                         break;
1296                 }
1297
1298                 lt->insertInset(new InsetNewline);
1299                 updwhat = CURSOR | CURSOR_PAR;
1300                 updflag = true;
1301                 break;
1302         }
1303
1304         case LFUN_LAYOUT:
1305                 // do not set layouts on non breakable textinsets
1306                 if (autoBreakRows) {
1307                         string cur_layout = cpar(bv)->layout()->name();
1308
1309                         // Derive layout number from given argument (string)
1310                         // and current buffer's textclass (number). */
1311                         LyXTextClass const & tclass =
1312                                 bv->buffer()->params.getLyXTextClass();
1313                         string layout = cmd.argument;
1314                         bool hasLayout = tclass.hasLayout(layout);
1315
1316                         // If the entry is obsolete, use the new one instead.
1317                         if (hasLayout) {
1318                                 string const & obs =
1319                                         tclass[layout]->obsoleted_by();
1320                                 if (!obs.empty())
1321                                         layout = obs;
1322                         }
1323
1324                         // see if we found the layout number:
1325                         if (!hasLayout) {
1326                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1327                                 bv->owner()->dispatch(lf);
1328                                 break;
1329                         }
1330
1331                         if (cur_layout != layout) {
1332                                 cur_layout = layout;
1333                                 lt->setLayout(layout);
1334                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1335                                 updwhat = CURSOR_PAR;
1336                                 updflag = true;
1337                         }
1338                 } else {
1339                         // reset the layout box
1340                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1341                 }
1342                 break;
1343         case LFUN_PARAGRAPH_SPACING:
1344                 // This one is absolutely not working. When fiddling with this
1345                 // it also seems to me that the paragraphs inside the insettext
1346                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1347                 // FIXME: how old is this comment ? ...
1348         {
1349                 ParagraphList::iterator pit = lt->cursor.par();
1350                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1351                 float cur_value = 1.0;
1352                 if (cur_spacing == Spacing::Other) {
1353                         cur_value = pit->params().spacing().getValue();
1354                 }
1355
1356                 istringstream istr(STRCONV(cmd.argument));
1357                 string tmp;
1358                 istr >> tmp;
1359                 Spacing::Space new_spacing = cur_spacing;
1360                 float new_value = cur_value;
1361                 if (tmp.empty()) {
1362                         lyxerr << "Missing argument to `paragraph-spacing'"
1363                                    << endl;
1364                 } else if (tmp == "single") {
1365                         new_spacing = Spacing::Single;
1366                 } else if (tmp == "onehalf") {
1367                         new_spacing = Spacing::Onehalf;
1368                 } else if (tmp == "double") {
1369                         new_spacing = Spacing::Double;
1370                 } else if (tmp == "other") {
1371                         new_spacing = Spacing::Other;
1372                         float tmpval = 0.0;
1373                         istr >> tmpval;
1374                         lyxerr << "new_value = " << tmpval << endl;
1375                         if (tmpval != 0.0)
1376                                 new_value = tmpval;
1377                 } else if (tmp == "default") {
1378                         new_spacing = Spacing::Default;
1379                 } else {
1380                         lyxerr << _("Unknown spacing argument: ")
1381                                    << cmd.argument << endl;
1382                 }
1383                 if (cur_spacing != new_spacing || cur_value != new_value) {
1384                         pit->params().spacing(Spacing(new_spacing, new_value));
1385                         updwhat = CURSOR_PAR;
1386                         updflag = true;
1387                 }
1388         }
1389         break;
1390
1391         // These need to do repaints but don't require
1392         // special handling otherwise. A *lot* of the
1393         // above could probably be done similarly ...
1394
1395         case LFUN_HOME:
1396         case LFUN_END:
1397         case LFUN_WORDLEFT:
1398         case LFUN_WORDRIGHT:
1399         // these two are really unhandled ...
1400         case LFUN_ENDBUF:
1401         case LFUN_BEGINNINGBUF:
1402                 updwhat = cursor_update;
1403                 if (!bv->dispatch(cmd))
1404                         result = UNDISPATCHED;
1405                 break;
1406
1407         case LFUN_RIGHTSEL:
1408         case LFUN_UPSEL:
1409         case LFUN_DOWNSEL:
1410         case LFUN_LEFTSEL:
1411         case LFUN_HOMESEL:
1412         case LFUN_ENDSEL:
1413         case LFUN_WORDLEFTSEL:
1414         case LFUN_WORDRIGHTSEL:
1415                 updwhat = SELECTION;
1416
1417                 // fallthrough
1418
1419         default:
1420                 if (!bv->dispatch(cmd))
1421                         result = UNDISPATCHED;
1422                 break;
1423         }
1424
1425         if (clear)
1426                 lt = 0;
1427         if (updwhat > 0)
1428                 updateLocal(bv, updwhat, updflag);
1429         /// If the action has deleted all text in the inset, we need to change the
1430         // language to the language of the surronding text.
1431         if (!was_empty && paragraphs.begin()->empty() &&
1432             boost::next(paragraphs.begin()) == paragraphs.end()) {
1433                 LyXFont font(LyXFont::ALL_IGNORE);
1434                 font.setLanguage(bv->getParentLanguage(this));
1435                 setFont(bv, font, false);
1436         }
1437
1438         if (result >= FINISHED)
1439                 bv->unlockInset(this);
1440
1441         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1442                 result = DISPATCHED;
1443         return result;
1444 }
1445
1446
1447 int InsetText::latex(Buffer const * buf, ostream & os,
1448                      LatexRunParams const & runparams) const
1449 {
1450         TexRow texrow;
1451         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1452         return texrow.rows();
1453 }
1454
1455
1456 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1457 {
1458         unsigned int lines = 0;
1459
1460         ParagraphList::const_iterator beg = paragraphs.begin();
1461         ParagraphList::const_iterator end = paragraphs.end();
1462         ParagraphList::const_iterator it = beg;
1463         for (; it != end; ++it) {
1464                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1465                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1466                 os << tmp;
1467         }
1468         return lines;
1469 }
1470
1471
1472 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1473 {
1474         unsigned int lines = 0;
1475
1476         vector<string> environment_stack(10);
1477         vector<string> environment_inner(10);
1478
1479         int const command_depth = 0;
1480         string item_name;
1481
1482         Paragraph::depth_type depth = 0; // paragraph depth
1483
1484         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1485         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1486
1487         for (; pit != pend; ++pit) {
1488                 string sgmlparam;
1489                 int desc_on = 0; // description mode
1490
1491                 LyXLayout_ptr const & style = pit->layout();
1492
1493                 // environment tag closing
1494                 for (; depth > pit->params().depth(); --depth) {
1495                         if (environment_inner[depth] != "!-- --") {
1496                                 item_name = "listitem";
1497                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1498                                 if (environment_inner[depth] == "varlistentry")
1499                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1500                         }
1501                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1502                         environment_stack[depth].erase();
1503                         environment_inner[depth].erase();
1504                 }
1505
1506                 if (depth == pit->params().depth()
1507                    && environment_stack[depth] != style->latexname()
1508                    && !environment_stack[depth].empty()) {
1509                         if (environment_inner[depth] != "!-- --") {
1510                                 item_name= "listitem";
1511                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1512                                 if (environment_inner[depth] == "varlistentry")
1513                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1514                         }
1515
1516                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1517
1518                         environment_stack[depth].erase();
1519                         environment_inner[depth].erase();
1520                 }
1521
1522                 // Write opening SGML tags.
1523                 switch (style->latextype) {
1524                 case LATEX_PARAGRAPH:
1525                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1526                         break;
1527
1528                 case LATEX_COMMAND:
1529                         buf->sgmlError(pit, 0,  _("Error: LatexType Command not allowed here.\n"));
1530                         return -1;
1531                         break;
1532
1533                 case LATEX_ENVIRONMENT:
1534                 case LATEX_ITEM_ENVIRONMENT:
1535                         if (depth < pit->params().depth()) {
1536                                 depth = pit->params().depth();
1537                                 environment_stack[depth].erase();
1538                         }
1539
1540                         if (environment_stack[depth] != style->latexname()) {
1541                                 if (environment_stack.size() == depth + 1) {
1542                                         environment_stack.push_back("!-- --");
1543                                         environment_inner.push_back("!-- --");
1544                                 }
1545                                 environment_stack[depth] = style->latexname();
1546                                 environment_inner[depth] = "!-- --";
1547                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1548                         } else {
1549                                 if (environment_inner[depth] != "!-- --") {
1550                                         item_name= "listitem";
1551                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1552                                         if (environment_inner[depth] == "varlistentry")
1553                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1554                                 }
1555                         }
1556
1557                         if (style->latextype == LATEX_ENVIRONMENT) {
1558                                 if (!style->latexparam().empty()) {
1559                                         if (style->latexparam() == "CDATA")
1560                                                 os << "<![CDATA[";
1561                                         else
1562                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1563                                 }
1564                                 break;
1565                         }
1566
1567                         desc_on = (style->labeltype == LABEL_MANUAL);
1568
1569                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1570                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1571
1572                         item_name = desc_on ? "term" : "para";
1573                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1574
1575                         break;
1576                 default:
1577                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1578                         break;
1579                 }
1580
1581                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1582
1583                 string end_tag;
1584                 // write closing SGML tags
1585                 switch (style->latextype) {
1586                 case LATEX_ENVIRONMENT:
1587                         if (!style->latexparam().empty()) {
1588                                 if (style->latexparam() == "CDATA")
1589                                         os << "]]>";
1590                                 else
1591                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1592                         }
1593                         break;
1594                 case LATEX_ITEM_ENVIRONMENT:
1595                         if (desc_on == 1) break;
1596                         end_tag= "para";
1597                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1598                         break;
1599                 case LATEX_PARAGRAPH:
1600                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1601                         break;
1602                 default:
1603                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1604                         break;
1605                 }
1606         }
1607
1608         // Close open tags
1609         for (int d = depth; d >= 0; --d) {
1610                 if (!environment_stack[depth].empty()) {
1611                         if (environment_inner[depth] != "!-- --") {
1612                                 item_name = "listitem";
1613                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1614                                if (environment_inner[depth] == "varlistentry")
1615                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1616                         }
1617
1618                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1619                 }
1620         }
1621
1622         return lines;
1623 }
1624
1625
1626 void InsetText::validate(LaTeXFeatures & features) const
1627 {
1628         for_each(paragraphs.begin(), paragraphs.end(),
1629                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1630 }
1631
1632
1633 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1634 {
1635         if (the_locking_inset) {
1636                 the_locking_inset->getCursor(bv, x, y);
1637                 return;
1638         }
1639         x = cx(&bv);
1640         y = cy(&bv) + InsetText::y();
1641 }
1642
1643
1644 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1645 {
1646         if (the_locking_inset) {
1647                 the_locking_inset->getCursorPos(bv, x, y);
1648                 return;
1649         }
1650         x = cx(bv) - top_x - TEXT_TO_INSET_OFFSET;
1651         y = cy(bv) - TEXT_TO_INSET_OFFSET;
1652 }
1653
1654
1655 int InsetText::insetInInsetY() const
1656 {
1657         if (!the_locking_inset)
1658                 return 0;
1659
1660         return (inset_y + the_locking_inset->insetInInsetY());
1661 }
1662
1663
1664 void InsetText::fitInsetCursor(BufferView * bv) const
1665 {
1666         if (the_locking_inset) {
1667                 the_locking_inset->fitInsetCursor(bv);
1668                 return;
1669         }
1670         LyXFont const font =
1671                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1672
1673         int const asc = font_metrics::maxAscent(font);
1674         int const desc = font_metrics::maxDescent(font);
1675
1676         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1677                 need_update |= FULL;
1678 }
1679
1680
1681 Inset::RESULT
1682 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1683 {
1684         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1685                 return moveLeftIntern(bv, false, activate_inset, selecting);
1686         else
1687                 return moveRightIntern(bv, true, activate_inset, selecting);
1688 }
1689
1690
1691 Inset::RESULT
1692 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1693 {
1694         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1695                 return moveRightIntern(bv, true, activate_inset, selecting);
1696         else
1697                 return moveLeftIntern(bv, false, activate_inset, selecting);
1698 }
1699
1700
1701 Inset::RESULT
1702 InsetText::moveRightIntern(BufferView * bv, bool front,
1703                            bool activate_inset, bool selecting)
1704 {
1705         LyXText * text = getLyXText(bv);
1706
1707         ParagraphList::iterator c_par = cpar(bv);
1708
1709         if (boost::next(c_par) == paragraphs.end() &&
1710             (cpos(bv) >= c_par->size()))
1711                 return FINISHED_RIGHT;
1712         if (activate_inset && checkAndActivateInset(bv, front))
1713                 return DISPATCHED;
1714         text->cursorRight(bv);
1715         if (!selecting)
1716                 text->clearSelection();
1717         return DISPATCHED_NOUPDATE;
1718 }
1719
1720
1721 Inset::RESULT
1722 InsetText::moveLeftIntern(BufferView * bv, bool front,
1723                           bool activate_inset, bool selecting)
1724 {
1725         LyXText * text = getLyXText(bv);
1726
1727         if (cpar(bv) == paragraphs.begin() && (cpos(bv) <= 0))
1728                 return FINISHED;
1729         text->cursorLeft(bv);
1730         if (!selecting)
1731                 text->clearSelection();
1732         if (activate_inset && checkAndActivateInset(bv, front))
1733                 return DISPATCHED;
1734         return DISPATCHED_NOUPDATE;
1735 }
1736
1737
1738 Inset::RESULT InsetText::moveUp(BufferView * bv)
1739 {
1740         if (crow(bv) == getLyXText(bv)->rows().begin())
1741                 return FINISHED_UP;
1742         getLyXText(bv)->cursorUp(bv);
1743         getLyXText(bv)->clearSelection();
1744         return DISPATCHED_NOUPDATE;
1745 }
1746
1747
1748 Inset::RESULT InsetText::moveDown(BufferView * bv)
1749 {
1750         if (boost::next(crow(bv)) == getLyXText(bv)->rows().end())
1751                 return FINISHED_DOWN;
1752         getLyXText(bv)->cursorDown(bv);
1753         getLyXText(bv)->clearSelection();
1754         return DISPATCHED_NOUPDATE;
1755 }
1756
1757
1758 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1759 {
1760         if (the_locking_inset) {
1761                 if (the_locking_inset->insetAllowed(inset))
1762                         return the_locking_inset->insertInset(bv, inset);
1763                 return false;
1764         }
1765         inset->setOwner(this);
1766         getLyXText(bv)->insertInset(inset);
1767         bv->fitCursor();
1768         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1769         return true;
1770 }
1771
1772
1773 bool InsetText::insetAllowed(Inset::Code code) const
1774 {
1775         // in_insetAllowed is a really gross hack,
1776         // to allow us to call the owner's insetAllowed
1777         // without stack overflow, which can happen
1778         // when the owner uses InsetCollapsable::insetAllowed()
1779         bool ret = true;
1780         if (in_insetAllowed)
1781                 return ret;
1782         in_insetAllowed = true;
1783         if (the_locking_inset)
1784                 ret = the_locking_inset->insetAllowed(code);
1785         else if (owner())
1786                 ret = owner()->insetAllowed(code);
1787         in_insetAllowed = false;
1788         return ret;
1789 }
1790
1791
1792 UpdatableInset * InsetText::getLockingInset() const
1793 {
1794         return the_locking_inset ? the_locking_inset->getLockingInset() :
1795                 const_cast<InsetText *>(this);
1796 }
1797
1798
1799 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1800 {
1801         if (c == lyxCode())
1802                 return this;
1803         if (the_locking_inset)
1804                 return the_locking_inset->getFirstLockingInsetOfType(c);
1805         return 0;
1806 }
1807
1808
1809 bool InsetText::showInsetDialog(BufferView * bv) const
1810 {
1811         if (the_locking_inset)
1812                 return the_locking_inset->showInsetDialog(bv);
1813         return false;
1814 }
1815
1816
1817 vector<string> const InsetText::getLabelList() const
1818 {
1819         vector<string> label_list;
1820
1821         ParagraphList::const_iterator pit = paragraphs.begin();
1822         ParagraphList::const_iterator pend = paragraphs.end();
1823         for (; pit != pend; ++pit) {
1824                 InsetList::iterator beg = pit->insetlist.begin();
1825                 InsetList::iterator end = pit->insetlist.end();
1826                 for (; beg != end; ++beg) {
1827                         vector<string> const l = beg.getInset()->getLabelList();
1828                         label_list.insert(label_list.end(), l.begin(), l.end());
1829                 }
1830         }
1831         return label_list;
1832 }
1833
1834
1835 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1836                         bool selectall)
1837 {
1838         if (the_locking_inset) {
1839                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1840                 return;
1841         }
1842         if ((boost::next(paragraphs.begin()) == paragraphs.end() &&
1843              paragraphs.begin()->empty()) || cpar(bv)->empty()) {
1844                 getLyXText(bv)->setFont(font, toggleall);
1845                 return;
1846         }
1847         bool clear = false;
1848         if (!lt) {
1849                 lt = getLyXText(bv);
1850                 clear = true;
1851         }
1852         if (lt->selection.set()) {
1853                 setUndo(bv, Undo::EDIT, lt->cursor.par());
1854         }
1855         if (selectall)
1856                 selectAll(bv);
1857         lt->toggleFree(font, toggleall);
1858         if (selectall)
1859                 lt->clearSelection();
1860         bv->fitCursor();
1861         bool flag = (selectall || lt->selection.set());
1862         if (clear)
1863                 lt = 0;
1864         if (flag)
1865                 updateLocal(bv, FULL, true);
1866         else
1867                 updateLocal(bv, CURSOR_PAR, true);
1868 }
1869
1870
1871 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1872 {
1873         if (cpar(bv)->isInset(cpos(bv))) {
1874                 Inset * inset =
1875                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1876                 if (!isHighlyEditableInset(inset))
1877                         return false;
1878                 FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1879                 inset->localDispatch(cmd);
1880                 if (!the_locking_inset)
1881                         return false;
1882                 updateLocal(bv, CURSOR, false);
1883                 return true;
1884         }
1885         return false;
1886 }
1887
1888
1889 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1890                                       mouse_button::state button)
1891 {
1892         x -= drawTextXOffset;
1893         int dummyx = x;
1894         int dummyy = y + dim_.asc;
1895         Inset * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1896         // we only do the edit() call if the inset was hit by the mouse
1897         // or if it is a highly editable inset. So we should call this
1898         // function from our own edit with button < 0.
1899         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1900         // WRONG
1901         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1902                 return false;
1903
1904         if (inset) {
1905                 if (x < 0)
1906                         x = dim_.wid;
1907                 if (y < 0)
1908                         y = dim_.des;
1909                 inset_x = cix(bv) - top_x + drawTextXOffset;
1910                 inset_y = ciy(bv) + drawTextYOffset;
1911                 FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1912                 inset->localDispatch(cmd);
1913                 if (!the_locking_inset)
1914                         return false;
1915                 updateLocal(bv, CURSOR, false);
1916                 return true;
1917         }
1918         return false;
1919 }
1920
1921
1922 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
1923 {
1924 #if 0
1925         int w = UpdatableInset::getMaxWidth(bv, inset);
1926         if (w < 0) {
1927                 return -1;
1928         }
1929         if (owner()) {
1930                 w = w - top_x + owner()->x();
1931                 return w;
1932         }
1933         w -= (2 * TEXT_TO_INSET_OFFSET);
1934         return w - top_x;
1935 #else
1936         return UpdatableInset::getMaxWidth(bv, inset);
1937 #endif
1938 }
1939
1940
1941 void InsetText::setParagraphData(ParagraphList const & plist)
1942 {
1943         // we have to unlock any locked inset otherwise we're in troubles
1944         the_locking_inset = 0;
1945
1946         // But it it makes no difference that is a lot better.
1947 #warning FIXME.
1948         // See if this can be simplified when std::list is in effect.
1949         paragraphs.clear();
1950
1951         ParagraphList::const_iterator it = plist.begin();
1952         ParagraphList::const_iterator end = plist.end();
1953         for (; it != end; ++it) {
1954                 paragraphs.push_back(*it);
1955                 Paragraph & tmp = paragraphs.back();
1956                 tmp.setInsetOwner(this);
1957         }
1958
1959         reinitLyXText();
1960         need_update = INIT;
1961 }
1962
1963
1964 void InsetText::markNew(bool track_changes)
1965 {
1966         ParagraphList::iterator pit = paragraphs.begin();
1967         ParagraphList::iterator pend = paragraphs.end();
1968         for (; pit != pend; ++pit) {
1969                 if (track_changes) {
1970                         pit->trackChanges();
1971                 } else {
1972                         // no-op when not tracking
1973                         pit->cleanChanges();
1974                 }
1975         }
1976 }
1977
1978
1979 void InsetText::setText(string const & data, LyXFont const & font)
1980 {
1981         clear(false);
1982         for (unsigned int i = 0; i < data.length(); ++i)
1983                 paragraphs.begin()->insertChar(i, data[i], font);
1984         reinitLyXText();
1985 }
1986
1987
1988 void InsetText::setAutoBreakRows(bool flag)
1989 {
1990         if (flag != autoBreakRows) {
1991                 autoBreakRows = flag;
1992                 if (!flag)
1993                         removeNewlines();
1994                 need_update = INIT;
1995         }
1996 }
1997
1998
1999 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
2000 {
2001         if (how != drawFrame_) {
2002                 drawFrame_ = how;
2003                 if (bv)
2004                         updateLocal(bv, DRAW_FRAME, false);
2005         }
2006 }
2007
2008
2009 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2010 {
2011         if (frame_color != col) {
2012                 frame_color = col;
2013                 if (bv)
2014                         updateLocal(bv, DRAW_FRAME, false);
2015         }
2016 }
2017
2018
2019 int InsetText::cx(BufferView * bv) const
2020 {
2021         // we do nothing dangerous so we use a local cache
2022         LyXText * llt = getLyXText(bv);
2023         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2024         if (the_locking_inset) {
2025                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2026                                             llt->cursor.pos());
2027                 if (font.isVisibleRightToLeft())
2028                         x -= the_locking_inset->width(bv, font);
2029         }
2030         return x;
2031 }
2032
2033
2034 int InsetText::cix(BufferView * bv) const
2035 {
2036         // we do nothing dangerous so we use a local cache
2037         LyXText * llt = getLyXText(bv);
2038         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2039         if (the_locking_inset) {
2040                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2041                                             llt->cursor.pos());
2042                 if (font.isVisibleRightToLeft())
2043                         x -= the_locking_inset->width(bv, font);
2044         }
2045         return x;
2046 }
2047
2048
2049 int InsetText::cy(BufferView * bv) const
2050 {
2051         LyXFont font;
2052         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2053 }
2054
2055
2056 int InsetText::ciy(BufferView * bv) const
2057 {
2058         LyXFont font;
2059         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2060 }
2061
2062
2063 pos_type InsetText::cpos(BufferView * bv) const
2064 {
2065         return getLyXText(bv)->cursor.pos();
2066 }
2067
2068
2069 ParagraphList::iterator InsetText::cpar(BufferView * bv) const
2070 {
2071         return getLyXText(bv)->cursor.par();
2072 }
2073
2074
2075 bool InsetText::cboundary(BufferView * bv) const
2076 {
2077         return getLyXText(bv)->cursor.boundary();
2078 }
2079
2080
2081 RowList::iterator InsetText::crow(BufferView * bv) const
2082 {
2083         return getLyXText(bv)->cursor.row();
2084 }
2085
2086
2087 LyXText * InsetText::getLyXText(BufferView const * lbv,
2088                                 bool const recursive) const
2089 {
2090         if (cached_bview == lbv) {
2091                 if (recursive && the_locking_inset)
2092                         return the_locking_inset->getLyXText(lbv, true);
2093                 LyXText * lt = cached_text.get();
2094                 lyx::Assert(lt && lt->rows().begin()->par() == const_cast<ParagraphList&>(paragraphs).begin());
2095                 return lt;
2096         }
2097         // Super UGLY! (Lgb)
2098         BufferView * bv = const_cast<BufferView *>(lbv);
2099
2100         cached_bview = bv;
2101         Cache::iterator it = cache.find(bv);
2102
2103         if (it != cache.end()) {
2104                 if (do_reinit) {
2105                         reinitLyXText();
2106                 } else if (do_resize) {
2107                         resizeLyXText(do_resize);
2108                 } else {
2109                         if (lt || !it->second.remove) {
2110                                 lyx::Assert(it->second.text.get());
2111                                 cached_text = it->second.text;
2112                                 if (recursive && the_locking_inset) {
2113                                         return the_locking_inset->getLyXText(bv, true);
2114                                 }
2115                                 return cached_text.get();
2116                         } else if (it->second.remove) {
2117                                 if (locked) {
2118                                         saveLyXTextState(it->second.text.get());
2119                                 } else {
2120                                         sstate.lpar = const_cast<ParagraphList&>(paragraphs).end();
2121                                 }
2122                         }
2123                         //
2124                         // when we have to reinit the existing LyXText!
2125                         //
2126                         it->second.text->init(bv);
2127                         restoreLyXTextState(it->second.text.get());
2128                         it->second.remove = false;
2129                 }
2130                 cached_text = it->second.text;
2131                 if (the_locking_inset && recursive) {
2132                         return the_locking_inset->getLyXText(bv);
2133                 }
2134                 return cached_text.get();
2135         }
2136         ///
2137         // we are here only if we don't have a BufferView * in the cache!!!
2138         ///
2139         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2140         cached_text->init(bv);
2141         restoreLyXTextState(cached_text.get());
2142
2143         cache.insert(make_pair(bv, cached_text));
2144
2145         if (the_locking_inset && recursive) {
2146                 return the_locking_inset->getLyXText(bv);
2147         }
2148         return cached_text.get();
2149 }
2150
2151
2152 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2153 {
2154         cached_bview = 0;
2155
2156         Cache::iterator it = cache.find(bv);
2157
2158         if (it == cache.end()) {
2159                 return;
2160         }
2161
2162         lyx::Assert(it->second.text.get());
2163
2164         it->second.remove = true;
2165         if (recursive) {
2166                 /// then remove all LyXText in text-insets
2167                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2168                          const_cast<ParagraphList&>(paragraphs).end(),
2169                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2170         }
2171 }
2172
2173
2174 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2175 {
2176         if (lt) {
2177                 // we cannot resize this because we are in use!
2178                 // so do this on the next possible getLyXText()
2179                 do_resize = bv;
2180                 return;
2181         }
2182         do_resize = 0;
2183         if (boost::next(paragraphs.begin()) == paragraphs.end() &&
2184             paragraphs.begin()->empty()) { // no data, resize not neccessary!
2185                 // we have to do this as a fixed width may have changed!
2186                 LyXText * t = getLyXText(bv);
2187                 saveLyXTextState(t);
2188                 t->init(bv, true);
2189                 restoreLyXTextState(t);
2190                 return;
2191         }
2192         // one endless line, resize normally not necessary
2193         if (!force && getMaxWidth(bv, this) < 0)
2194                 return;
2195
2196         Cache::iterator it = cache.find(bv);
2197         if (it == cache.end()) {
2198                 return;
2199         }
2200         lyx::Assert(it->second.text.get());
2201
2202         LyXText * t = it->second.text.get();
2203         saveLyXTextState(t);
2204
2205         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2206                  const_cast<ParagraphList&>(paragraphs).end(),
2207                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2208
2209         t->init(bv, true);
2210         restoreLyXTextState(t);
2211         if (the_locking_inset) {
2212                 inset_x = cix(bv) - top_x + drawTextXOffset;
2213                 inset_y = ciy(bv) + drawTextYOffset;
2214         }
2215
2216         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2217         if (!owner()) {
2218                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2219                 // this will scroll the screen such that the cursor becomes visible
2220                 bv->updateScrollbar();
2221         } else {
2222                 need_update |= FULL;
2223         }
2224 }
2225
2226
2227 void InsetText::reinitLyXText() const
2228 {
2229         if (lt) {
2230                 // we cannot resize this because we are in use!
2231                 // so do this on the next possible getLyXText()
2232                 do_reinit = true;
2233                 return;
2234         }
2235         do_reinit = false;
2236         do_resize = 0;
2237         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2238                 lyx::Assert(it->second.text.get());
2239
2240                 LyXText * t = it->second.text.get();
2241                 BufferView * bv = it->first;
2242
2243                 saveLyXTextState(t);
2244
2245                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2246                          const_cast<ParagraphList&>(paragraphs).end(),
2247                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2248
2249                 t->init(bv, true);
2250                 restoreLyXTextState(t);
2251                 if (the_locking_inset) {
2252                         inset_x = cix(bv) - top_x + drawTextXOffset;
2253                         inset_y = ciy(bv) + drawTextYOffset;
2254                 }
2255                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2256                 if (!owner()) {
2257                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2258                         // this will scroll the screen such that the cursor becomes visible
2259                         bv->updateScrollbar();
2260                 } else {
2261                         need_update = FULL;
2262                 }
2263         }
2264 }
2265
2266
2267 void InsetText::removeNewlines()
2268 {
2269         bool changed = false;
2270
2271         ParagraphList::iterator it = paragraphs.begin();
2272         ParagraphList::iterator end = paragraphs.end();
2273         for (; it != end; ++it) {
2274                 for (int i = 0; i < it->size(); ++i) {
2275                         if (it->isNewline(i)) {
2276                                 changed = true;
2277                                 it->erase(i);
2278                         }
2279                 }
2280         }
2281         if (changed)
2282                 reinitLyXText();
2283 }
2284
2285
2286 bool InsetText::nodraw() const
2287 {
2288         if (the_locking_inset)
2289                 return the_locking_inset->nodraw();
2290         return UpdatableInset::nodraw();
2291 }
2292
2293
2294 int InsetText::scroll(bool recursive) const
2295 {
2296         int sx = UpdatableInset::scroll(false);
2297
2298         if (recursive && the_locking_inset)
2299                 sx += the_locking_inset->scroll(recursive);
2300
2301         return sx;
2302 }
2303
2304
2305 void InsetText::selectAll(BufferView * bv)
2306 {
2307         getLyXText(bv)->cursorTop();
2308         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2309         getLyXText(bv)->cursorBottom();
2310         getLyXText(bv)->setSelection();
2311 }
2312
2313
2314 void InsetText::clearSelection(BufferView * bv)
2315 {
2316         getLyXText(bv)->clearSelection();
2317 }
2318
2319
2320 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2321 {
2322         Painter & pain = bv->painter();
2323         int w = dim_.wid;
2324         int h = dim_.asc + dim_.des;
2325         int ty = baseline - dim_.asc;
2326
2327         if (ty < 0) {
2328                 h += ty;
2329                 ty = 0;
2330         }
2331         if ((ty + h) > pain.paperHeight())
2332                 h = pain.paperHeight();
2333         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2334                 w = pain.paperWidth();
2335         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2336         need_update = FULL;
2337 }
2338
2339
2340 ParagraphList * InsetText::getParagraphs(int i) const
2341 {
2342         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
2343 }
2344
2345
2346 LyXCursor const & InsetText::cursor(BufferView * bv) const
2347 {
2348         if (the_locking_inset)
2349                 return the_locking_inset->cursor(bv);
2350         return getLyXText(bv)->cursor;
2351 }
2352
2353
2354 Inset * InsetText::getInsetFromID(int id_arg) const
2355 {
2356         if (id_arg == id())
2357                 return const_cast<InsetText *>(this);
2358
2359         ParagraphList::const_iterator pit = paragraphs.begin();
2360         ParagraphList::const_iterator pend = paragraphs.end();
2361         for (; pit != pend; ++pit) {
2362                 InsetList::iterator it = pit->insetlist.begin();
2363                 InsetList::iterator end = pit->insetlist.end();
2364                 for (; it != end; ++it) {
2365                         if (it.getInset()->id() == id_arg)
2366                                 return it.getInset();
2367                         Inset * in = it.getInset()->getInsetFromID(id_arg);
2368                         if (in)
2369                                 return in;
2370                 }
2371         }
2372         return 0;
2373 }
2374
2375
2376 WordLangTuple const
2377 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2378                                       float & value) const
2379 {
2380         bool clear = false;
2381         WordLangTuple word;
2382
2383         if (!lt) {
2384                 lt = getLyXText(bv);
2385                 clear = true;
2386         }
2387         if (the_locking_inset) {
2388                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2389                 if (!word.word().empty()) {
2390                         value += cy(bv);
2391                         if (clear)
2392                                 lt = 0;
2393                         return word;
2394                 }
2395                 // we have to go on checking so move cursor to the next char
2396                 lt->cursor.pos(lt->cursor.pos() + 1);
2397         }
2398         word = lt->selectNextWordToSpellcheck(value);
2399         if (word.word().empty())
2400                 bv->unlockInset(const_cast<InsetText *>(this));
2401         else
2402                 value = cy(bv);
2403         if (clear)
2404                 lt = 0;
2405         return word;
2406 }
2407
2408
2409 void InsetText::selectSelectedWord(BufferView * bv)
2410 {
2411         if (the_locking_inset) {
2412                 the_locking_inset->selectSelectedWord(bv);
2413                 return;
2414         }
2415         getLyXText(bv)->selectSelectedWord();
2416         updateLocal(bv, SELECTION, false);
2417 }
2418
2419
2420 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2421 {
2422         if (the_locking_inset) {
2423                 the_locking_inset->toggleSelection(bv, kill_selection);
2424         }
2425         bool clear = false;
2426         if (!lt) {
2427                 lt = getLyXText(bv);
2428                 clear = true;
2429         }
2430
2431         int x = top_x + TEXT_TO_INSET_OFFSET;
2432
2433         RowList::iterator rowit = lt->rows().begin();
2434         RowList::iterator end = lt->rows().end();
2435         int y_offset = top_baseline - rowit->ascent_of_text();
2436         int y = y_offset;
2437         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2438                 y += rowit->height();
2439                 ++rowit;
2440         }
2441         if (y_offset < 0)
2442                 y_offset = y;
2443
2444         if (need_update & SELECTION)
2445                 need_update = NONE;
2446         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2447         if (clear)
2448                 lt = 0;
2449 }
2450
2451
2452 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2453 {
2454         bool clear = false;
2455         if (!lt) {
2456                 lt = getLyXText(bv);
2457                 clear = true;
2458         }
2459         if (the_locking_inset) {
2460                 if (the_locking_inset->nextChange(bv, length))
2461                         return true;
2462                 lt->cursorRight(true);
2463         }
2464         lyxfind::SearchResult result =
2465                 lyxfind::findNextChange(bv, lt, length);
2466
2467         if (result == lyxfind::SR_FOUND) {
2468                 LyXCursor cur = lt->cursor;
2469                 bv->unlockInset(bv->theLockingInset());
2470                 if (bv->lockInset(this))
2471                         locked = true;
2472                 lt->cursor = cur;
2473                 lt->setSelectionRange(length);
2474                 updateLocal(bv, SELECTION, false);
2475         }
2476         if (clear)
2477                 lt = 0;
2478         return result != lyxfind::SR_NOT_FOUND;
2479 }
2480
2481
2482 bool InsetText::searchForward(BufferView * bv, string const & str,
2483                               bool cs, bool mw)
2484 {
2485         bool clear = false;
2486         if (!lt) {
2487                 lt = getLyXText(bv);
2488                 clear = true;
2489         }
2490         if (the_locking_inset) {
2491                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2492                         return true;
2493                 lt->cursorRight(true);
2494         }
2495         lyxfind::SearchResult result =
2496                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2497
2498         if (result == lyxfind::SR_FOUND) {
2499                 LyXCursor cur = lt->cursor;
2500                 bv->unlockInset(bv->theLockingInset());
2501                 if (bv->lockInset(this))
2502                         locked = true;
2503                 lt->cursor = cur;
2504                 lt->setSelectionRange(str.length());
2505                 updateLocal(bv, SELECTION, false);
2506         }
2507         if (clear)
2508                 lt = 0;
2509         return (result != lyxfind::SR_NOT_FOUND);
2510 }
2511
2512 bool InsetText::searchBackward(BufferView * bv, string const & str,
2513                                bool cs, bool mw)
2514 {
2515         if (the_locking_inset) {
2516                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2517                         return true;
2518         }
2519         bool clear = false;
2520         if (!lt) {
2521                 lt = getLyXText(bv);
2522                 clear = true;
2523         }
2524         if (!locked) {
2525                 ParagraphList::iterator pit = paragraphs.begin();
2526                 ParagraphList::iterator pend = paragraphs.end();
2527
2528                 while (boost::next(pit) != pend)
2529                         ++pit;
2530
2531                 lt->setCursor(pit, pit->size());
2532         }
2533         lyxfind::SearchResult result =
2534                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2535
2536         if (result == lyxfind::SR_FOUND) {
2537                 LyXCursor cur = lt->cursor;
2538                 bv->unlockInset(bv->theLockingInset());
2539                 if (bv->lockInset(this))
2540                         locked = true;
2541                 lt->cursor = cur;
2542                 lt->setSelectionRange(str.length());
2543                 updateLocal(bv, SELECTION, false);
2544         }
2545         if (clear)
2546                 lt = 0;
2547         return (result != lyxfind::SR_NOT_FOUND);
2548 }
2549
2550
2551 bool InsetText::checkInsertChar(LyXFont & font)
2552 {
2553         if (owner())
2554                 return owner()->checkInsertChar(font);
2555         return true;
2556 }
2557
2558
2559 void InsetText::collapseParagraphs(BufferView * bv)
2560 {
2561         LyXText * llt = getLyXText(bv);
2562
2563         while (boost::next(paragraphs.begin()) != paragraphs.end()) {
2564                 if (!paragraphs.begin()->empty() &&
2565                     !boost::next(paragraphs.begin())->empty() &&
2566                         !paragraphs.begin()->isSeparator(paragraphs.begin()->size() - 1))
2567                 {
2568                         paragraphs.begin()->insertChar(paragraphs.begin()->size(), ' ');
2569                 }
2570                 if (llt->selection.set()) {
2571                         if (llt->selection.start.par() == boost::next(paragraphs.begin())) {
2572                                 llt->selection.start.par(paragraphs.begin());
2573                                 llt->selection.start.pos(
2574                                         llt->selection.start.pos() + paragraphs.begin()->size());
2575                         }
2576                         if (llt->selection.end.par() == boost::next(paragraphs.begin())) {
2577                                 llt->selection.end.par(paragraphs.begin());
2578                                 llt->selection.end.pos(
2579                                         llt->selection.end.pos() + paragraphs.begin()->size());
2580                         }
2581                 }
2582                 mergeParagraph(bv->buffer()->params, paragraphs, paragraphs.begin());
2583         }
2584         reinitLyXText();
2585 }
2586
2587
2588 void InsetText::getDrawFont(LyXFont & font) const
2589 {
2590         if (!owner())
2591                 return;
2592         owner()->getDrawFont(font);
2593 }
2594
2595
2596 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2597 {
2598 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2599 // And it probably does. You have to take a look at this John. (Lgb)
2600 #warning John, have a look here. (Lgb)
2601 #if 0
2602         BufferParams const & bparams = buffer->params;
2603         Paragraph * buf;
2604         Paragraph * tmpbuf = newpar;
2605         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2606         if (bparams.tracking_changes)
2607                 buf->cleanChanges();
2608
2609         while (tmpbuf->next()) {
2610                 tmpbuf = tmpbuf->next();
2611                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2612                 lastbuffer->next()->previous(lastbuffer);
2613                 lastbuffer = lastbuffer->next();
2614                 if (bparams.tracking_changes)
2615                         lastbuffer->cleanChanges();
2616         }
2617
2618         lastbuffer = &*(paragraphs.begin());
2619         while (lastbuffer->next())
2620                 lastbuffer = lastbuffer->next();
2621         if (!newpar->empty() && !lastbuffer->empty() &&
2622                 !lastbuffer->isSeparator(lastbuffer->size() - 1))
2623         {
2624                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2625         }
2626
2627         // make the buf exactly the same layout than our last paragraph
2628         buf->makeSameLayout(lastbuffer);
2629
2630         // paste it!
2631         lastbuffer->next(buf);
2632         buf->previous(lastbuffer);
2633         mergeParagraph(buffer->params, paragraphs, lastbuffer);
2634 #else
2635         ParagraphList::iterator pit = plist.begin();
2636         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
2637         ++pit;
2638         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2639
2640         ParagraphList::iterator pend = plist.end();
2641         for (; pit != pend; ++pit) {
2642                 paragraphs.push_back(*pit);
2643         }
2644
2645 #endif
2646
2647         reinitLyXText();
2648 }
2649
2650
2651 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2652 {
2653         ParagraphList::const_iterator pit = paragraphs.begin();
2654         ParagraphList::const_iterator pend = paragraphs.end();
2655
2656         for (; pit != pend; ++pit) {
2657                 InsetList::iterator it  = pit->insetlist.begin();
2658                 InsetList::iterator end = pit->insetlist.end();
2659                 for (; it != end; ++it) {
2660                         it.getInset()->addPreview(loader);
2661                 }
2662         }
2663 }