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