]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
b538fc064945dee951b2080e0a36636cb6df5ddc
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "debug.h"
27 #include "DispatchResult.h"
28 #include "EmbeddedFiles.h"
29 #include "ErrorList.h"
30 #include "factory.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "gettext.h"
35 #include "Intl.h"
36 #include "InsetIterator.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "LyXRC.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "Session.h"
50 #include "Text.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
53 #include "TexRow.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/Delegates.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/FontMetrics.h"
67 #include "frontends/Painter.h"
68 #include "frontends/Selection.h"
69
70 #include "graphics/Previews.h"
71
72 #include "support/convert.h"
73 #include "support/FileFilterList.h"
74 #include "support/filetools.h"
75 #include "support/Package.h"
76 #include "support/types.h"
77 #include "support/fs_extras.h"
78
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
81 #include <boost/next_prior.hpp>
82 #include <boost/filesystem/operations.hpp>
83
84 #include <cerrno>
85 #include <fstream>
86 #include <functional>
87 #include <vector>
88
89 using std::distance;
90 using std::endl;
91 using std::ifstream;
92 using std::istringstream;
93 using std::istream_iterator;
94 using std::make_pair;
95 using std::min;
96 using std::max;
97 using std::mem_fun_ref;
98 using std::string;
99 using std::vector;
100
101 namespace fs = boost::filesystem;
102
103 namespace lyx {
104
105 using support::addPath;
106 using support::bformat;
107 using support::FileFilterList;
108 using support::FileName;
109 using support::fileSearch;
110 using support::makeDisplayPath;
111 using support::makeAbsPath;
112 using support::package;
113
114 namespace Alert = frontend::Alert;
115
116 namespace {
117
118 /// Return an inset of this class if it exists at the current cursor position
119 template <class T>
120 T * getInsetByCode(Cursor const & cur, InsetCode code)
121 {
122         DocIterator it = cur;
123         Inset * inset = it.nextInset();
124         if (inset && inset->lyxCode() == code)
125                 return static_cast<T*>(inset);
126         return 0;
127 }
128
129
130 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
131         bool same_content);
132
133 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
134         docstring const & contents)
135 {
136         DocIterator tmpdit = dit;
137
138         while (tmpdit) {
139                 Inset const * inset = tmpdit.nextInset();
140                 if (inset
141                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
142                     && (contents.empty() ||
143                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
144                         dit = tmpdit;
145                         return true;
146                 }
147                 tmpdit.forwardInset();
148         }
149
150         return false;
151 }
152
153
154 /// Looks for next inset with one of the given codes.
155 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
156         bool same_content)
157 {
158         docstring contents;
159         DocIterator tmpdit = dit;
160         tmpdit.forwardInset();
161         if (!tmpdit)
162                 return false;
163
164         if (same_content) {
165                 Inset const * inset = tmpdit.nextInset();
166                 if (inset
167                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
168                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
169                 }
170         }
171
172         if (!findNextInset(tmpdit, codes, contents)) {
173                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
174                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
175                         if (!findNextInset(tmpdit, codes, contents))
176                                 return false;
177                 } else
178                         return false;
179         }
180
181         dit = tmpdit;
182         return true;
183 }
184
185
186 /// Looks for next inset with the given code
187 void findInset(DocIterator & dit, InsetCode code, bool same_content)
188 {
189         findInset(dit, vector<InsetCode>(1, code), same_content);
190 }
191
192
193 /// Moves cursor to the next inset with one of the given codes.
194 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
195                bool same_content)
196 {
197         Cursor tmpcur = bv->cursor();
198         if (!findInset(tmpcur, codes, same_content)) {
199                 bv->cursor().message(_("No more insets"));
200                 return;
201         }
202
203         tmpcur.clearSelection();
204         bv->setCursor(tmpcur);
205 }
206
207
208 /// Moves cursor to the next inset with given code.
209 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
210 {
211         gotoInset(bv, vector<InsetCode>(1, code), same_content);
212 }
213
214
215
216 /// the type of outline operation
217 enum OutlineOp {
218         OutlineUp, // Move this header with text down
219         OutlineDown,   // Move this header with text up
220         OutlineIn, // Make this header deeper
221         OutlineOut // Make this header shallower
222 };
223
224
225 void outline(OutlineOp mode, Cursor & cur)
226 {
227         Buffer & buf = cur.buffer();
228         pit_type & pit = cur.pit();
229         ParagraphList & pars = buf.text().paragraphs();
230         ParagraphList::iterator bgn = pars.begin();
231         // The first paragraph of the area to be copied:
232         ParagraphList::iterator start = boost::next(bgn, pit);
233         // The final paragraph of area to be copied:
234         ParagraphList::iterator finish = start;
235         ParagraphList::iterator end = pars.end();
236
237         TextClass::const_iterator lit =
238                 buf.params().getTextClass().begin();
239         TextClass::const_iterator const lend =
240                 buf.params().getTextClass().end();
241
242         int const thistoclevel = start->layout()->toclevel;
243         int toclevel;
244         switch (mode) {
245                 case OutlineUp: {
246                         // Move out (down) from this section header
247                         if (finish != end)
248                                 ++finish;
249                         // Seek the one (on same level) below
250                         for (; finish != end; ++finish) {
251                                 toclevel = finish->layout()->toclevel;
252                                 if (toclevel != Layout::NOT_IN_TOC
253                                     && toclevel <= thistoclevel) {
254                                         break;
255                                 }
256                         }
257                         ParagraphList::iterator dest = start;
258                         // Move out (up) from this header
259                         if (dest == bgn)
260                                 break;
261                         // Search previous same-level header above
262                         do {
263                                 --dest;
264                                 toclevel = dest->layout()->toclevel;
265                         } while(dest != bgn
266                                 && (toclevel == Layout::NOT_IN_TOC
267                                     || toclevel > thistoclevel));
268                         // Not found; do nothing
269                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
270                                 break;
271                         pit_type const newpit = std::distance(bgn, dest);
272                         pit_type const len = std::distance(start, finish);
273                         pit_type const deletepit = pit + len;
274                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
275                         pars.insert(dest, start, finish);
276                         start = boost::next(pars.begin(), deletepit);
277                         pit = newpit;
278                         pars.erase(start, finish);
279                         break;
280                 }
281                 case OutlineDown: {
282                         // Go down out of current header:
283                         if (finish != end)
284                                 ++finish;
285                         // Find next same-level header:
286                         for (; finish != end; ++finish) {
287                                 toclevel = finish->layout()->toclevel;
288                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
289                                         break;
290                         }
291                         ParagraphList::iterator dest = finish;
292                         // Go one down from *this* header:
293                         if (dest != end)
294                                 ++dest;
295                         else
296                                 break;
297                         // Go further down to find header to insert in front of:
298                         for (; dest != end; ++dest) {
299                                 toclevel = dest->layout()->toclevel;
300                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
301                                         break;
302                         }
303                         // One such was found:
304                         pit_type newpit = std::distance(bgn, dest);
305                         pit_type const len = std::distance(start, finish);
306                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
307                         pars.insert(dest, start, finish);
308                         start = boost::next(bgn, pit);
309                         pit = newpit - len;
310                         pars.erase(start, finish);
311                         break;
312                 }
313                 case OutlineIn:
314                         buf.undo().recordUndo(cur);
315                         for (; lit != lend; ++lit) {
316                                 if ((*lit)->toclevel == thistoclevel + 1 &&
317                                     start->layout()->labeltype == (*lit)->labeltype) {
318                                         start->layout((*lit));
319                                         break;
320                                 }
321                         }
322                         break;
323                 case OutlineOut:
324                         buf.undo().recordUndo(cur);
325                         for (; lit != lend; ++lit) {
326                                 if ((*lit)->toclevel == thistoclevel - 1 &&
327                                     start->layout()->labeltype == (*lit)->labeltype) {
328                                         start->layout((*lit));
329                                         break;
330                                 }
331                         }
332                         break;
333                 default:
334                         break;
335         }
336 }
337
338 /// A map from a Text to the associated text metrics
339 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
340
341 } // anon namespace
342
343
344 /////////////////////////////////////////////////////////////////////
345 //
346 // BufferView
347 //
348 /////////////////////////////////////////////////////////////////////
349
350 struct BufferView::Private
351 {
352         Private(BufferView & bv): wh_(0), cursor_(bv),
353                 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
354                 need_centering_(false), last_inset_(0), gui_(0)
355         {}
356
357         ///
358         ScrollbarParameters scrollbarParameters_;
359         ///
360         ViewMetricsInfo metrics_info_;
361         ///
362         CoordCache coord_cache_;
363
364         /// Estimated average par height for scrollbar.
365         int wh_;
366         /// this is used to handle XSelection events in the right manner.
367         struct {
368                 CursorSlice cursor;
369                 CursorSlice anchor;
370                 bool set;
371         } xsel_cache_;
372         ///
373         Cursor cursor_;
374         ///
375         bool multiparsel_cache_;
376         ///
377         pit_type anchor_ref_;
378         ///
379         int offset_ref_;
380         ///
381         bool need_centering_;
382
383         /// keyboard mapping object.
384         Intl intl_;
385
386         /// last visited inset.
387         /** kept to send setMouseHover(false).
388           * Not owned, so don't delete.
389           */
390         Inset * last_inset_;
391
392         mutable TextMetricsCache text_metrics_;
393
394         /// Whom to notify.
395         /** Not owned, so don't delete.
396           */
397         frontend::GuiBufferViewDelegate * gui_;
398 };
399
400
401 BufferView::BufferView(Buffer & buf)
402         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
403 {
404         d->xsel_cache_.set = false;
405         d->intl_.initKeyMapper(lyxrc.use_kbmap);
406
407         d->cursor_.push(buffer_.inset());
408         d->cursor_.resetAnchor();
409         d->cursor_.setCurrentFont();
410
411         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
412                 graphics::Previews::get().generateBufferPreviews(buffer_);
413 }
414
415
416 BufferView::~BufferView()
417 {
418         // current buffer is going to be switched-off, save cursor pos
419         // Ideally, the whole cursor stack should be saved, but session
420         // currently can only handle bottom (whole document) level pit and pos.
421         // That is to say, if a cursor is in a nested inset, it will be
422         // restore to the left of the top level inset.
423         LastFilePosSection::FilePos fp;
424         fp.pit = d->cursor_.bottom().pit();
425         fp.pos = d->cursor_.bottom().pos();
426         LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
427
428         delete d;
429 }
430
431
432 Intl & BufferView::getIntl()
433 {
434         return d->intl_;
435 }
436
437
438 Intl const & BufferView::getIntl() const
439 {
440         return d->intl_;
441 }
442
443
444 CoordCache & BufferView::coordCache()
445 {
446         return d->coord_cache_;
447 }
448
449
450 CoordCache const & BufferView::coordCache() const
451 {
452         return d->coord_cache_;
453 }
454
455
456 Buffer & BufferView::buffer()
457 {
458         return buffer_;
459 }
460
461
462 Buffer const & BufferView::buffer() const
463 {
464         return buffer_;
465 }
466
467
468 bool BufferView::fitCursor()
469 {
470         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
471                 frontend::FontMetrics const & fm =
472                         theFontMetrics(d->cursor_.getFont().fontInfo());
473                 int const asc = fm.maxAscent();
474                 int const des = fm.maxDescent();
475                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
476                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
477                         return false;
478         }
479         center();
480         return true;
481 }
482
483
484 bool BufferView::multiParSel()
485 {
486         if (!d->cursor_.selection())
487                 return false;
488         bool ret = d->multiparsel_cache_;
489         d->multiparsel_cache_ = d->cursor_.selBegin().pit() != d->cursor_.selEnd().pit();
490         // Either this, or previous selection spans paragraphs
491         return ret || d->multiparsel_cache_;
492 }
493
494
495 void BufferView::processUpdateFlags(Update::flags flags)
496 {
497         // last_inset_ points to the last visited inset. This pointer may become
498         // invalid because of keyboard editing. Since all such operations
499         // causes screen update(), I reset last_inset_ to avoid such a problem.
500         d->last_inset_ = 0;
501         // This is close to a hot-path.
502         LYXERR(Debug::DEBUG)
503                 << BOOST_CURRENT_FUNCTION
504                 << "[fitcursor = " << (flags & Update::FitCursor)
505                 << ", forceupdate = " << (flags & Update::Force)
506                 << ", singlepar = " << (flags & Update::SinglePar)
507                 << "]  buffer: " << &buffer_ << endl;
508
509         // Update macro store
510         if (!(cursor().inMathed() && cursor().inMacroMode()))
511                 buffer_.updateMacros();
512
513         // Now do the first drawing step if needed. This consists on updating
514         // the CoordCache in updateMetrics().
515         // The second drawing step is done in WorkArea::redraw() if needed.
516
517         // Case when no explicit update is requested.
518         if (!flags) {
519                 // no need to redraw anything.
520                 d->metrics_info_.update_strategy = NoScreenUpdate;
521                 return;
522         }
523
524         if (flags == Update::Decoration) {
525                 d->metrics_info_.update_strategy = DecorationUpdate;
526                 buffer_.changed();
527                 return;
528         }
529
530         if (flags == Update::FitCursor
531                 || flags == (Update::Decoration | Update::FitCursor)) {
532                 bool const fit_cursor = fitCursor();
533                 // tell the frontend to update the screen if needed.
534                 if (fit_cursor) {
535                         updateMetrics(false);
536                         buffer_.changed();
537                         return;
538                 }
539                 if (flags & Update::Decoration) {
540                         d->metrics_info_.update_strategy = DecorationUpdate;
541                         buffer_.changed();
542                         return;
543                 }
544                 // no screen update is needed.
545                 d->metrics_info_.update_strategy = NoScreenUpdate;
546                 return;
547         }
548
549         bool full_metrics = flags & Update::Force;
550         if (flags & Update::MultiParSel)
551                 full_metrics |= multiParSel();
552
553         bool const single_par = !full_metrics;
554         updateMetrics(single_par);
555
556         if (!(flags & Update::FitCursor)) {
557                 buffer_.changed();
558                 return;
559         }
560
561         //FIXME: updateMetrics() does not update paragraph position
562         // This is done at draw() time. So we need a redraw!
563         buffer_.changed();
564         if (!fitCursor())
565                 // The screen has already been updated thanks to the
566                 // 'buffer_.changed()' call three line above. So no need
567                 // to redraw again.
568                 return;
569
570         // The screen has been recentered around the cursor position so
571         // refresh it:
572         updateMetrics(false);
573         buffer_.changed();
574 }
575
576
577 void BufferView::updateScrollbar()
578 {
579         Text & t = buffer_.text();
580         TextMetrics & tm = d->text_metrics_[&t];
581
582         int const parsize = int(t.paragraphs().size() - 1);
583         if (d->anchor_ref_ >  parsize)  {
584                 d->anchor_ref_ = parsize;
585                 d->offset_ref_ = 0;
586         }
587
588         LYXERR(Debug::GUI)
589                 << BOOST_CURRENT_FUNCTION
590                 << " Updating scrollbar: height: " << t.paragraphs().size()
591                 << " curr par: " << d->cursor_.bottom().pit()
592                 << " default height " << defaultRowHeight() << endl;
593
594         // It would be better to fix the scrollbar to understand
595         // values in [0..1] and divide everything by wh
596
597         // estimated average paragraph height:
598         if (d->wh_ == 0)
599                 d->wh_ = height_ / 4;
600
601         int h = tm.parMetrics(d->anchor_ref_).height();
602
603         // Normalize anchor/offset (MV):
604         while (d->offset_ref_ > h && d->anchor_ref_ < parsize) {
605                 d->anchor_ref_++;
606                 d->offset_ref_ -= h;
607                 h = tm.parMetrics(d->anchor_ref_).height();
608         }
609         // Look at paragraph heights on-screen
610         int sumh = 0;
611         int nh = 0;
612         for (pit_type pit = d->anchor_ref_; pit <= parsize; ++pit) {
613                 if (sumh > height_)
614                         break;
615                 int const h2 = tm.parMetrics(pit).height();
616                 sumh += h2;
617                 nh++;
618         }
619
620         BOOST_ASSERT(nh);
621         int const hav = sumh / nh;
622         // More realistic average paragraph height
623         if (hav > d->wh_)
624                 d->wh_ = hav;
625
626         BOOST_ASSERT(h);
627         d->scrollbarParameters_.height = (parsize + 1) * d->wh_;
628         d->scrollbarParameters_.position = d->anchor_ref_ * d->wh_ + int(d->offset_ref_ * d->wh_ / float(h));
629         d->scrollbarParameters_.lineScrollHeight = int(d->wh_ * defaultRowHeight() / float(h));
630 }
631
632
633 ScrollbarParameters const & BufferView::scrollbarParameters() const
634 {
635         return d->scrollbarParameters_;
636 }
637
638
639 void BufferView::scrollDocView(int value)
640 {
641         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
642                            << "[ value = " << value << "]" << endl;
643
644         Text & t = buffer_.text();
645         TextMetrics & tm = d->text_metrics_[&t];
646
647         float const bar = value / float(d->wh_ * t.paragraphs().size());
648
649         d->anchor_ref_ = int(bar * t.paragraphs().size());
650         if (d->anchor_ref_ >  int(t.paragraphs().size()) - 1)
651                 d->anchor_ref_ = int(t.paragraphs().size()) - 1;
652
653         tm.redoParagraph(d->anchor_ref_);
654         int const h = tm.parMetrics(d->anchor_ref_).height();
655         d->offset_ref_ = int((bar * t.paragraphs().size() - d->anchor_ref_) * h);
656         updateMetrics(false);
657         buffer_.changed();
658 }
659
660
661 void BufferView::setCursorFromScrollbar()
662 {
663         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
664
665         int const height = 2 * defaultRowHeight();
666         int const first = height;
667         int const last = height_ - height;
668         Cursor & cur = d->cursor_;
669
670         switch (cursorStatus(cur)) {
671         case CUR_ABOVE:
672                 // We reset the cursor because cursorStatus() does not
673                 // work when the cursor is within mathed.
674                 cur.reset(buffer_.inset());
675                 tm.setCursorFromCoordinates(cur, 0, first);
676                 cur.clearSelection();
677                 break;
678         case CUR_BELOW:
679                 // We reset the cursor because cursorStatus() does not
680                 // work when the cursor is within mathed.
681                 cur.reset(buffer_.inset());
682                 tm.setCursorFromCoordinates(cur, 0, last);
683                 cur.clearSelection();
684                 break;
685         case CUR_INSIDE:
686                 int const y = getPos(cur, cur.boundary()).y_;
687                 int const newy = min(last, max(y, first));
688                 if (y != newy) {
689                         cur.reset(buffer_.inset());
690                         tm.setCursorFromCoordinates(cur, 0, newy);
691                 }
692         }
693 }
694
695
696 Change const BufferView::getCurrentChange() const
697 {
698         if (!d->cursor_.selection())
699                 return Change(Change::UNCHANGED);
700
701         DocIterator dit = d->cursor_.selectionBegin();
702         return dit.paragraph().lookupChange(dit.pos());
703 }
704
705
706 // this could be used elsewhere as well?
707 // FIXME: This does not work within mathed!
708 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
709 {
710         Point const p = getPos(dit, dit.boundary());
711         if (p.y_ < 0)
712                 return CUR_ABOVE;
713         if (p.y_ > workHeight())
714                 return CUR_BELOW;
715         return CUR_INSIDE;
716 }
717
718
719 void BufferView::saveBookmark(unsigned int idx)
720 {
721         // tenatively save bookmark, id and pos will be used to
722         // acturately locate a bookmark in a 'live' lyx session.
723         // pit and pos will be updated with bottom level pit/pos
724         // when lyx exits.
725         LyX::ref().session().bookmarks().save(
726                 buffer_.fileName(),
727                 d->cursor_.bottom().pit(),
728                 d->cursor_.bottom().pos(),
729                 d->cursor_.paragraph().id(),
730                 d->cursor_.pos(),
731                 idx
732         );
733         if (idx)
734                 // emit message signal.
735                 message(_("Save bookmark"));
736 }
737
738
739 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
740         int top_id, pos_type top_pos)
741 {
742         bool success = false;
743         DocIterator doc_it;
744
745         d->cursor_.clearSelection();
746
747         // if a valid par_id is given, try it first
748         // This is the case for a 'live' bookmark when unique paragraph ID
749         // is used to track bookmarks.
750         if (top_id > 0) {
751                 ParIterator par = buffer_.getParFromID(top_id);
752                 if (par != buffer_.par_iterator_end()) {
753                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
754                         // Some slices of the iterator may not be
755                         // reachable (e.g. closed collapsable inset)
756                         // so the dociterator may need to be
757                         // shortened. Otherwise, setCursor may crash
758                         // lyx when the cursor can not be set to these
759                         // insets.
760                         size_t const n = doc_it.depth();
761                         for (size_t i = 0; i < n; ++i)
762                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
763                                         doc_it.resize(i);
764                                         break;
765                                 }
766                         success = true;
767                 }
768         }
769
770         // if top_id == 0, or searching through top_id failed
771         // This is the case for a 'restored' bookmark when only bottom
772         // (document level) pit was saved. Because of this, bookmark
773         // restoration is inaccurate. If a bookmark was within an inset,
774         // it will be restored to the left of the outmost inset that contains
775         // the bookmark.
776         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
777                 doc_it = doc_iterator_begin(buffer_.inset());
778                 doc_it.pit() = bottom_pit;
779                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
780                 success = true;
781         }
782
783         if (success) {
784                 // Note: only bottom (document) level pit is set.
785                 setCursor(doc_it);
786                 // set the current font.
787                 d->cursor_.setCurrentFont();
788                 // center the screen on this new position.
789                 center();
790         }
791
792         return success;
793 }
794
795
796 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
797 {
798         if (lyxrc.rtl_support) {
799                 if (d->cursor_.real_current_font.isRightToLeft()) {
800                         if (d->intl_.keymap == Intl::PRIMARY)
801                                 d->intl_.keyMapSec();
802                 } else {
803                         if (d->intl_.keymap == Intl::SECONDARY)
804                                 d->intl_.keyMapPrim();
805                 }
806         }
807
808         d->intl_.getTransManager().translateAndInsert(c, t, cur);
809 }
810
811
812 int BufferView::workWidth() const
813 {
814         return width_;
815 }
816
817
818 void BufferView::updateOffsetRef()
819 {
820         // No need to update d->offset_ref_ in this case.
821         if (!d->need_centering_)
822                 return;
823
824         // We are not properly started yet, delay until resizing is
825         // done.
826         if (height_ == 0)
827                 return;
828
829         CursorSlice & bot = d->cursor_.bottom();
830         TextMetrics & tm = d->text_metrics_[bot.text()];
831         ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
832         int y = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
833         d->offset_ref_ = y + pm.ascent() - height_ / 2;
834
835         d->need_centering_ = false;
836 }
837
838
839 void BufferView::center()
840 {
841         d->anchor_ref_ = d->cursor_.bottom().pit();
842         d->need_centering_ = true;
843 }
844
845
846 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
847 {
848         FuncStatus flag;
849
850         Cursor & cur = d->cursor_;
851
852         switch (cmd.action) {
853
854         case LFUN_UNDO:
855                 flag.enabled(buffer_.undo().hasUndoStack());
856                 break;
857         case LFUN_REDO:
858                 flag.enabled(buffer_.undo().hasRedoStack());
859                 break;
860         case LFUN_FILE_INSERT:
861         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
862         case LFUN_FILE_INSERT_PLAINTEXT:
863         case LFUN_BOOKMARK_SAVE:
864                 // FIXME: Actually, these LFUNS should be moved to Text
865                 flag.enabled(cur.inTexted());
866                 break;
867         case LFUN_FONT_STATE:
868         case LFUN_LABEL_INSERT:
869         case LFUN_INFO_INSERT:
870         case LFUN_PARAGRAPH_GOTO:
871         // FIXME handle non-trivially
872         case LFUN_OUTLINE_UP:
873         case LFUN_OUTLINE_DOWN:
874         case LFUN_OUTLINE_IN:
875         case LFUN_OUTLINE_OUT:
876         case LFUN_NOTE_NEXT:
877         case LFUN_REFERENCE_NEXT:
878         case LFUN_WORD_FIND:
879         case LFUN_WORD_REPLACE:
880         case LFUN_MARK_OFF:
881         case LFUN_MARK_ON:
882         case LFUN_MARK_TOGGLE:
883         case LFUN_SCREEN_RECENTER:
884         case LFUN_BIBTEX_DATABASE_ADD:
885         case LFUN_BIBTEX_DATABASE_DEL:
886         case LFUN_WORDS_COUNT:
887         case LFUN_NEXT_INSET_TOGGLE:
888                 flag.enabled(true);
889                 break;
890
891         case LFUN_LABEL_GOTO: {
892                 flag.enabled(!cmd.argument().empty()
893                     || getInsetByCode<InsetRef>(cur, REF_CODE));
894                 break;
895         }
896
897         case LFUN_CHANGES_TRACK:
898                 flag.enabled(true);
899                 flag.setOnOff(buffer_.params().trackChanges);
900                 break;
901
902         case LFUN_CHANGES_OUTPUT:
903                 flag.enabled(true);
904                 flag.setOnOff(buffer_.params().outputChanges);
905                 break;
906
907         case LFUN_CHANGES_MERGE:
908         case LFUN_CHANGE_NEXT:
909         case LFUN_ALL_CHANGES_ACCEPT:
910         case LFUN_ALL_CHANGES_REJECT:
911                 // TODO: context-sensitive enabling of LFUNs
912                 // In principle, these command should only be enabled if there
913                 // is a change in the document. However, without proper
914                 // optimizations, this will inevitably result in poor performance.
915                 flag.enabled(true);
916                 break;
917
918         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
919                 flag.setOnOff(buffer_.params().compressed);
920                 break;
921         }
922         
923         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
924                 flag.setOnOff(buffer_.params().embedded);
925                 break;
926         }
927
928         case LFUN_SCREEN_UP:
929         case LFUN_SCREEN_DOWN:
930                 flag.enabled(true);
931                 break;
932
933         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
934         // everywhere else before this can enabled:
935         case LFUN_SCREEN_UP_SELECT:
936         case LFUN_SCREEN_DOWN_SELECT:
937                 flag.enabled(false);
938                 break;
939
940         case LFUN_LAYOUT_TABULAR:
941                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
942                 break;
943
944         case LFUN_LAYOUT:
945         case LFUN_LAYOUT_PARAGRAPH:
946                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
947                 break;
948
949         case LFUN_INSET_SETTINGS: {
950                 InsetCode code = cur.inset().lyxCode();
951                 bool enable = false;
952                 switch (code) {
953                         case TABULAR_CODE:
954                                 enable = cmd.argument() == "tabular";
955                                 break;
956                         case ERT_CODE:
957                                 enable = cmd.argument() == "ert";
958                                 break;
959                         case FLOAT_CODE:
960                                 enable = cmd.argument() == "float";
961                                 break;
962                         case WRAP_CODE:
963                                 enable = cmd.argument() == "wrap";
964                                 break;
965                         case NOTE_CODE:
966                                 enable = cmd.argument() == "note";
967                                 break;
968                         case BRANCH_CODE:
969                                 enable = cmd.argument() == "branch";
970                                 break;
971                         case BOX_CODE:
972                                 enable = cmd.argument() == "box";
973                                 break;
974                         case LISTINGS_CODE:
975                                 enable = cmd.argument() == "listings";
976                                 break;
977                         default:
978                                 break;
979                 }
980                 flag.enabled(enable);
981                 break;
982         }
983
984         case LFUN_DIALOG_SHOW_NEW_INSET:
985                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
986                         cur.inset().lyxCode() != LISTINGS_CODE);
987                 if (cur.inset().lyxCode() == CAPTION_CODE) {
988                         FuncStatus flag;
989                         if (cur.inset().getStatus(cur, cmd, flag))
990                                 return flag;
991                 }
992                 break;
993
994         default:
995                 flag.enabled(false);
996         }
997
998         return flag;
999 }
1000
1001
1002 Update::flags BufferView::dispatch(FuncRequest const & cmd)
1003 {
1004         //lyxerr << BOOST_CURRENT_FUNCTION
1005         //       << [ cmd = " << cmd << "]" << endl;
1006
1007         // Make sure that the cached BufferView is correct.
1008         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
1009                 << " action[" << cmd.action << ']'
1010                 << " arg[" << to_utf8(cmd.argument()) << ']'
1011                 << " x[" << cmd.x << ']'
1012                 << " y[" << cmd.y << ']'
1013                 << " button[" << cmd.button() << ']'
1014                 << endl;
1015
1016         Cursor & cur = d->cursor_;
1017         // Default Update flags.
1018         Update::flags updateFlags = Update::Force | Update::FitCursor;
1019
1020         switch (cmd.action) {
1021
1022         case LFUN_UNDO:
1023                 cur.message(_("Undo"));
1024                 cur.clearSelection();
1025                 if (!cur.textUndo()) {
1026                         cur.message(_("No further undo information"));
1027                         updateFlags = Update::None;
1028                 }
1029                 break;
1030
1031         case LFUN_REDO:
1032                 cur.message(_("Redo"));
1033                 cur.clearSelection();
1034                 if (!cur.textRedo()) {
1035                         cur.message(_("No further redo information"));
1036                         updateFlags = Update::None;
1037                 }
1038                 break;
1039
1040         case LFUN_FILE_INSERT:
1041                 // FIXME UNICODE
1042                 menuInsertLyXFile(to_utf8(cmd.argument()));
1043                 break;
1044
1045         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1046                 // FIXME UNICODE
1047                 insertPlaintextFile(to_utf8(cmd.argument()), true);
1048                 break;
1049
1050         case LFUN_FILE_INSERT_PLAINTEXT:
1051                 // FIXME UNICODE
1052                 insertPlaintextFile(to_utf8(cmd.argument()), false);
1053                 break;
1054
1055         case LFUN_FONT_STATE:
1056                 cur.message(cur.currentState());
1057                 break;
1058
1059         case LFUN_BOOKMARK_SAVE:
1060                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1061                 break;
1062
1063         case LFUN_LABEL_GOTO: {
1064                 docstring label = cmd.argument();
1065                 if (label.empty()) {
1066                         InsetRef * inset =
1067                                 getInsetByCode<InsetRef>(d->cursor_,
1068                                                          REF_CODE);
1069                         if (inset) {
1070                                 label = inset->getParam("reference");
1071                                 // persistent=false: use temp_bookmark
1072                                 saveBookmark(0);
1073                         }
1074                 }
1075
1076                 if (!label.empty())
1077                         gotoLabel(label);
1078                 break;
1079         }
1080
1081         case LFUN_PARAGRAPH_GOTO: {
1082                 int const id = convert<int>(to_utf8(cmd.argument()));
1083                 int i = 0;
1084                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1085                         b = theBufferList().next(b)) {
1086
1087                         ParIterator par = b->getParFromID(id);
1088                         if (par == b->par_iterator_end()) {
1089                                 LYXERR(Debug::INFO)
1090                                         << "No matching paragraph found! ["
1091                                         << id << "]." << endl;
1092                         } else {
1093                                 LYXERR(Debug::INFO)
1094                                         << "Paragraph " << par->id()
1095                                         << " found in buffer `"
1096                                         << b->absFileName() << "'." << endl;
1097
1098                                 if (b == &buffer_) {
1099                                         // Set the cursor
1100                                         setCursor(makeDocIterator(par, 0));
1101                                 } else {
1102                                         // Switch to other buffer view and resend cmd
1103                                         theLyXFunc().dispatch(FuncRequest(
1104                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
1105                                         theLyXFunc().dispatch(cmd);
1106                                         updateFlags = Update::None;
1107                                 }
1108                                 break;
1109                         }
1110                         ++i;
1111                 }
1112                 break;
1113         }
1114
1115         case LFUN_OUTLINE_UP:
1116                 outline(OutlineUp, d->cursor_);
1117                 d->cursor_.text()->setCursor(d->cursor_, d->cursor_.pit(), 0);
1118                 updateLabels(buffer_);
1119                 break;
1120         case LFUN_OUTLINE_DOWN:
1121                 outline(OutlineDown, d->cursor_);
1122                 d->cursor_.text()->setCursor(d->cursor_, d->cursor_.pit(), 0);
1123                 updateLabels(buffer_);
1124                 break;
1125         case LFUN_OUTLINE_IN:
1126                 outline(OutlineIn, d->cursor_);
1127                 updateLabels(buffer_);
1128                 break;
1129         case LFUN_OUTLINE_OUT:
1130                 outline(OutlineOut, d->cursor_);
1131                 updateLabels(buffer_);
1132                 break;
1133
1134         case LFUN_NOTE_NEXT:
1135                 gotoInset(this, NOTE_CODE, false);
1136                 break;
1137
1138         case LFUN_REFERENCE_NEXT: {
1139                 vector<InsetCode> tmp;
1140                 tmp.push_back(LABEL_CODE);
1141                 tmp.push_back(REF_CODE);
1142                 gotoInset(this, tmp, true);
1143                 break;
1144         }
1145
1146         case LFUN_CHANGES_TRACK:
1147                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1148                 break;
1149
1150         case LFUN_CHANGES_OUTPUT:
1151                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1152                 if (buffer_.params().outputChanges) {
1153                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1154                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1155                                           LaTeXFeatures::isAvailable("xcolor");
1156
1157                         if (!dvipost && !xcolorsoul) {
1158                                 Alert::warning(_("Changes not shown in LaTeX output"),
1159                                                _("Changes will not be highlighted in LaTeX output, "
1160                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1161                                                  "Please install these packages or redefine "
1162                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1163                         } else if (!xcolorsoul) {
1164                                 Alert::warning(_("Changes not shown in LaTeX output"),
1165                                                _("Changes will not be highlighted in LaTeX output "
1166                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1167                                                  "Please install both packages or redefine "
1168                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1169                         }
1170                 }
1171                 break;
1172
1173         case LFUN_CHANGE_NEXT:
1174                 findNextChange(this);
1175                 break;
1176
1177         case LFUN_CHANGES_MERGE:
1178                 if (findNextChange(this))
1179                         showDialog("changes");
1180                 break;
1181
1182         case LFUN_ALL_CHANGES_ACCEPT:
1183                 // select complete document
1184                 d->cursor_.reset(buffer_.inset());
1185                 d->cursor_.selHandle(true);
1186                 buffer_.text().cursorBottom(d->cursor_);
1187                 // accept everything in a single step to support atomic undo
1188                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1189                 break;
1190
1191         case LFUN_ALL_CHANGES_REJECT:
1192                 // select complete document
1193                 d->cursor_.reset(buffer_.inset());
1194                 d->cursor_.selHandle(true);
1195                 buffer_.text().cursorBottom(d->cursor_);
1196                 // reject everything in a single step to support atomic undo
1197                 // Note: reject does not work recursively; the user may have to repeat the operation
1198                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1199                 break;
1200
1201         case LFUN_WORD_FIND:
1202                 find(this, cmd);
1203                 break;
1204
1205         case LFUN_WORD_REPLACE: {
1206                 bool has_deleted = false;
1207                 if (cur.selection()) {
1208                         DocIterator beg = cur.selectionBegin();
1209                         DocIterator end = cur.selectionEnd();
1210                         if (beg.pit() == end.pit()) {
1211                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1212                                         if (cur.paragraph().isDeleted(p))
1213                                                 has_deleted = true;
1214                                 }
1215                         }
1216                 }
1217                 replace(this, cmd, has_deleted);
1218                 break;
1219         }
1220
1221         case LFUN_MARK_OFF:
1222                 cur.clearSelection();
1223                 cur.resetAnchor();
1224                 cur.message(from_utf8(N_("Mark off")));
1225                 break;
1226
1227         case LFUN_MARK_ON:
1228                 cur.clearSelection();
1229                 cur.mark() = true;
1230                 cur.resetAnchor();
1231                 cur.message(from_utf8(N_("Mark on")));
1232                 break;
1233
1234         case LFUN_MARK_TOGGLE:
1235                 cur.clearSelection();
1236                 if (cur.mark()) {
1237                         cur.mark() = false;
1238                         cur.message(from_utf8(N_("Mark removed")));
1239                 } else {
1240                         cur.mark() = true;
1241                         cur.message(from_utf8(N_("Mark set")));
1242                 }
1243                 cur.resetAnchor();
1244                 break;
1245
1246         case LFUN_SCREEN_RECENTER:
1247                 center();
1248                 break;
1249
1250         case LFUN_BIBTEX_DATABASE_ADD: {
1251                 Cursor tmpcur = d->cursor_;
1252                 findInset(tmpcur, BIBTEX_CODE, false);
1253                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1254                                                 BIBTEX_CODE);
1255                 if (inset) {
1256                         if (inset->addDatabase(to_utf8(cmd.argument())))
1257                                 buffer_.updateBibfilesCache();
1258                 }
1259                 break;
1260         }
1261
1262         case LFUN_BIBTEX_DATABASE_DEL: {
1263                 Cursor tmpcur = d->cursor_;
1264                 findInset(tmpcur, BIBTEX_CODE, false);
1265                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1266                                                 BIBTEX_CODE);
1267                 if (inset) {
1268                         if (inset->delDatabase(to_utf8(cmd.argument())))
1269                                 buffer_.updateBibfilesCache();
1270                 }
1271                 break;
1272         }
1273
1274         case LFUN_WORDS_COUNT: {
1275                 DocIterator from, to;
1276                 if (cur.selection()) {
1277                         from = cur.selectionBegin();
1278                         to = cur.selectionEnd();
1279                 } else {
1280                         from = doc_iterator_begin(buffer_.inset());
1281                         to = doc_iterator_end(buffer_.inset());
1282                 }
1283                 int const count = countWords(from, to);
1284                 docstring message;
1285                 if (count != 1) {
1286                         if (cur.selection())
1287                                 message = bformat(_("%1$d words in selection."),
1288                                           count);
1289                                 else
1290                                         message = bformat(_("%1$d words in document."),
1291                                                           count);
1292                 }
1293                 else {
1294                         if (cur.selection())
1295                                 message = _("One word in selection.");
1296                         else
1297                                 message = _("One word in document.");
1298                 }
1299
1300                 Alert::information(_("Count words"), message);
1301         }
1302                 break;
1303
1304         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1305                 // turn compression on/off
1306                 buffer_.params().compressed = !buffer_.params().compressed;
1307                 break;
1308         
1309         case LFUN_BUFFER_TOGGLE_EMBEDDING:
1310                 // turn embedding on/off
1311                 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1312                 break;
1313
1314         case LFUN_NEXT_INSET_TOGGLE: {
1315                 // this is the real function we want to invoke
1316                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1317                 // if there is an inset at cursor, see whether it
1318                 // wants to toggle.
1319                 Inset * inset = cur.nextInset();
1320                 if (inset) {
1321                         if (inset->isActive()) {
1322                                 Cursor tmpcur = cur;
1323                                 tmpcur.pushLeft(*inset);
1324                                 inset->dispatch(tmpcur, tmpcmd);
1325                                 if (tmpcur.result().dispatched()) {
1326                                         cur.dispatched();
1327                                 }
1328                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1329                                 inset->edit(cur, true);
1330                         }
1331                 }
1332                 // if it did not work, try the underlying inset.
1333                 if (!cur.result().dispatched())
1334                         cur.dispatch(tmpcmd);
1335
1336                 if (cur.result().dispatched())
1337                         cur.clearSelection();
1338
1339                 break;
1340         }
1341
1342         case LFUN_SCREEN_UP:
1343         case LFUN_SCREEN_DOWN: {
1344                 Point p = getPos(cur, cur.boundary());
1345                 if (p.y_ < 0 || p.y_ > height_) {
1346                         // The cursor is off-screen so recenter before proceeding.
1347                         center();
1348                         updateMetrics(false);
1349                         //FIXME: updateMetrics() does not update paragraph position
1350                         // This is done at draw() time. So we need a redraw!
1351                         buffer_.changed();
1352                         p = getPos(cur, cur.boundary());
1353                 }
1354                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1355                 cur.reset(buffer_.inset());
1356                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1357                 //FIXME: what to do with cur.x_target()?
1358                 cur.finishUndo();
1359                 // The metrics are already up to date. see scroll()
1360                 updateFlags = Update::None;
1361                 break;
1362         }
1363
1364         case LFUN_SCREEN_UP_SELECT:
1365         case LFUN_SCREEN_DOWN_SELECT: {
1366                 cur.selHandle(true);
1367                 size_t initial_depth = cur.depth();
1368                 Point const p = getPos(cur, cur.boundary());
1369                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1370                 // FIXME: We need to verify if the cursor stayed within an inset...
1371                 //cur.reset(buffer_.inset());
1372                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1373                 cur.finishUndo();
1374                 while (cur.depth() > initial_depth) {
1375                         cur.forwardInset();
1376                 }
1377                 // FIXME: we need to do a redraw again because of the selection
1378                 buffer_.changed();
1379                 updateFlags = Update::Force | Update::FitCursor;
1380                 break;
1381         }
1382
1383         default:
1384                 updateFlags = Update::None;
1385         }
1386
1387         return updateFlags;
1388 }
1389
1390
1391 docstring const BufferView::requestSelection()
1392 {
1393         Cursor & cur = d->cursor_;
1394
1395         if (!cur.selection()) {
1396                 d->xsel_cache_.set = false;
1397                 return docstring();
1398         }
1399
1400         if (!d->xsel_cache_.set ||
1401             cur.top() != d->xsel_cache_.cursor ||
1402             cur.anchor_.top() != d->xsel_cache_.anchor)
1403         {
1404                 d->xsel_cache_.cursor = cur.top();
1405                 d->xsel_cache_.anchor = cur.anchor_.top();
1406                 d->xsel_cache_.set = cur.selection();
1407                 return cur.selectionAsString(false);
1408         }
1409         return docstring();
1410 }
1411
1412
1413 void BufferView::clearSelection()
1414 {
1415         d->cursor_.clearSelection();
1416         // Clear the selection buffer. Otherwise a subsequent
1417         // middle-mouse-button paste would use the selection buffer,
1418         // not the more current external selection.
1419         cap::clearSelection();
1420         d->xsel_cache_.set = false;
1421         // The buffer did not really change, but this causes the
1422         // redraw we need because we cleared the selection above.
1423         buffer_.changed();
1424 }
1425
1426
1427 void BufferView::resize(int width, int height)
1428 {
1429         // Update from work area
1430         width_ = width;
1431         height_ = height;
1432
1433         updateMetrics(false);
1434 }
1435
1436
1437 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1438 {
1439         TextMetrics & tm = d->text_metrics_[&text];
1440         Inset * inset = tm.checkInsetHit(x, y);
1441         if (!inset)
1442                 return 0;
1443
1444         if (!inset->descendable())
1445                 // No need to go further down if the inset is not
1446                 // descendable.
1447                 return inset;
1448
1449         size_t cell_number = inset->nargs();
1450         // Check all the inner cell.
1451         for (size_t i = 0; i != cell_number; ++i) {
1452                 Text const * inner_text = inset->getText(i);
1453                 if (inner_text) {
1454                         // Try deeper.
1455                         Inset const * inset_deeper =
1456                                 getCoveringInset(*inner_text, x, y);
1457                         if (inset_deeper)
1458                                 return inset_deeper;
1459                 }
1460         }
1461
1462         return inset;
1463 }
1464
1465
1466 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1467 {
1468         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1469
1470         // This is only called for mouse related events including
1471         // LFUN_FILE_OPEN generated by drag-and-drop.
1472         FuncRequest cmd = cmd0;
1473
1474         Cursor cur(*this);
1475         cur.push(buffer_.inset());
1476         cur.selection() = d->cursor_.selection();
1477
1478         // Either the inset under the cursor or the
1479         // surrounding Text will handle this event.
1480
1481         // make sure we stay within the screen...
1482         cmd.y = min(max(cmd.y, -1), height_);
1483
1484         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1485
1486                 // Get inset under mouse, if there is one.
1487                 Inset const * covering_inset =
1488                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1489                 if (covering_inset == d->last_inset_)
1490                         // Same inset, no need to do anything...
1491                         return;
1492
1493                 bool need_redraw = false;
1494                 // const_cast because of setMouseHover().
1495                 Inset * inset = const_cast<Inset *>(covering_inset);
1496                 if (d->last_inset_)
1497                         // Remove the hint on the last hovered inset (if any).
1498                         need_redraw |= d->last_inset_->setMouseHover(false);
1499                 if (inset)
1500                         // Highlighted the newly hovered inset (if any).
1501                         need_redraw |= inset->setMouseHover(true);
1502                 d->last_inset_ = inset;
1503                 if (!need_redraw)
1504                         return;
1505
1506                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1507                 // not expose the button for redraw. We adjust here the metrics dimension
1508                 // to enable a full redraw in any case as this is not costly.
1509                 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
1510                 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1511                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1512                 int y1 = firstpm.second->position() - firstpm.second->ascent();
1513                 int y2 = lastpm.second->position() + lastpm.second->descent();
1514                 d->metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1515                         FullScreenUpdate, buffer_.text().paragraphs().size());
1516                 // Reinitialize anchor to first pit.
1517                 d->anchor_ref_ = firstpm.first;
1518                 d->offset_ref_ = -y1;
1519                 LYXERR(Debug::PAINTING)
1520                         << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1521                         << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1522                         << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1523
1524                 // This event (moving without mouse click) is not passed further.
1525                 // This should be changed if it is further utilized.
1526                 buffer_.changed();
1527                 return;
1528         }
1529
1530         // Build temporary cursor.
1531         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1532
1533         // Put anchor at the same position.
1534         cur.resetAnchor();
1535
1536         // Try to dispatch to an non-editable inset near this position
1537         // via the temp cursor. If the inset wishes to change the real
1538         // cursor it has to do so explicitly by using
1539         //  cur.bv().cursor() = cur;  (or similar)
1540         if (inset)
1541                 inset->dispatch(cur, cmd);
1542
1543         // Now dispatch to the temporary cursor. If the real cursor should
1544         // be modified, the inset's dispatch has to do so explicitly.
1545         if (!cur.result().dispatched())
1546                 cur.dispatch(cmd);
1547
1548         //Do we have a selection?
1549         theSelection().haveSelection(cursor().selection());
1550
1551         // If the command has been dispatched,
1552         if (cur.result().dispatched()
1553                 // an update is asked,
1554                 && cur.result().update())
1555                 processUpdateFlags(cur.result().update());
1556 }
1557
1558
1559 void BufferView::scroll(int y)
1560 {
1561         if (y > 0)
1562                 scrollDown(y);
1563         else if (y < 0)
1564                 scrollUp(-y);
1565 }
1566
1567
1568 void BufferView::scrollDown(int offset)
1569 {
1570         Text * text = &buffer_.text();
1571         TextMetrics & tm = d->text_metrics_[text];
1572         int ymax = height_ + offset;
1573         while (true) {
1574                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1575                 int bottom_pos = last.second->position() + last.second->descent();
1576                 if (last.first + 1 == int(text->paragraphs().size())) {
1577                         if (bottom_pos <= height_)
1578                                 return;
1579                         offset = min(offset, bottom_pos - height_);
1580                         break;
1581                 }
1582                 if (bottom_pos > ymax)
1583                         break;
1584                 tm.newParMetricsDown();
1585         }
1586         d->offset_ref_ += offset;
1587         updateMetrics(false);
1588         buffer_.changed();
1589 }
1590
1591
1592 void BufferView::scrollUp(int offset)
1593 {
1594         Text * text = &buffer_.text();
1595         TextMetrics & tm = d->text_metrics_[text];
1596         int ymin = - offset;
1597         while (true) {
1598                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1599                 int top_pos = first.second->position() - first.second->ascent();
1600                 if (first.first == 0) {
1601                         if (top_pos >= 0)
1602                                 return;
1603                         offset = min(offset, - top_pos);
1604                         break;
1605                 }
1606                 if (top_pos < ymin)
1607                         break;
1608                 tm.newParMetricsUp();
1609         }
1610         d->offset_ref_ -= offset;
1611         updateMetrics(false);
1612         buffer_.changed();
1613 }
1614
1615
1616 void BufferView::setCursorFromRow(int row)
1617 {
1618         int tmpid = -1;
1619         int tmppos = -1;
1620
1621         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1622
1623         d->cursor_.reset(buffer_.inset());
1624         if (tmpid == -1)
1625                 buffer_.text().setCursor(d->cursor_, 0, 0);
1626         else
1627                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1628 }
1629
1630
1631 void BufferView::gotoLabel(docstring const & label)
1632 {
1633         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1634                 vector<docstring> labels;
1635                 it->getLabelList(buffer_, labels);
1636                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1637                         setCursor(it);
1638                         processUpdateFlags(Update::FitCursor);
1639                         return;
1640                 }
1641         }
1642 }
1643
1644
1645 TextMetrics const & BufferView::textMetrics(Text const * t) const
1646 {
1647         return const_cast<BufferView *>(this)->textMetrics(t);
1648 }
1649
1650
1651 TextMetrics & BufferView::textMetrics(Text const * t)
1652 {
1653         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1654         if (tmc_it == d->text_metrics_.end()) {
1655                 tmc_it = d->text_metrics_.insert(
1656                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1657         }
1658         return tmc_it->second;
1659 }
1660
1661
1662 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1663                 pit_type pit) const
1664 {
1665         return textMetrics(t).parMetrics(pit);
1666 }
1667
1668
1669 int BufferView::workHeight() const
1670 {
1671         return height_;
1672 }
1673
1674
1675 void BufferView::setCursor(DocIterator const & dit)
1676 {
1677         size_t const n = dit.depth();
1678         for (size_t i = 0; i < n; ++i)
1679                 dit[i].inset().edit(d->cursor_, true);
1680
1681         d->cursor_.setCursor(dit);
1682         d->cursor_.selection() = false;
1683 }
1684
1685
1686 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1687 {
1688         // Would be wrong to delete anything if we have a selection.
1689         if (cur.selection())
1690                 return false;
1691
1692         bool need_anchor_change = false;
1693         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1694                 need_anchor_change);
1695
1696         if (need_anchor_change)
1697                 cur.resetAnchor();
1698
1699         if (!changed)
1700                 return false;
1701
1702         updateLabels(buffer_);
1703
1704         updateMetrics(false);
1705         buffer_.changed();
1706         return true;
1707 }
1708
1709
1710 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1711 {
1712         BOOST_ASSERT(&cur.bv() == this);
1713
1714         if (!select)
1715                 // this event will clear selection so we save selection for
1716                 // persistent selection
1717                 cap::saveSelection(cursor());
1718
1719         // Has the cursor just left the inset?
1720         bool badcursor = false;
1721         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1722         if (leftinset)
1723                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1724
1725         // FIXME: shift-mouse selection doesn't work well across insets.
1726         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1727
1728         // do the dEPM magic if needed
1729         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1730         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1731         // the leftinset bool would not be necessary (badcursor instead).
1732         bool update = leftinset;
1733         if (!do_selection && !badcursor && d->cursor_.inTexted())
1734                 update |= checkDepm(cur, d->cursor_);
1735
1736         // if the cursor was in an empty script inset and the new
1737         // position is in the nucleus of the inset, notifyCursorLeaves
1738         // will kill the script inset itself. So we check all the
1739         // elements of the cursor to make sure that they are correct.
1740         // For an example, see bug 2933:
1741         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1742         // The code below could maybe be moved to a DocIterator method.
1743         //lyxerr << "cur before " << cur <<std::endl;
1744         DocIterator dit(cur.inset());
1745         dit.push_back(cur.bottom());
1746         size_t i = 1;
1747         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1748                 dit.push_back(cur[i]);
1749                 ++i;
1750         }
1751         //lyxerr << "5 cur after" << dit <<std::endl;
1752
1753         d->cursor_.setCursor(dit);
1754         d->cursor_.boundary(cur.boundary());
1755         if (do_selection)
1756                 d->cursor_.setSelection();
1757         else
1758                 d->cursor_.clearSelection();
1759
1760         d->cursor_.finishUndo();
1761         d->cursor_.setCurrentFont();
1762         return update;
1763 }
1764
1765
1766 void BufferView::putSelectionAt(DocIterator const & cur,
1767                                 int length, bool backwards)
1768 {
1769         d->cursor_.clearSelection();
1770
1771         setCursor(cur);
1772
1773         if (length) {
1774                 if (backwards) {
1775                         d->cursor_.pos() += length;
1776                         d->cursor_.setSelection(d->cursor_, -length);
1777                 } else
1778                         d->cursor_.setSelection(d->cursor_, length);
1779         }
1780 }
1781
1782
1783 Cursor & BufferView::cursor()
1784 {
1785         return d->cursor_;
1786 }
1787
1788
1789 Cursor const & BufferView::cursor() const
1790 {
1791         return d->cursor_;
1792 }
1793
1794
1795 pit_type BufferView::anchor_ref() const
1796 {
1797         return d->anchor_ref_;
1798 }
1799
1800
1801 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1802 {
1803         return d->metrics_info_;
1804 }
1805
1806
1807 bool BufferView::singleParUpdate()
1808 {
1809         Text & buftext = buffer_.text();
1810         pit_type const bottom_pit = d->cursor_.bottom().pit();
1811         TextMetrics & tm = textMetrics(&buftext);
1812         int old_height = tm.parMetrics(bottom_pit).height();
1813
1814         // In Single Paragraph mode, rebreak only
1815         // the (main text, not inset!) paragraph containing the cursor.
1816         // (if this paragraph contains insets etc., rebreaking will
1817         // recursively descend)
1818         tm.redoParagraph(bottom_pit);
1819         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1820         if (pm.height() != old_height)
1821                 // Paragraph height has changed so we cannot proceed to
1822                 // the singlePar optimisation.
1823                 return false;
1824
1825         int y1 = pm.position() - pm.ascent();
1826         int y2 = pm.position() + pm.descent();
1827         d->metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1828                 SingleParUpdate, buftext.paragraphs().size());
1829         LYXERR(Debug::PAINTING)
1830                 << BOOST_CURRENT_FUNCTION
1831                 << "\ny1: " << y1
1832                 << " y2: " << y2
1833                 << " pit: " << bottom_pit
1834                 << " singlepar: 1"
1835                 << endl;
1836         return true;
1837 }
1838
1839
1840 void BufferView::updateMetrics(bool singlepar)
1841 {
1842         if (singlepar && singleParUpdate())
1843                 // No need to update the full screen metrics.
1844                 return;
1845
1846         Text & buftext = buffer_.text();
1847         pit_type const npit = int(buftext.paragraphs().size());
1848
1849         if (d->anchor_ref_ > int(npit - 1)) {
1850                 d->anchor_ref_ = int(npit - 1);
1851                 d->offset_ref_ = 0;
1852         }
1853
1854         // Clear out the position cache in case of full screen redraw,
1855         d->coord_cache_.clear();
1856
1857         // Clear out paragraph metrics to avoid having invalid metrics
1858         // in the cache from paragraphs not relayouted below
1859         // The complete text metrics will be redone.
1860         d->text_metrics_.clear();
1861
1862         TextMetrics & tm = textMetrics(&buftext);
1863
1864         pit_type const pit = d->anchor_ref_;
1865         int pit1 = pit;
1866         int pit2 = pit;
1867
1868         // Rebreak anchor paragraph.
1869         tm.redoParagraph(pit);
1870
1871         // Take care of anchor offset if case a recentering is needed.
1872         updateOffsetRef();
1873
1874         int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1875
1876         // Redo paragraphs above anchor if necessary.
1877         int y1 = y0;
1878         while (y1 > 0 && pit1 > 0) {
1879                 y1 -= tm.parMetrics(pit1).ascent();
1880                 --pit1;
1881                 tm.redoParagraph(pit1);
1882                 y1 -= tm.parMetrics(pit1).descent();
1883         }
1884
1885         // Take care of ascent of first line
1886         y1 -= tm.parMetrics(pit1).ascent();
1887
1888         // Normalize anchor for next time
1889         d->anchor_ref_ = pit1;
1890         d->offset_ref_ = -y1;
1891
1892         // Grey at the beginning is ugly
1893         if (pit1 == 0 && y1 > 0) {
1894                 y0 -= y1;
1895                 y1 = 0;
1896                 d->anchor_ref_ = 0;
1897         }
1898
1899         // Redo paragraphs below the anchor if necessary.
1900         int y2 = y0;
1901         while (y2 < height_ && pit2 < int(npit) - 1) {
1902                 y2 += tm.parMetrics(pit2).descent();
1903                 ++pit2;
1904                 tm.redoParagraph(pit2);
1905                 y2 += tm.parMetrics(pit2).ascent();
1906         }
1907
1908         // Take care of descent of last line
1909         y2 += tm.parMetrics(pit2).descent();
1910
1911         LYXERR(Debug::PAINTING)
1912                 << BOOST_CURRENT_FUNCTION
1913                 << "\n y1: " << y1
1914                 << " y2: " << y2
1915                 << " pit1: " << pit1
1916                 << " pit2: " << pit2
1917                 << " npit: " << npit
1918                 << " singlepar: 0"
1919                 << endl;
1920
1921         d->metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1922                 FullScreenUpdate, npit);
1923
1924         if (lyxerr.debugging(Debug::WORKAREA)) {
1925                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1926                 d->coord_cache_.dump();
1927         }
1928 }
1929
1930
1931 void BufferView::menuInsertLyXFile(string const & filenm)
1932 {
1933         BOOST_ASSERT(d->cursor_.inTexted());
1934         string filename = filenm;
1935
1936         if (filename.empty()) {
1937                 // Launch a file browser
1938                 // FIXME UNICODE
1939                 string initpath = lyxrc.document_path;
1940                 string const trypath = buffer_.filePath();
1941                 // If directory is writeable, use this as default.
1942                 if (FileName(trypath).isDirWritable())
1943                         initpath = trypath;
1944
1945                 // FIXME UNICODE
1946                 FileDialog dlg(_("Select LyX document to insert"), LFUN_FILE_INSERT);
1947                 dlg.setButton1(_("Documents|#o#O"), from_utf8(lyxrc.document_path));
1948                 dlg.setButton2(_("Examples|#E#e"),
1949                         from_utf8(addPath(package().system_support().absFilename(),
1950                         "examples")));
1951
1952                 FileDialog::Result result =
1953                         dlg.open(from_utf8(initpath),
1954                                      FileFilterList(_("LyX Documents (*.lyx)")),
1955                                      docstring());
1956
1957                 if (result.first == FileDialog::Later)
1958                         return;
1959
1960                 // FIXME UNICODE
1961                 filename = to_utf8(result.second);
1962
1963                 // check selected filename
1964                 if (filename.empty()) {
1965                         // emit message signal.
1966                         message(_("Canceled."));
1967                         return;
1968                 }
1969         }
1970
1971         // Get absolute path of file and add ".lyx"
1972         // to the filename if necessary
1973         filename = fileSearch(string(), filename, "lyx").absFilename();
1974
1975         docstring const disp_fn = makeDisplayPath(filename);
1976         // emit message signal.
1977         message(bformat(_("Inserting document %1$s..."), disp_fn));
1978
1979         docstring res;
1980         Buffer buf("", false);
1981         if (buf.loadLyXFile(FileName(filename))) {
1982                 ErrorList & el = buffer_.errorList("Parse");
1983                 // Copy the inserted document error list into the current buffer one.
1984                 el = buf.errorList("Parse");
1985                 buffer_.undo().recordUndo(d->cursor_);
1986                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1987                                              buf.params().getTextClassPtr(), el);
1988                 res = _("Document %1$s inserted.");
1989         } else {
1990                 res = _("Could not insert document %1$s");
1991         }
1992
1993         // emit message signal.
1994         message(bformat(res, disp_fn));
1995         buffer_.errors("Parse");
1996         updateMetrics(false);
1997 }
1998
1999
2000 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
2001 {
2002         int x = 0;
2003         int y = 0;
2004         int lastw = 0;
2005
2006         // Addup contribution of nested insets, from inside to outside,
2007         // keeping the outer paragraph for a special handling below
2008         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2009                 CursorSlice const & sl = dit[i];
2010                 int xx = 0;
2011                 int yy = 0;
2012                 
2013                 // get relative position inside sl.inset()
2014                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2015                 
2016                 // Make relative position inside of the edited inset relative to sl.inset()
2017                 x += xx;
2018                 y += yy;
2019                 
2020                 // In case of an RTL inset, the edited inset will be positioned to the left
2021                 // of xx:yy
2022                 if (sl.text()) {
2023                         bool boundary_i = boundary && i + 1 == dit.depth();
2024                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2025                         if (rtl)
2026                                 x -= lastw;
2027                 }
2028
2029                 // remember width for the case that sl.inset() is positioned in an RTL inset
2030                 if (i && dit[i - 1].text()) {
2031                         // If this Inset is inside a Text Inset, retrieve the Dimension
2032                         // from the containing text instead of using Inset::dimension() which
2033                         // might not be implemented.
2034                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2035                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2036                         // to be rewritten in light of the new design.
2037                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2038                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2039                         lastw = dim.wid;
2040                 } else {
2041                         Dimension const dim = sl.inset().dimension(*this);
2042                         lastw = dim.wid;
2043                 }
2044                 
2045                 //lyxerr << "Cursor::getPos, i: "
2046                 // << i << " x: " << xx << " y: " << y << endl;
2047         }
2048
2049         // Add contribution of initial rows of outermost paragraph
2050         CursorSlice const & sl = dit[0];
2051         TextMetrics const & tm = textMetrics(sl.text());
2052         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2053         BOOST_ASSERT(!pm.rows().empty());
2054         y -= pm.rows()[0].ascent();
2055 #if 1
2056         // FIXME: document this mess
2057         size_t rend;
2058         if (sl.pos() > 0 && dit.depth() == 1) {
2059                 int pos = sl.pos();
2060                 if (pos && boundary)
2061                         --pos;
2062 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
2063                 rend = pm.pos2row(pos);
2064         } else
2065                 rend = pm.pos2row(sl.pos());
2066 #else
2067         size_t rend = pm.pos2row(sl.pos());
2068 #endif
2069         for (size_t rit = 0; rit != rend; ++rit)
2070                 y += pm.rows()[rit].height();
2071         y += pm.rows()[rend].ascent();
2072         
2073         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2074         
2075         // Make relative position from the nested inset now bufferview absolute.
2076         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2077         x += xx;
2078         
2079         // In the RTL case place the nested inset at the left of the cursor in 
2080         // the outer paragraph
2081         bool boundary_1 = boundary && 1 == dit.depth();
2082         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2083         if (rtl)
2084                 x -= lastw;
2085         
2086         return Point(x, y);
2087 }
2088
2089
2090 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2091 {
2092         CursorSlice const & bot = dit.bottom();
2093         TextMetrics const & tm = textMetrics(bot.text());
2094         if (!tm.has(bot.pit()))
2095                 return Point(-1, -1);
2096
2097         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2098         p.y_ += tm.parMetrics(bot.pit()).position();
2099         return p;
2100 }
2101
2102
2103 void BufferView::draw(frontend::Painter & pain)
2104 {
2105         PainterInfo pi(this, pain);
2106         // Should the whole screen, including insets, be refreshed?
2107         // FIXME: We should also distinguish DecorationUpdate to avoid text
2108         // drawing if possible. This is not possible to do easily right now
2109         // because of the single backing pixmap.
2110         pi.full_repaint = d->metrics_info_.update_strategy != SingleParUpdate;
2111
2112         if (pi.full_repaint)
2113                 // Clear background (if not delegated to rows)
2114                 pain.fillRectangle(0, d->metrics_info_.y1, width_,
2115                         d->metrics_info_.y2 - d->metrics_info_.y1,
2116                         buffer_.inset().backgroundColor());
2117
2118         LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
2119         Text & text = buffer_.text();
2120         TextMetrics const & tm = d->text_metrics_[&text];
2121         int y = d->metrics_info_.y1 + tm.parMetrics(d->metrics_info_.p1).ascent();
2122         if (!pi.full_repaint)
2123                 tm.drawParagraph(pi, d->metrics_info_.p1, 0, y);
2124         else
2125                 tm.draw(pi, 0, y);
2126         LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING  ***" << endl;
2127
2128         // and grey out above (should not happen later)
2129 //      lyxerr << "par ascent: " << text.getPar(d->metrics_info_.p1).ascent() << endl;
2130         if (d->metrics_info_.y1 > 0
2131                 && d->metrics_info_.update_strategy == FullScreenUpdate)
2132                 pain.fillRectangle(0, 0, width_, d->metrics_info_.y1, Color_bottomarea);
2133
2134         // and possibly grey out below
2135 //      lyxerr << "par descent: " << text.getPar(d->metrics_info_.p1).ascent() << endl;
2136         if (d->metrics_info_.y2 < height_
2137                 && d->metrics_info_.update_strategy == FullScreenUpdate)
2138                 pain.fillRectangle(0, d->metrics_info_.y2, width_,
2139                         height_ - d->metrics_info_.y2, Color_bottomarea);
2140 }
2141
2142
2143 void BufferView::message(docstring const & msg)
2144 {
2145         if (d->gui_)
2146                 d->gui_->message(msg);
2147 }
2148
2149
2150 void BufferView::showDialog(std::string const & name)
2151 {
2152         if (d->gui_)
2153                 d->gui_->showDialog(name);
2154 }
2155
2156
2157 void BufferView::showDialogWithData(std::string const & name,
2158         std::string const & data)
2159 {
2160         if (d->gui_)
2161                 d->gui_->showDialogWithData(name, data);
2162 }
2163
2164
2165 void BufferView::showInsetDialog(std::string const & name,
2166         std::string const & data, Inset * inset)
2167 {
2168         if (d->gui_)
2169                 d->gui_->showInsetDialog(name, data, inset);
2170 }
2171
2172
2173 void BufferView::updateDialog(std::string const & name, std::string const & data)
2174 {
2175         if (d->gui_)
2176                 d->gui_->updateDialog(name, data);
2177 }
2178
2179
2180 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2181 {
2182         d->gui_ = gui;
2183 }
2184
2185
2186 // FIXME: Move this out of BufferView again
2187 docstring BufferView::contentsOfPlaintextFile(string const & f,
2188         bool asParagraph)
2189 {
2190         FileName fname(f);
2191
2192         if (fname.empty()) {
2193                 FileDialog dlg(_("Select file to insert"),
2194                                    ( asParagraph
2195                                      ? LFUN_FILE_INSERT_PLAINTEXT_PARA 
2196                                      : LFUN_FILE_INSERT_PLAINTEXT) );
2197
2198                 FileDialog::Result result =
2199                         dlg.open(from_utf8(buffer().filePath()),
2200                                      FileFilterList(), docstring());
2201
2202                 if (result.first == FileDialog::Later)
2203                         return docstring();
2204
2205                 fname = makeAbsPath(to_utf8(result.second));
2206
2207                 if (fname.empty())
2208                         return docstring();
2209         }
2210
2211         if (!fs::is_readable(fname.toFilesystemEncoding())) {
2212                 docstring const error = from_ascii(strerror(errno));
2213                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2214                 docstring const text =
2215                   bformat(_("Could not read the specified document\n"
2216                             "%1$s\ndue to the error: %2$s"), file, error);
2217                 Alert::error(_("Could not read file"), text);
2218                 return docstring();
2219         }
2220
2221         ifstream ifs(fname.toFilesystemEncoding().c_str());
2222         if (!ifs) {
2223                 docstring const error = from_ascii(strerror(errno));
2224                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2225                 docstring const text =
2226                   bformat(_("Could not open the specified document\n"
2227                             "%1$s\ndue to the error: %2$s"), file, error);
2228                 Alert::error(_("Could not open file"), text);
2229                 return docstring();
2230         }
2231
2232         ifs.unsetf(std::ios::skipws);
2233         istream_iterator<char> ii(ifs);
2234         istream_iterator<char> end;
2235 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2236         // We use this until the compilers get better...
2237         std::vector<char> tmp;
2238         copy(ii, end, back_inserter(tmp));
2239         string const tmpstr(tmp.begin(), tmp.end());
2240 #else
2241         // This is what we want to use and what we will use once the
2242         // compilers get good enough.
2243         //string tmpstr(ii, end); // yet a reason for using std::string
2244         // alternate approach to get the file into a string:
2245         string tmpstr;
2246         copy(ii, end, back_inserter(tmpstr));
2247 #endif
2248
2249         // FIXME UNICODE: We don't know the encoding of the file
2250         docstring file_content = from_utf8(tmpstr);
2251         if (file_content.empty()) {
2252                 Alert::error(_("Reading not UTF-8 encoded file"),
2253                              _("The file is not UTF-8 encoded.\n"
2254                                "It will be read as local 8Bit-encoded.\n"
2255                                "If this does not give the correct result\n"
2256                                "then please change the encoding of the file\n"
2257                                "to UTF-8 with a program other than LyX.\n"));
2258                 file_content = from_local8bit(tmpstr);
2259         }
2260
2261         return normalize_c(file_content);
2262 }
2263
2264
2265 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2266 {
2267         docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2268
2269         if (tmpstr.empty())
2270                 return;
2271
2272         Cursor & cur = cursor();
2273         cap::replaceSelection(cur);
2274         buffer_.undo().recordUndo(cur);
2275         if (asParagraph)
2276                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2277         else
2278                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2279 }
2280
2281 } // namespace lyx