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