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