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