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