]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
merge parts of InsetText and LyXText::dispatch
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14
15 #include "buffer.h"
16 #include "BufferView.h"
17 #include "bufferview_funcs.h"
18 #include "CutAndPaste.h"
19 #include "debug.h"
20 #include "dimension.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "errorlist.h"
24 #include "intl.h"
25 #include "LaTeXFeatures.h"
26 #include "LColor.h"
27 #include "Lsstream.h"
28 #include "lyxfont.h"
29 #include "lyxcursor.h"
30 #include "lyxfind.h"
31 #include "lyxlex.h"
32 #include "lyxrow.h"
33 #include "lyxrc.h"
34 #include "lyxtext.h"
35 #include "paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "trans_mgr.h"
38 #include "undo_funcs.h"
39 #include "WordLangTuple.h"
40 #include "paragraph_funcs.h"
41 #include "sgml.h"
42 #include "rowpainter.h"
43 #include "insetnewline.h"
44 #include "metricsinfo.h"
45
46 #include "frontends/Alert.h"
47 #include "frontends/Dialogs.h"
48 #include "frontends/font_metrics.h"
49 #include "frontends/LyXView.h"
50 #include "frontends/Painter.h"
51 #include "frontends/screen.h"
52
53 #include "support/textutils.h"
54 #include "support/LAssert.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // lyx::count
57
58 #include <boost/bind.hpp>
59
60 #include <fstream>
61 #include <algorithm>
62 #include <cstdlib>
63
64 using std::ostream;
65 using std::ifstream;
66 using std::endl;
67 using std::min;
68 using std::max;
69 using std::make_pair;
70 using std::vector;
71 using std::pair;
72 using std::for_each;
73 using std::auto_ptr;
74
75 using namespace lyx::support;
76 using namespace lyx::graphics;
77 using namespace bv_funcs;
78
79 using lyx::pos_type;
80 using lyx::textclass_type;
81
82
83 // we should get rid of these (Andre')
84
85 void InsetText::saveLyXTextState() const
86 {
87         // check if my paragraphs are still valid
88         ParagraphList::iterator it = const_cast<ParagraphList&>(paragraphs).begin();
89         ParagraphList::iterator end = const_cast<ParagraphList&>(paragraphs).end();
90         for (; it != end; ++it)
91                 if (it == text_.cursor.par())
92                         break;
93
94         if (it != end && text_.cursor.pos() <= it->size())
95                 sstate = text_; // slicing intended
96         else
97                 sstate.cursor.par(end);
98 }
99
100
101 void InsetText::restoreLyXTextState() const
102 {
103         if (sstate.cursor.par() == const_cast<ParagraphList&>(paragraphs).end())
104                 return;
105
106         text_.selection.set(true);
107         // at this point just to avoid the DEPM when setting the cursor
108         text_.selection.mark(sstate.selection.mark());
109         if (sstate.selection.set()) {
110                 text_.setCursor(sstate.selection.start.par(),
111                         sstate.selection.start.pos(),
112                         true, sstate.selection.start.boundary());
113                 text_.selection.cursor = text_.cursor;
114                 text_.setCursor(sstate.selection.end.par(), sstate.selection.end.pos(),
115                         true, sstate.selection.end.boundary());
116                 text_.setSelection();
117                 text_.setCursor(sstate.cursor.par(), sstate.cursor.pos());
118         } else {
119                 text_.setCursor(sstate.cursor.par(), sstate.cursor.pos(),
120                         true, sstate.cursor.boundary());
121                 text_.selection.cursor = text_.cursor;
122                 text_.selection.set(false);
123         }
124 }
125
126
127 InsetText::InsetText(BufferParams const & bp)
128         : UpdatableInset(), text_(0, this)
129 {
130         paragraphs.push_back(Paragraph());
131         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
132         if (bp.tracking_changes)
133                 paragraphs.begin()->trackChanges();
134         init(0);
135 }
136
137
138 InsetText::InsetText(InsetText const & in)
139         : UpdatableInset(in), text_(0, this)
140 {
141         init(&in);
142 }
143
144
145 InsetText & InsetText::operator=(InsetText const & it)
146 {
147         init(&it);
148         return *this;
149 }
150
151
152 void InsetText::init(InsetText const * ins)
153 {
154         if (ins) {
155                 textwidth_ = ins->textwidth_;
156                 text_.bv_owner = ins->text_.bv_owner;
157
158                 paragraphs = ins->paragraphs;
159
160                 ParagraphList::iterator pit = paragraphs.begin();
161                 ParagraphList::iterator end = paragraphs.end();
162                 for (; pit != end; ++pit)
163                         pit->setInsetOwner(this);
164
165                 reinitLyXText();
166
167                 autoBreakRows = ins->autoBreakRows;
168                 drawFrame_ = ins->drawFrame_;
169                 frame_color = ins->frame_color;
170         } else {
171                 textwidth_ = 0; // broken
172                 drawFrame_ = NEVER;
173                 frame_color = LColor::insetframe;
174                 autoBreakRows = false;
175         }
176         the_locking_inset = 0;
177         for_each(paragraphs.begin(), paragraphs.end(),
178                  boost::bind(&Paragraph::setInsetOwner, _1, this));
179         top_y = 0;
180         no_selection = true;
181         drawTextXOffset = 0;
182         drawTextYOffset = 0;
183         locked = false;
184         old_par = paragraphs.end();
185         sstate.cursor.par(paragraphs.end());
186         in_insetAllowed = false;
187 }
188
189
190 void InsetText::clear(bool just_mark_erased)
191 {
192         if (just_mark_erased) {
193                 ParagraphList::iterator it = paragraphs.begin();
194                 ParagraphList::iterator end = paragraphs.end();
195                 for (; it != end; ++it) {
196                         it->markErased();
197                 }
198                 return;
199         }
200
201         // This is a gross hack...
202         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
203
204         paragraphs.clear();
205         paragraphs.push_back(Paragraph());
206         paragraphs.begin()->setInsetOwner(this);
207         paragraphs.begin()->layout(old_layout);
208
209         reinitLyXText();
210 }
211
212
213 auto_ptr<InsetBase> InsetText::clone() const
214 {
215         return auto_ptr<InsetBase>(new InsetText(*this));
216 }
217
218
219 void InsetText::write(Buffer const * buf, ostream & os) const
220 {
221         os << "Text\n";
222         writeParagraphData(buf, os);
223 }
224
225
226 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
227 {
228         ParagraphList::const_iterator it = paragraphs.begin();
229         ParagraphList::const_iterator end = paragraphs.end();
230         Paragraph::depth_type dth = 0;
231         for (; it != end; ++it) {
232                 it->write(buf, os, buf->params, dth);
233         }
234 }
235
236
237 void InsetText::read(Buffer const * buf, LyXLex & lex)
238 {
239         string token;
240         Paragraph::depth_type depth = 0;
241
242         clear(false);
243
244         if (buf->params.tracking_changes)
245                 paragraphs.begin()->trackChanges();
246
247         // delete the initial paragraph
248         paragraphs.clear();
249         ParagraphList::iterator pit = paragraphs.begin();
250
251         while (lex.isOK()) {
252                 lex.nextToken();
253                 token = lex.getString();
254                 if (token.empty())
255                         continue;
256                 if (token == "\\end_inset") {
257                         break;
258                 }
259
260                 if (token == "\\end_document") {
261                         lex.printError("\\end_document read in inset! Error in document!");
262                         return;
263                 }
264
265                 // FIXME: ugly.
266                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
267         }
268
269         pit = paragraphs.begin();
270         ParagraphList::iterator const end = paragraphs.end();
271         for (; pit != end; ++pit)
272                 pit->setInsetOwner(this);
273
274         if (token != "\\end_inset") {
275                 lex.printError("Missing \\end_inset at this point. "
276                                            "Read: `$$Token'");
277         }
278 }
279
280
281 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
282 {
283         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
284
285         textwidth_ = mi.base.textwidth;
286         BufferView * bv = mi.base.bv;
287         setViewCache(bv);
288         text_.metrics(mi, dim);
289         dim.asc += TEXT_TO_INSET_OFFSET;
290         dim.des += TEXT_TO_INSET_OFFSET;
291         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
292         dim.wid = max(dim.wid, 10);
293         dim_ = dim;
294 }
295
296
297 int InsetText::textWidth() const
298 {
299         return textwidth_;
300 }
301
302
303 void InsetText::draw(PainterInfo & pi, int x, int baseline) const
304 {
305         // update our idea of where we are. Clearly, we should
306         // not have to know this information.
307         top_x = x;
308
309         int const start_x = x;
310
311         BufferView * bv = pi.base.bv;
312         Painter & pain = pi.pain;
313
314         // repaint the background if needed
315         if (backgroundColor() != LColor::background)
316                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
317
318         // no draw is necessary !!!
319         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
320                 top_baseline = baseline;
321                 return;
322         }
323
324         bv->hideCursor();
325
326         if (!owner())
327                 x += scroll();
328
329         top_baseline = baseline;
330         top_y = baseline - dim_.asc;
331
332         if (the_locking_inset && cpar() == inset_par && cpos() == inset_pos) {
333                 inset_x = cix() - x + drawTextXOffset;
334                 inset_y = ciy() + drawTextYOffset;
335         }
336
337         x += TEXT_TO_INSET_OFFSET;
338
339         RowList::iterator rit = text_.rows().begin();
340         RowList::iterator end = text_.rows().end();
341
342         int y_offset = baseline - rit->ascent_of_text();
343         int y2 = pain.paperHeight();
344         int first = 0;
345         int y = y_offset;
346         while (rit != end && y + rit->height() <= 0) {
347                 y += rit->height();
348                 first += rit->height();
349                 ++rit;
350         }
351         if (y_offset < 0) {
352                 text_.top_y(-y_offset);
353                 first = y;
354                 y_offset = 0;
355         } else {
356                 text_.top_y(first);
357                 first = 0;
358         }
359
360         int yo = y_offset + first;
361
362         paintRows(*bv, text_, rit, x, 0, yo, y2, yo);
363
364         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
365                 drawFrame(pain, int(start_x));
366 }
367
368
369 void InsetText::drawFrame(Painter & pain, int x) const
370 {
371         int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
372         int const frame_x = x + ttoD2;
373         int const frame_y = top_baseline - dim_.asc + ttoD2;
374         int const frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
375         int const frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
376         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frame_color);
377 }
378
379
380 void InsetText::updateLocal(BufferView * bv, bool /*mark_dirty*/)
381 {
382         if (!bv)
383                 return;
384
385         if (!autoBreakRows && paragraphs.size() > 1)
386                 collapseParagraphs(bv);
387
388         text_.partialRebreak();
389         if (!text_.selection.set())
390                 text_.selection.cursor = text_.cursor;
391
392         bv->fitCursor();
393         bv->updateInset();
394         bv->owner()->view_state_changed();
395         bv->owner()->updateMenubar();
396         bv->owner()->updateToolbar();
397         if (old_par != cpar()) {
398                 bv->owner()->setLayout(cpar()->layout()->name());
399                 old_par = cpar();
400         }
401 }
402
403
404 string const InsetText::editMessage() const
405 {
406         return _("Opened Text Inset");
407 }
408
409
410 void InsetText::insetUnlock(BufferView * bv)
411 {
412         if (the_locking_inset) {
413                 the_locking_inset->insetUnlock(bv);
414                 the_locking_inset = 0;
415                 updateLocal(bv, false);
416         }
417         no_selection = true;
418         locked = false;
419
420         if (text_.selection.set()) {
421                 text_.clearSelection();
422         } else if (owner()) {
423                 bv->owner()->setLayout(owner()->getLyXText(bv)
424                                        ->cursor.par()->layout()->name());
425         } else
426                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
427         // hack for deleteEmptyParMech
428         ParagraphList::iterator first_par = paragraphs.begin();
429         if (!first_par->empty()) {
430                 text_.setCursor(first_par, 0);
431         } else if (paragraphs.size() > 1) {
432                 text_.setCursor(boost::next(first_par), 0);
433         }
434 }
435
436
437 void InsetText::lockInset(BufferView * bv)
438 {
439         locked = true;
440         the_locking_inset = 0;
441         inset_pos = inset_x = inset_y = 0;
442         inset_boundary = false;
443         inset_par = paragraphs.end();
444         old_par = paragraphs.end();
445         text_.setCursorIntern(paragraphs.begin(), 0);
446         text_.clearSelection();
447         finishUndo();
448         // If the inset is empty set the language of the current font to the
449         // language to the surronding text (if different).
450         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
451                 bv->getParentLanguage(this) != text_.current_font.language()) {
452                 LyXFont font(LyXFont::ALL_IGNORE);
453                 font.setLanguage(bv->getParentLanguage(this));
454                 setFont(bv, font, false);
455         }
456 }
457
458
459 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
460 {
461         the_locking_inset = inset;
462         inset_x = cix() - top_x + drawTextXOffset;
463         inset_y = ciy() + drawTextYOffset;
464         inset_pos = cpos();
465         inset_par = cpar();
466         inset_boundary = cboundary();
467 }
468
469
470 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
471 {
472         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
473                               << inset << "): " << endl;
474         if (!inset)
475                 return false;
476         if (!the_locking_inset) {
477                 ParagraphList::iterator pit = paragraphs.begin();
478                 ParagraphList::iterator pend = paragraphs.end();
479
480                 int const id = inset->id();
481                 for (; pit != pend; ++pit) {
482                         InsetList::iterator it = pit->insetlist.begin();
483                         InsetList::iterator const end = pit->insetlist.end();
484                         for (; it != end; ++it) {
485                                 if (it->inset == inset) {
486                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
487                                         text_.setCursorIntern(pit, it->pos);
488                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
489                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
490                                         lockInset(bv, inset);
491                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
492                                         return true;
493                                 }
494                                 if (it->inset->getInsetFromID(id)) {
495                                         lyxerr << "InsetText::lockInsetInInset: 2" << endl;
496                                         text_.setCursorIntern(pit, it->pos);
497                                         it->inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
498                                         return the_locking_inset->lockInsetInInset(bv, inset);
499                                 }
500                         }
501                 }
502                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
503                 return false;
504         }
505         if (inset == cpar()->getInset(cpos())) {
506                 lyxerr[Debug::INSETS] << "OK" << endl;
507                 lockInset(bv, inset);
508                 return true;
509         }
510
511         if (the_locking_inset && the_locking_inset == inset) {
512                 if (cpar() == inset_par && cpos() == inset_pos) {
513                         lyxerr[Debug::INSETS] << "OK" << endl;
514                         inset_x = cix() - top_x + drawTextXOffset;
515                         inset_y = ciy() + drawTextYOffset;
516                 } else {
517                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
518                 }
519         } else if (the_locking_inset) {
520                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
521                 return the_locking_inset->lockInsetInInset(bv, inset);
522         }
523         lyxerr[Debug::INSETS] << "NOT OK" << endl;
524         return false;
525 }
526
527
528 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
529                                    bool lr)
530 {
531         if (!the_locking_inset)
532                 return false;
533         if (the_locking_inset == inset) {
534                 the_locking_inset->insetUnlock(bv);
535                 getLyXText(bv)->updateInset(inset);
536                 the_locking_inset = 0;
537                 if (lr)
538                         moveRightIntern(bv, true, false);
539                 old_par = paragraphs.end(); // force layout setting
540                 if (scroll())
541                         scroll(bv, 0.0F);
542                 else
543                         updateLocal(bv, false);
544                 return true;
545         }
546         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
547 }
548
549
550 void InsetText::lfunMousePress(FuncRequest const & cmd)
551 {
552         no_selection = true;
553
554         // use this to check mouse motion for selection!
555         mouse_x = cmd.x;
556         mouse_y = cmd.y;
557
558         BufferView * bv = cmd.view();
559         FuncRequest cmd1 = cmd;
560         cmd1.x -= inset_x;
561         cmd1.y -= inset_y;
562         if (!locked)
563                 lockInset(bv);
564
565         int tmp_x = cmd.x - drawTextXOffset;
566         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
567         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
568
569         if (the_locking_inset) {
570                 if (the_locking_inset == inset) {
571                         the_locking_inset->localDispatch(cmd1);
572                         return;
573                 }
574                 // otherwise only unlock the_locking_inset
575                 the_locking_inset->insetUnlock(bv);
576                 the_locking_inset = 0;
577         }
578         if (!inset)
579                 no_selection = false;
580
581         if (bv->theLockingInset()) {
582                 if (isHighlyEditableInset(inset)) {
583                         // We just have to lock the inset before calling a
584                         // PressEvent on it!
585                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
586                         if (!bv->lockInset(uinset)) {
587                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
588                         }
589                         inset->localDispatch(cmd1);
590                         if (the_locking_inset)
591                                 updateLocal(bv, false);
592                         return;
593                 }
594         }
595         if (!inset) {
596                 bool paste_internally = false;
597                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
598                         localDispatch(FuncRequest(bv, LFUN_COPY));
599                         paste_internally = true;
600                 }
601                 int old_top_y = text_.top_y();
602
603                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
604                                              cmd.y + dim_.asc);
605                 // set the selection cursor!
606                 text_.selection.cursor = text_.cursor;
607                 text_.cursor.x_fix(text_.cursor.x());
608
609                 text_.clearSelection();
610                 updateLocal(bv, false);
611
612                 bv->owner()->setLayout(cpar()->layout()->name());
613
614                 // we moved the view we cannot do mouse selection in this case!
615                 if (getLyXText(bv)->top_y() != old_top_y)
616                         no_selection = true;
617                 old_par = cpar();
618                 // Insert primary selection with middle mouse
619                 // if there is a local selection in the current buffer,
620                 // insert this
621                 if (cmd.button() == mouse_button::button2) {
622                         if (paste_internally)
623                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
624                         else
625                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
626                 }
627         } else {
628                 getLyXText(bv)->clearSelection();
629         }
630 }
631
632
633 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
634 {
635         BufferView * bv = cmd.view();
636         FuncRequest cmd1 = cmd;
637         cmd1.x -= inset_x;
638         cmd1.y -= inset_y;
639
640         no_selection = true;
641         if (the_locking_inset)
642                 return the_locking_inset->localDispatch(cmd1);
643
644         int tmp_x = cmd.x - drawTextXOffset;
645         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
646         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
647         bool ret = false;
648         if (inset) {
649 // This code should probably be removed now. Simple insets
650 // (!highlyEditable) can actually take the localDispatch,
651 // and turn it into edit() if necessary. But we still
652 // need to deal properly with the whole relative vs.
653 // absolute mouse co-ords thing in a realiable, sensible way
654 #if 0
655                 if (isHighlyEditableInset(inset))
656                         ret = inset->localDispatch(cmd1);
657                 else {
658                         inset_x = cix(bv) - top_x + drawTextXOffset;
659                         inset_y = ciy() + drawTextYOffset;
660                         cmd1.x = cmd.x - inset_x;
661                         cmd1.y = cmd.x - inset_y;
662                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
663                         ret = true;
664                 }
665 #endif
666                 ret = inset->localDispatch(cmd1);
667                 updateLocal(bv, false);
668
669         }
670         return ret;
671 }
672
673
674 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
675 {
676         FuncRequest cmd1 = cmd;
677         cmd1.x -= inset_x;
678         cmd1.y -= inset_y;
679
680         if (the_locking_inset) {
681                 the_locking_inset->localDispatch(cmd1);
682                 return;
683         }
684
685         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
686                 return;
687
688         BufferView * bv = cmd.view();
689         LyXCursor cur = text_.cursor;
690         text_.setCursorFromCoordinates
691                 (cmd.x - drawTextXOffset, cmd.y + dim_.asc);
692         text_.cursor.x_fix(text_.cursor.x());
693         if (cur == text_.cursor)
694                 return;
695         text_.setSelection();
696         updateLocal(bv, false);
697 }
698
699
700 InsetOld::RESULT InsetText::localDispatch(FuncRequest const & cmd)
701 {
702         BufferView * bv = cmd.view();
703         setViewCache(bv);
704
705         switch (cmd.action) {
706         case LFUN_INSET_EDIT: {
707                 UpdatableInset::localDispatch(cmd);
708
709                 if (!bv->lockInset(this)) {
710                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
711                         return DISPATCHED;
712                 }
713
714                 locked = true;
715                 the_locking_inset = 0;
716                 inset_pos = 0;
717                 inset_x = 0;
718                 inset_y = 0;
719                 inset_boundary = false;
720                 inset_par = paragraphs.end();
721                 old_par = paragraphs.end();
722
723
724                 if (cmd.argument.size()) {
725                         if (cmd.argument == "left")
726                                 text_.setCursorIntern(paragraphs.begin(), 0);
727                         else {
728                                 ParagraphList::iterator it = boost::prior(paragraphs.end());
729                                 text_.setCursor(it, it->size());
730                         }
731                 } else {
732                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
733                         // we put here -1 and not button as now the button in the
734                         // edit call should not be needed we will fix this in 1.3.x
735                         // cycle hopefully (Jug 20020509)
736                         // FIXME: GUII I've changed this to none: probably WRONG
737                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
738                                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
739                                                                         cmd.y + dim_.asc);
740                                 text_.cursor.x_fix(text_.cursor.x());
741                         }
742                 }
743
744                 text_.clearSelection();
745                 finishUndo();
746
747                 // If the inset is empty set the language of the current font to the
748                 // language to the surronding text (if different).
749                 if (paragraphs.begin()->empty() &&
750                     paragraphs.size() == 1 &&
751                     bv->getParentLanguage(this) != text_.current_font.language())
752                 {
753                         LyXFont font(LyXFont::ALL_IGNORE);
754                         font.setLanguage(bv->getParentLanguage(this));
755                         setFont(bv, font, false);
756                 }
757
758                 updateLocal(bv, false);
759                 // Tell the paragraph dialog that we've entered an insettext.
760                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
761                 return DISPATCHED;
762         }
763
764         case LFUN_MOUSE_PRESS:
765                 lfunMousePress(cmd);
766                 return DISPATCHED;
767
768         case LFUN_MOUSE_MOTION:
769                 lfunMouseMotion(cmd);
770                 return DISPATCHED;
771
772         case LFUN_MOUSE_RELEASE:
773                 return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
774
775         default:
776                 break;
777         }
778
779         bool was_empty = paragraphs.begin()->empty() && paragraphs.size() == 1;
780         no_selection = false;
781
782         RESULT result = UpdatableInset::localDispatch(cmd);
783         if (result != UNDISPATCHED)
784                 return DISPATCHED;
785
786         result = DISPATCHED;
787         if (cmd.action < 0 && cmd.argument.empty())
788                 return FINISHED;
789
790         if (the_locking_inset) {
791                 result = the_locking_inset->localDispatch(cmd);
792                 if (result == DISPATCHED_NOUPDATE)
793                         return result;
794                 if (result == DISPATCHED) {
795                         updateLocal(bv, false);
796                         return result;
797                 }
798                 if (result >= FINISHED) {
799                         switch (result) {
800                         case FINISHED_RIGHT:
801                                 moveRightIntern(bv, false, false);
802                                 result = DISPATCHED;
803                                 break;
804                         case FINISHED_UP:
805                                 result = moveUp(bv);
806                                 if (result >= FINISHED) {
807                                         updateLocal(bv, false);
808                                         bv->unlockInset(this);
809                                 }
810                                 break;
811                         case FINISHED_DOWN:
812                                 result = moveDown(bv);
813                                 if (result >= FINISHED) {
814                                         updateLocal(bv, false);
815                                         bv->unlockInset(this);
816                                 }
817                                 break;
818                         default:
819                                 result = DISPATCHED;
820                                 break;
821                         }
822                         the_locking_inset = 0;
823                         updateLocal(bv, false);
824                         // make sure status gets reset immediately
825                         bv->owner()->clearMessage();
826                         return result;
827                 }
828         }
829         bool updflag = false;
830
831         switch (cmd.action) {
832
833         // Normal chars
834         case LFUN_SELFINSERT:
835                 if (bv->buffer()->isReadonly()) {
836 //          setErrorMessage(N_("Document is read only"));
837                         break;
838                 }
839                 if (!cmd.argument.empty()) {
840                         /* Automatically delete the currently selected
841                          * text and replace it with what is being
842                          * typed in now. Depends on lyxrc settings
843                          * "auto_region_delete", which defaults to
844                          * true (on). */
845 #if 0
846                         // This should not be needed here and is also WRONG!
847                         recordUndo(bv, Undo::INSERT, text_.cursor.par());
848 #endif
849                         bv->switchKeyMap();
850
851                         if (lyxrc.auto_region_delete && text_.selection.set())
852                                 text_.cutSelection(false, false);
853                         text_.clearSelection();
854
855                         for (string::size_type i = 0; i < cmd.argument.length(); ++i)
856                                 bv->owner()->getIntl().getTransManager().
857                                         TranslateAndInsert(cmd.argument[i], &text_);
858                 }
859                 text_.selection.cursor = text_.cursor;
860                 updflag = true;
861                 result = DISPATCHED_NOUPDATE;
862                 break;
863
864         // cursor movements that need special handling
865
866         case LFUN_RIGHT:
867                 result = moveRight(bv);
868                 finishUndo();
869                 break;
870         case LFUN_LEFT:
871                 finishUndo();
872                 result = moveLeft(bv);
873                 break;
874         case LFUN_DOWN:
875                 finishUndo();
876                 result = moveDown(bv);
877                 break;
878         case LFUN_UP:
879                 finishUndo();
880                 result = moveUp(bv);
881                 break;
882
883         case LFUN_PRIOR:
884                 if (crow() == text_.rows().begin())
885                         result = FINISHED_UP;
886                 else {
887                         text_.cursorPrevious();
888                         text_.clearSelection();
889                         result = DISPATCHED_NOUPDATE;
890                 }
891                 break;
892
893         case LFUN_NEXT:
894                 if (boost::next(crow()) == text_.rows().end())
895                         result = FINISHED_DOWN;
896                 else {
897                         text_.cursorNext();
898                         text_.clearSelection();
899                         result = DISPATCHED_NOUPDATE;
900                 }
901                 break;
902
903         case LFUN_BACKSPACE:
904                 if (text_.selection.set())
905                         text_.cutSelection(true, false);
906                 else
907                         text_.backspace();
908                 updflag = true;
909                 break;
910
911         case LFUN_DELETE:
912                 if (text_.selection.set())
913                         text_.cutSelection(true, false);
914                 else 
915                         text_.Delete();
916                 updflag = true;
917                 break;
918
919         case LFUN_PASTE: {
920                 if (!autoBreakRows) {
921                         if (CutAndPaste::nrOfParagraphs() > 1) {
922 #ifdef WITH_WARNINGS
923 #warning FIXME horrendously bad UI
924 #endif
925                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
926                                 break;
927                         }
928                 }
929
930                 replaceSelection(bv->getLyXText());
931                 size_t sel_index = 0;
932                 string const & arg = cmd.argument;
933                 if (isStrUnsignedInt(arg)) {
934                         size_t const paste_arg = strToUnsignedInt(arg);
935 #warning FIXME Check if the arg is in the domain of available selections.
936                         sel_index = paste_arg;
937                 }
938                 text_.pasteSelection(sel_index);
939                 // bug 393
940                 text_.clearSelection();
941                 updflag = true;
942                 break;
943         }
944
945         case LFUN_BREAKPARAGRAPH:
946                 if (!autoBreakRows) {
947                         result = DISPATCHED;
948                         break;
949                 }
950                 replaceSelection(bv->getLyXText());
951                 text_.breakParagraph(paragraphs, 0);
952                 updflag = true;
953                 break;
954
955         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
956                 if (!autoBreakRows) {
957                         result = DISPATCHED;
958                         break;
959                 }
960                 replaceSelection(bv->getLyXText());
961                 text_.breakParagraph(paragraphs, 1);
962                 updflag = true;
963                 break;
964
965         case LFUN_BREAKLINE: {
966                 if (!autoBreakRows) {
967                         result = DISPATCHED;
968                         break;
969                 }
970
971                 replaceSelection(bv->getLyXText());
972                 text_.insertInset(new InsetNewline);
973                 updflag = true;
974                 break;
975         }
976
977         case LFUN_LAYOUT:
978                 // do not set layouts on non breakable textinsets
979                 if (autoBreakRows) {
980                         string cur_layout = cpar()->layout()->name();
981
982                         // Derive layout number from given argument (string)
983                         // and current buffer's textclass (number). 
984                         LyXTextClass const & tclass =
985                                 bv->buffer()->params.getLyXTextClass();
986                         string layout = cmd.argument;
987                         bool hasLayout = tclass.hasLayout(layout);
988
989                         // If the entry is obsolete, use the new one instead.
990                         if (hasLayout) {
991                                 string const & obs = tclass[layout]->obsoleted_by();
992                                 if (!obs.empty())
993                                         layout = obs;
994                         }
995
996                         // see if we found the layout number:
997                         if (!hasLayout) {
998                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
999                                 bv->owner()->dispatch(lf);
1000                                 break;
1001                         }
1002
1003                         if (cur_layout != layout) {
1004                                 cur_layout = layout;
1005                                 text_.setLayout(layout);
1006                                 bv->owner()->setLayout(cpar()->layout()->name());
1007                                 updflag = true;
1008                         }
1009                 } else {
1010                         // reset the layout box
1011                         bv->owner()->setLayout(cpar()->layout()->name());
1012                 }
1013                 break;
1014
1015         default:
1016                 if (!bv->dispatch(cmd))
1017                         result = UNDISPATCHED;
1018                 break;
1019         }
1020
1021         updateLocal(bv, updflag);
1022
1023         /// If the action has deleted all text in the inset, we need to change the
1024         // language to the language of the surronding text.
1025         if (!was_empty && paragraphs.begin()->empty() &&
1026             paragraphs.size() == 1) {
1027                 LyXFont font(LyXFont::ALL_IGNORE);
1028                 font.setLanguage(bv->getParentLanguage(this));
1029                 setFont(bv, font, false);
1030         }
1031
1032         if (result >= FINISHED)
1033                 bv->unlockInset(this);
1034
1035         if (result == DISPATCHED_NOUPDATE)
1036                 result = DISPATCHED;
1037         return result;
1038 }
1039
1040
1041 int InsetText::latex(Buffer const * buf, ostream & os,
1042                      LatexRunParams const & runparams) const
1043 {
1044         TexRow texrow;
1045         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1046         return texrow.rows();
1047 }
1048
1049
1050 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1051 {
1052         unsigned int lines = 0;
1053
1054         ParagraphList::const_iterator beg = paragraphs.begin();
1055         ParagraphList::const_iterator end = paragraphs.end();
1056         ParagraphList::const_iterator it = beg;
1057         for (; it != end; ++it) {
1058                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1059                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1060                 os << tmp;
1061         }
1062         return lines;
1063 }
1064
1065
1066 int InsetText::linuxdoc(Buffer const * buf, ostream & os) const
1067 {
1068         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1069         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1070
1071         // There is a confusion between the empty paragraph and the default paragraph
1072         // The default paragraph is <p></p>, the empty paragraph is *empty*
1073         // Since none of the floats of linuxdoc accepts standard paragraphs
1074         // I disable them. I don't expect problems. (jamatos 2003/07/27)
1075         for (; pit != pend; ++pit) {
1076                 const string name = pit->layout()->latexname();
1077                 if (name != "p")
1078                         sgml::openTag(os, 1, 0, name);
1079                 buf->simpleLinuxDocOnePar(os, pit, 0);
1080                 if (name != "p")
1081                         sgml::closeTag(os, 1, 0, name);
1082         }
1083         return 0;
1084 }
1085
1086
1087 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1088 {
1089         unsigned int lines = 0;
1090
1091         vector<string> environment_stack(10);
1092         vector<string> environment_inner(10);
1093
1094         int const command_depth = 0;
1095         string item_name;
1096
1097         Paragraph::depth_type depth = 0; // paragraph depth
1098
1099         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1100         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1101
1102         for (; pit != pend; ++pit) {
1103                 int desc_on = 0; // description mode
1104
1105                 LyXLayout_ptr const & style = pit->layout();
1106
1107                 // environment tag closing
1108                 for (; depth > pit->params().depth(); --depth) {
1109                         if (environment_inner[depth] != "!-- --") {
1110                                 item_name = "listitem";
1111                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1112                                 if (environment_inner[depth] == "varlistentry")
1113                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1114                         }
1115                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1116                         environment_stack[depth].erase();
1117                         environment_inner[depth].erase();
1118                 }
1119
1120                 if (depth == pit->params().depth()
1121                    && environment_stack[depth] != style->latexname()
1122                    && !environment_stack[depth].empty()) {
1123                         if (environment_inner[depth] != "!-- --") {
1124                                 item_name= "listitem";
1125                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1126                                 if (environment_inner[depth] == "varlistentry")
1127                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1128                         }
1129
1130                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1131
1132                         environment_stack[depth].erase();
1133                         environment_inner[depth].erase();
1134                 }
1135
1136                 // Write opening SGML tags.
1137                 switch (style->latextype) {
1138                 case LATEX_PARAGRAPH:
1139                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1140                         break;
1141
1142                 case LATEX_COMMAND:
1143                         buf->error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1144                         return -1;
1145                         break;
1146
1147                 case LATEX_ENVIRONMENT:
1148                 case LATEX_ITEM_ENVIRONMENT:
1149                         if (depth < pit->params().depth()) {
1150                                 depth = pit->params().depth();
1151                                 environment_stack[depth].erase();
1152                         }
1153
1154                         if (environment_stack[depth] != style->latexname()) {
1155                                 if (environment_stack.size() == depth + 1) {
1156                                         environment_stack.push_back("!-- --");
1157                                         environment_inner.push_back("!-- --");
1158                                 }
1159                                 environment_stack[depth] = style->latexname();
1160                                 environment_inner[depth] = "!-- --";
1161                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1162                         } else {
1163                                 if (environment_inner[depth] != "!-- --") {
1164                                         item_name= "listitem";
1165                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1166                                         if (environment_inner[depth] == "varlistentry")
1167                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1168                                 }
1169                         }
1170
1171                         if (style->latextype == LATEX_ENVIRONMENT) {
1172                                 if (!style->latexparam().empty()) {
1173                                         if (style->latexparam() == "CDATA")
1174                                                 os << "<![CDATA[";
1175                                         else
1176                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1177                                 }
1178                                 break;
1179                         }
1180
1181                         desc_on = (style->labeltype == LABEL_MANUAL);
1182
1183                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1184                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1185
1186                         item_name = desc_on ? "term" : "para";
1187                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1188
1189                         break;
1190                 default:
1191                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1192                         break;
1193                 }
1194
1195                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1196
1197                 string end_tag;
1198                 // write closing SGML tags
1199                 switch (style->latextype) {
1200                 case LATEX_ENVIRONMENT:
1201                         if (!style->latexparam().empty()) {
1202                                 if (style->latexparam() == "CDATA")
1203                                         os << "]]>";
1204                                 else
1205                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1206                         }
1207                         break;
1208                 case LATEX_ITEM_ENVIRONMENT:
1209                         if (desc_on == 1)
1210                                 break;
1211                         end_tag= "para";
1212                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1213                         break;
1214                 case LATEX_PARAGRAPH:
1215                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1216                         break;
1217                 default:
1218                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1219                         break;
1220                 }
1221         }
1222
1223         // Close open tags
1224         for (int d = depth; d >= 0; --d) {
1225                 if (!environment_stack[depth].empty()) {
1226                         if (environment_inner[depth] != "!-- --") {
1227                                 item_name = "listitem";
1228                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1229                                if (environment_inner[depth] == "varlistentry")
1230                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1231                         }
1232
1233                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1234                 }
1235         }
1236
1237         return lines;
1238 }
1239
1240
1241 void InsetText::validate(LaTeXFeatures & features) const
1242 {
1243         for_each(paragraphs.begin(), paragraphs.end(),
1244                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1245 }
1246
1247
1248 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1249 {
1250         if (the_locking_inset) {
1251                 the_locking_inset->getCursor(bv, x, y);
1252                 return;
1253         }
1254         x = cx();
1255         y = cy() + InsetText::y();
1256 }
1257
1258
1259 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1260 {
1261         if (the_locking_inset) {
1262                 the_locking_inset->getCursorPos(bv, x, y);
1263                 return;
1264         }
1265         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1266         y = cy() - TEXT_TO_INSET_OFFSET;
1267 }
1268
1269
1270 int InsetText::insetInInsetY() const
1271 {
1272         if (!the_locking_inset)
1273                 return 0;
1274
1275         return inset_y + the_locking_inset->insetInInsetY();
1276 }
1277
1278
1279 void InsetText::fitInsetCursor(BufferView * bv) const
1280 {
1281         if (the_locking_inset) {
1282                 the_locking_inset->fitInsetCursor(bv);
1283                 return;
1284         }
1285
1286         LyXFont const font = text_.getFont(cpar(), cpos());
1287
1288         int const asc = font_metrics::maxAscent(font);
1289         int const desc = font_metrics::maxDescent(font);
1290
1291         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1292 }
1293
1294
1295 InsetOld::RESULT InsetText::moveRight(BufferView * bv)
1296 {
1297         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1298                 return moveLeftIntern(bv, false, true, false);
1299         else
1300                 return moveRightIntern(bv, true, true, false);
1301 }
1302
1303
1304 InsetOld::RESULT InsetText::moveLeft(BufferView * bv)
1305 {
1306         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1307                 return moveRightIntern(bv, true, true, false);
1308         else
1309                 return moveLeftIntern(bv, false, true, false);
1310 }
1311
1312
1313 InsetOld::RESULT
1314 InsetText::moveRightIntern(BufferView * bv, bool front,
1315                            bool activate_inset, bool selecting)
1316 {
1317         ParagraphList::iterator c_par = cpar();
1318
1319         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1320                 return FINISHED_RIGHT;
1321         if (activate_inset && checkAndActivateInset(bv, front))
1322                 return DISPATCHED;
1323         text_.cursorRight(bv);
1324         if (!selecting)
1325                 text_.clearSelection();
1326         return DISPATCHED_NOUPDATE;
1327 }
1328
1329
1330 InsetOld::RESULT
1331 InsetText::moveLeftIntern(BufferView * bv, bool front,
1332                           bool activate_inset, bool selecting)
1333 {
1334         if (cpar() == paragraphs.begin() && cpos() <= 0)
1335                 return FINISHED;
1336         text_.cursorLeft(bv);
1337         if (!selecting)
1338                 text_.clearSelection();
1339         if (activate_inset && checkAndActivateInset(bv, front))
1340                 return DISPATCHED;
1341         return DISPATCHED_NOUPDATE;
1342 }
1343
1344
1345 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1346 {
1347         if (crow() == text_.rows().begin())
1348                 return FINISHED_UP;
1349         text_.cursorUp(bv);
1350         text_.clearSelection();
1351         return DISPATCHED_NOUPDATE;
1352 }
1353
1354
1355 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1356 {
1357         if (boost::next(crow()) == text_.rows().end())
1358                 return FINISHED_DOWN;
1359         text_.cursorDown(bv);
1360         text_.clearSelection();
1361         return DISPATCHED_NOUPDATE;
1362 }
1363
1364
1365 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1366 {
1367         if (the_locking_inset) {
1368                 if (the_locking_inset->insetAllowed(inset))
1369                         return the_locking_inset->insertInset(bv, inset);
1370                 return false;
1371         }
1372         inset->setOwner(this);
1373         text_.insertInset(inset);
1374         bv->fitCursor();
1375         updateLocal(bv, true);
1376         return true;
1377 }
1378
1379
1380 bool InsetText::insetAllowed(InsetOld::Code code) const
1381 {
1382         // in_insetAllowed is a really gross hack,
1383         // to allow us to call the owner's insetAllowed
1384         // without stack overflow, which can happen
1385         // when the owner uses InsetCollapsable::insetAllowed()
1386         bool ret = true;
1387         if (in_insetAllowed)
1388                 return ret;
1389         in_insetAllowed = true;
1390         if (the_locking_inset)
1391                 ret = the_locking_inset->insetAllowed(code);
1392         else if (owner())
1393                 ret = owner()->insetAllowed(code);
1394         in_insetAllowed = false;
1395         return ret;
1396 }
1397
1398
1399 UpdatableInset * InsetText::getLockingInset() const
1400 {
1401         return the_locking_inset ? the_locking_inset->getLockingInset() :
1402                 const_cast<InsetText *>(this);
1403 }
1404
1405
1406 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1407 {
1408         if (c == lyxCode())
1409                 return this;
1410         if (the_locking_inset)
1411                 return the_locking_inset->getFirstLockingInsetOfType(c);
1412         return 0;
1413 }
1414
1415
1416 bool InsetText::showInsetDialog(BufferView * bv) const
1417 {
1418         if (the_locking_inset)
1419                 return the_locking_inset->showInsetDialog(bv);
1420         return false;
1421 }
1422
1423
1424 void InsetText::getLabelList(std::vector<string> & list) const
1425 {
1426         ParagraphList::const_iterator pit = paragraphs.begin();
1427         ParagraphList::const_iterator pend = paragraphs.end();
1428         for (; pit != pend; ++pit) {
1429                 InsetList::const_iterator beg = pit->insetlist.begin();
1430                 InsetList::const_iterator end = pit->insetlist.end();
1431                 for (; beg != end; ++beg)
1432                         beg->inset->getLabelList(list);
1433         }
1434 }
1435
1436
1437 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1438                         bool selectall)
1439 {
1440         if (the_locking_inset) {
1441                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1442                 return;
1443         }
1444
1445         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1446             || cpar()->empty()) {
1447                 text_.setFont(font, toggleall);
1448                 return;
1449         }
1450
1451
1452         if (text_.selection.set())
1453                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1454
1455         if (selectall) {
1456                 text_.cursorTop();
1457                 text_.selection.cursor = text_.cursor;
1458                 text_.cursorBottom();
1459                 text_.setSelection();
1460         }
1461
1462         text_.toggleFree(font, toggleall);
1463
1464         if (selectall)
1465                 text_.clearSelection();
1466
1467         bv->fitCursor();
1468         updateLocal(bv, true);
1469 }
1470
1471
1472 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1473 {
1474         InsetOld * inset = cpar()->getInset(cpos());
1475         if (!isHighlyEditableInset(inset))
1476                 return false;
1477         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1478         inset->localDispatch(cmd);
1479         if (!the_locking_inset)
1480                 return false;
1481         updateLocal(bv, false);
1482         return true;
1483 }
1484
1485
1486 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1487                                       mouse_button::state button)
1488 {
1489         x -= drawTextXOffset;
1490         int dummyx = x;
1491         int dummyy = y + dim_.asc;
1492         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1493         // we only do the edit() call if the inset was hit by the mouse
1494         // or if it is a highly editable inset. So we should call this
1495         // function from our own edit with button < 0.
1496         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1497         // WRONG
1498         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1499                 return false;
1500
1501         if (!inset)
1502                 return false;
1503         if (x < 0)
1504                 x = dim_.wid;
1505         if (y < 0)
1506                 y = dim_.des;
1507         inset_x = cix() - top_x + drawTextXOffset;
1508         inset_y = ciy() + drawTextYOffset;
1509         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1510         inset->localDispatch(cmd);
1511         if (!the_locking_inset)
1512                 return false;
1513         updateLocal(bv, false);
1514         return true;
1515 }
1516
1517
1518 void InsetText::markNew(bool track_changes)
1519 {
1520         ParagraphList::iterator pit = paragraphs.begin();
1521         ParagraphList::iterator end = paragraphs.end();
1522         for (; pit != end; ++pit) {
1523                 if (track_changes) {
1524                         pit->trackChanges();
1525                 } else {
1526                         // no-op when not tracking
1527                         pit->cleanChanges();
1528                 }
1529         }
1530 }
1531
1532
1533 void InsetText::setText(string const & data, LyXFont const & font)
1534 {
1535         clear(false);
1536         for (unsigned int i = 0; i < data.length(); ++i)
1537                 paragraphs.begin()->insertChar(i, data[i], font);
1538         reinitLyXText();
1539 }
1540
1541
1542 void InsetText::setAutoBreakRows(bool flag)
1543 {
1544         if (flag != autoBreakRows) {
1545                 autoBreakRows = flag;
1546                 if (!flag)
1547                         removeNewlines();
1548         }
1549 }
1550
1551
1552 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1553 {
1554         if (how != drawFrame_) {
1555                 drawFrame_ = how;
1556                 updateLocal(bv, false);
1557         }
1558 }
1559
1560
1561 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
1562 {
1563         if (frame_color != col) {
1564                 frame_color = col;
1565                 updateLocal(bv, false);
1566         }
1567 }
1568
1569
1570 int InsetText::cx() const
1571 {
1572         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1573         if (the_locking_inset) {
1574                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1575                 if (font.isVisibleRightToLeft())
1576                         x -= the_locking_inset->width();
1577         }
1578         return x;
1579 }
1580
1581
1582 int InsetText::cix() const
1583 {
1584         int x = text_.cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
1585         if (the_locking_inset) {
1586                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1587                 if (font.isVisibleRightToLeft())
1588                         x -= the_locking_inset->width();
1589         }
1590         return x;
1591 }
1592
1593
1594 int InsetText::cy() const
1595 {
1596         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1597 }
1598
1599
1600 int InsetText::ciy() const
1601 {
1602         return text_.cursor.iy() - dim_.asc + TEXT_TO_INSET_OFFSET;
1603 }
1604
1605
1606 pos_type InsetText::cpos() const
1607 {
1608         return text_.cursor.pos();
1609 }
1610
1611
1612 ParagraphList::iterator InsetText::cpar() const
1613 {
1614         return text_.cursor.par();
1615 }
1616
1617
1618 bool InsetText::cboundary() const
1619 {
1620         return text_.cursor.boundary();
1621 }
1622
1623
1624 RowList::iterator InsetText::crow() const
1625 {
1626         return text_.cursorRow();
1627 }
1628
1629
1630 LyXText * InsetText::getLyXText(BufferView const * bv,
1631                                 bool const recursive) const
1632 {
1633         setViewCache(bv);
1634         if (recursive && the_locking_inset)
1635                 return the_locking_inset->getLyXText(bv, true);
1636         return &text_;
1637 }
1638
1639
1640 void InsetText::setViewCache(BufferView const * bv) const
1641 {
1642         if (bv)
1643                 text_.bv_owner = const_cast<BufferView *>(bv);
1644 }
1645
1646
1647 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1648 {
1649         if (recursive) {
1650                 /// then remove all LyXText in text-insets
1651                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1652                          const_cast<ParagraphList&>(paragraphs).end(),
1653                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1654         }
1655 }
1656
1657
1658 void InsetText::resizeLyXText(BufferView * bv, bool /*force*/) const
1659 {
1660         if (paragraphs.size() == 1 && paragraphs.begin()->empty())
1661                 return;
1662
1663         if (!bv)
1664                 return;
1665
1666         Assert(bv);
1667         setViewCache(bv);
1668
1669         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1670                  const_cast<ParagraphList&>(paragraphs).end(),
1671                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1672
1673         saveLyXTextState();
1674         text_.init(bv);
1675         restoreLyXTextState();
1676
1677         // seems to be unneeded
1678 #if 1
1679         if (the_locking_inset) {
1680                 inset_x = cix() - top_x + drawTextXOffset;
1681                 inset_y = ciy() + drawTextYOffset;
1682         }
1683 #endif
1684
1685 #if 0
1686         text_.top_y(bv->screen().topCursorVisible(&text_));
1687         if (!owner()) {
1688                 const_cast<InsetText*>(this)->updateLocal(bv, false);
1689                 // this will scroll the screen such that the cursor becomes visible
1690                 bv->updateScrollbar();
1691         }
1692 #endif
1693 }
1694
1695
1696 void InsetText::reinitLyXText() const
1697 {
1698         BufferView * bv = text_.bv_owner;
1699
1700         if (!bv)
1701                 return;
1702
1703         saveLyXTextState();
1704
1705         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1706                  const_cast<ParagraphList&>(paragraphs).end(),
1707                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1708
1709         text_.init(bv);
1710         restoreLyXTextState();
1711         if (the_locking_inset) {
1712                 inset_x = cix() - top_x + drawTextXOffset;
1713                 inset_y = ciy() + drawTextYOffset;
1714         }
1715         text_.top_y(bv->screen().topCursorVisible(&text_));
1716         if (!owner()) {
1717                 // this will scroll the screen such that the cursor becomes visible
1718                 bv->updateScrollbar();
1719         }
1720 }
1721
1722
1723 void InsetText::removeNewlines()
1724 {
1725         bool changed = false;
1726
1727         ParagraphList::iterator it = paragraphs.begin();
1728         ParagraphList::iterator end = paragraphs.end();
1729         for (; it != end; ++it) {
1730                 for (int i = 0; i < it->size(); ++i) {
1731                         if (it->isNewline(i)) {
1732                                 changed = true;
1733                                 it->erase(i);
1734                         }
1735                 }
1736         }
1737         if (changed)
1738                 reinitLyXText();
1739 }
1740
1741
1742 int InsetText::scroll(bool recursive) const
1743 {
1744         int sx = UpdatableInset::scroll(false);
1745
1746         if (recursive && the_locking_inset)
1747                 sx += the_locking_inset->scroll(recursive);
1748
1749         return sx;
1750 }
1751
1752
1753 void InsetText::clearSelection(BufferView * bv)
1754 {
1755         getLyXText(bv)->clearSelection();
1756 }
1757
1758
1759 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1760 {
1761         Painter & pain = bv->painter();
1762         int w = dim_.wid;
1763         int h = dim_.asc + dim_.des;
1764         int ty = baseline - dim_.asc;
1765
1766         if (ty < 0) {
1767                 h += ty;
1768                 ty = 0;
1769         }
1770         if (ty + h > pain.paperHeight())
1771                 h = pain.paperHeight();
1772         if (top_x + drawTextXOffset + w > pain.paperWidth())
1773                 w = pain.paperWidth();
1774         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1775 }
1776
1777
1778 ParagraphList * InsetText::getParagraphs(int i) const
1779 {
1780         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1781 }
1782
1783
1784 LyXCursor const & InsetText::cursor(BufferView * bv) const
1785 {
1786         if (the_locking_inset)
1787                 return the_locking_inset->cursor(bv);
1788         return getLyXText(bv)->cursor;
1789 }
1790
1791
1792 InsetOld * InsetText::getInsetFromID(int id_arg) const
1793 {
1794         if (id_arg == id())
1795                 return const_cast<InsetText *>(this);
1796
1797         ParagraphList::const_iterator pit = paragraphs.begin();
1798         ParagraphList::const_iterator pend = paragraphs.end();
1799         for (; pit != pend; ++pit) {
1800                 InsetList::const_iterator it = pit->insetlist.begin();
1801                 InsetList::const_iterator end = pit->insetlist.end();
1802                 for (; it != end; ++it) {
1803                         if (it->inset->id() == id_arg)
1804                                 return it->inset;
1805                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1806                         if (in)
1807                                 return in;
1808                 }
1809         }
1810         return 0;
1811 }
1812
1813
1814 WordLangTuple const
1815 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1816 {
1817         WordLangTuple word;
1818         if (the_locking_inset) {
1819                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1820                 if (!word.word().empty()) {
1821                         value += cy();
1822                         return word;
1823                 }
1824                 // we have to go on checking so move cursor to the next char
1825                 text_.cursor.pos(text_.cursor.pos() + 1);
1826         }
1827         word = text_.selectNextWordToSpellcheck(value);
1828         if (word.word().empty())
1829                 bv->unlockInset(const_cast<InsetText *>(this));
1830         else
1831                 value = cy();
1832         return word;
1833 }
1834
1835
1836 void InsetText::selectSelectedWord(BufferView * bv)
1837 {
1838         if (the_locking_inset) {
1839                 the_locking_inset->selectSelectedWord(bv);
1840                 return;
1841         }
1842         getLyXText(bv)->selectSelectedWord();
1843         updateLocal(bv, false);
1844 }
1845
1846
1847 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1848 {
1849         if (the_locking_inset) {
1850                 if (the_locking_inset->nextChange(bv, length))
1851                         return true;
1852                 text_.cursorRight(true);
1853         }
1854         lyx::find::SearchResult result =
1855                 lyx::find::findNextChange(bv, &text_, length);
1856
1857         if (result == lyx::find::SR_FOUND) {
1858                 LyXCursor cur = text_.cursor;
1859                 bv->unlockInset(bv->theLockingInset());
1860                 if (bv->lockInset(this))
1861                         locked = true;
1862                 text_.cursor = cur;
1863                 text_.setSelectionRange(length);
1864                 updateLocal(bv, false);
1865         }
1866         return result != lyx::find::SR_NOT_FOUND;
1867 }
1868
1869
1870 bool InsetText::searchForward(BufferView * bv, string const & str,
1871                               bool cs, bool mw)
1872 {
1873         if (the_locking_inset) {
1874                 if (the_locking_inset->searchForward(bv, str, cs, mw))
1875                         return true;
1876                 text_.cursorRight(true);
1877         }
1878         lyx::find::SearchResult result =
1879                 lyx::find::find(bv, &text_, str, true, cs, mw);
1880
1881         if (result == lyx::find::SR_FOUND) {
1882                 LyXCursor cur = text_.cursor;
1883                 bv->unlockInset(bv->theLockingInset());
1884                 if (bv->lockInset(this))
1885                         locked = true;
1886                 text_.cursor = cur;
1887                 text_.setSelectionRange(str.length());
1888                 updateLocal(bv, false);
1889         }
1890         return result != lyx::find::SR_NOT_FOUND;
1891 }
1892
1893
1894 bool InsetText::searchBackward(BufferView * bv, string const & str,
1895                                bool cs, bool mw)
1896 {
1897         if (the_locking_inset) {
1898                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
1899                         return true;
1900         }
1901         if (!locked) {
1902                 ParagraphList::iterator pit = paragraphs.begin();
1903                 ParagraphList::iterator pend = paragraphs.end();
1904
1905                 while (boost::next(pit) != pend)
1906                         ++pit;
1907
1908                 text_.setCursor(pit, pit->size());
1909         }
1910         lyx::find::SearchResult result =
1911                 lyx::find::find(bv, &text_, str, false, cs, mw);
1912
1913         if (result == lyx::find::SR_FOUND) {
1914                 LyXCursor cur = text_.cursor;
1915                 bv->unlockInset(bv->theLockingInset());
1916                 if (bv->lockInset(this))
1917                         locked = true;
1918                 text_.cursor = cur;
1919                 text_.setSelectionRange(str.length());
1920                 updateLocal(bv, false);
1921         }
1922         return result != lyx::find::SR_NOT_FOUND;
1923 }
1924
1925
1926 bool InsetText::checkInsertChar(LyXFont & font)
1927 {
1928         return owner() ? owner()->checkInsertChar(font) : true;
1929 }
1930
1931
1932 void InsetText::collapseParagraphs(BufferView * bv)
1933 {
1934         while (paragraphs.size() > 1) {
1935                 ParagraphList::iterator first_par = paragraphs.begin();
1936                 ParagraphList::iterator next_par = boost::next(first_par);
1937                 size_t const first_par_size = first_par->size();
1938
1939                 if (!first_par->empty() &&
1940                     !next_par->empty() &&
1941                     !first_par->isSeparator(first_par_size - 1)) {
1942                         first_par->insertChar(first_par_size, ' ');
1943                 }
1944
1945                 if (text_.selection.set()) {
1946                         if (text_.selection.start.par() == next_par) {
1947                                 text_.selection.start.par(first_par);
1948                                 text_.selection.start.pos(
1949                                         text_.selection.start.pos() + first_par_size);
1950                         }
1951                         if (text_.selection.end.par() == next_par) {
1952                                 text_.selection.end.par(first_par);
1953                                 text_.selection.end.pos(
1954                                         text_.selection.end.pos() + first_par_size);
1955                         }
1956                 }
1957
1958                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
1959         }
1960         reinitLyXText();
1961 }
1962
1963
1964 void InsetText::getDrawFont(LyXFont & font) const
1965 {
1966         if (!owner())
1967                 return;
1968         owner()->getDrawFont(font);
1969 }
1970
1971
1972 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
1973 {
1974 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
1975 // And it probably does. You have to take a look at this John. (Lgb)
1976 #warning John, have a look here. (Lgb)
1977         ParagraphList::iterator pit = plist.begin();
1978         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
1979         ++pit;
1980         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
1981
1982         ParagraphList::iterator pend = plist.end();
1983         for (; pit != pend; ++pit)
1984                 paragraphs.push_back(*pit);
1985
1986         reinitLyXText();
1987 }
1988
1989
1990 void InsetText::addPreview(PreviewLoader & loader) const
1991 {
1992         ParagraphList::const_iterator pit = paragraphs.begin();
1993         ParagraphList::const_iterator pend = paragraphs.end();
1994
1995         for (; pit != pend; ++pit) {
1996                 InsetList::const_iterator it  = pit->insetlist.begin();
1997                 InsetList::const_iterator end = pit->insetlist.end();
1998                 for (; it != end; ++it)
1999                         it->inset->addPreview(loader);
2000         }
2001 }