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