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