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