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