]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
PrefShortcuts: list all shortcuts (bound and unbound), using a better implementation
[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 "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "LyX.h"
39 #include "lyxfind.h"
40 #include "LyXFunc.h"
41 #include "Layout.h"
42 #include "LyXRC.h"
43 #include "MetricsInfo.h"
44 #include "Paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "ParIterator.h"
48 #include "Session.h"
49 #include "Text.h"
50 #include "TextClass.h"
51 #include "TextMetrics.h"
52 #include "TexRow.h"
53 #include "VSpace.h"
54 #include "WordLangTuple.h"
55
56
57 #include "insets/InsetBibtex.h"
58 #include "insets/InsetCommand.h" // ChangeRefs
59 #include "insets/InsetRef.h"
60 #include "insets/InsetText.h"
61
62 #include "frontends/alert.h"
63 #include "frontends/Delegates.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/Package.h"
75 #include "support/types.h"
76 #include "support/fs_extras.h"
77
78 #include <boost/bind.hpp>
79 #include <boost/current_function.hpp>
80 #include <boost/next_prior.hpp>
81 #include <boost/filesystem/operations.hpp>
82
83 #include <cerrno>
84 #include <fstream>
85 #include <functional>
86 #include <vector>
87
88 using std::distance;
89 using std::endl;
90 using std::ifstream;
91 using std::istringstream;
92 using std::istream_iterator;
93 using std::make_pair;
94 using std::min;
95 using std::max;
96 using std::mem_fun_ref;
97 using std::string;
98 using std::vector;
99
100 namespace fs = boost::filesystem;
101
102 namespace lyx {
103
104 using support::addPath;
105 using support::bformat;
106 using support::FileFilterList;
107 using support::FileName;
108 using support::fileSearch;
109 using support::isDirWriteable;
110 using support::isFileReadable;
111 using support::makeDisplayPath;
112 using support::makeAbsPath;
113 using support::package;
114
115 namespace Alert = frontend::Alert;
116
117 namespace {
118
119 /// Return an inset of this class if it exists at the current cursor position
120 template <class T>
121 T * getInsetByCode(Cursor const & cur, InsetCode code)
122 {
123         DocIterator it = cur;
124         Inset * inset = it.nextInset();
125         if (inset && inset->lyxCode() == code)
126                 return static_cast<T*>(inset);
127         return 0;
128 }
129
130
131 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
132         bool same_content);
133
134 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
135         string const & contents)
136 {
137         DocIterator tmpdit = dit;
138
139         while (tmpdit) {
140                 Inset const * inset = tmpdit.nextInset();
141                 if (inset
142                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
143                     && (contents.empty() ||
144                     static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
145                         dit = tmpdit;
146                         return true;
147                 }
148                 tmpdit.forwardInset();
149         }
150
151         return false;
152 }
153
154
155 /// Looks for next inset with one of the the given code
156 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
157         bool same_content)
158 {
159         string contents;
160         DocIterator tmpdit = dit;
161         tmpdit.forwardInset();
162         if (!tmpdit)
163                 return false;
164
165         if (same_content) {
166                 Inset const * inset = tmpdit.nextInset();
167                 if (inset
168                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
169                         contents = static_cast<InsetCommand const *>(inset)->getContents();
170                 }
171         }
172
173         if (!findNextInset(tmpdit, codes, contents)) {
174                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
175                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
176                         if (!findNextInset(tmpdit, codes, contents))
177                                 return false;
178                 } else
179                         return false;
180         }
181
182         dit = tmpdit;
183         return true;
184 }
185
186
187 /// Looks for next inset with the given code
188 void findInset(DocIterator & dit, InsetCode code, bool same_content)
189 {
190         findInset(dit, vector<InsetCode>(1, code), same_content);
191 }
192
193
194 /// Moves cursor to the next inset with one of the given codes.
195 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
196                bool same_content)
197 {
198         Cursor tmpcur = bv->cursor();
199         if (!findInset(tmpcur, codes, same_content)) {
200                 bv->cursor().message(_("No more insets"));
201                 return;
202         }
203
204         tmpcur.clearSelection();
205         bv->setCursor(tmpcur);
206 }
207
208
209 /// Moves cursor to the next inset with given code.
210 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
211 {
212         gotoInset(bv, vector<InsetCode>(1, code), same_content);
213 }
214
215
216
217 /// the type of outline operation
218 enum OutlineOp {
219         OutlineUp, // Move this header with text down
220         OutlineDown,   // Move this header with text up
221         OutlineIn, // Make this header deeper
222         OutlineOut // Make this header shallower
223 };
224
225
226 void outline(OutlineOp mode, Cursor & cur)
227 {
228         Buffer & buf = cur.buffer();
229         pit_type & pit = cur.pit();
230         ParagraphList & pars = buf.text().paragraphs();
231         ParagraphList::iterator bgn = pars.begin();
232         // The first paragraph of the area to be copied:
233         ParagraphList::iterator start = boost::next(bgn, pit);
234         // The final paragraph of area to be copied:
235         ParagraphList::iterator finish = start;
236         ParagraphList::iterator end = pars.end();
237
238         TextClass::const_iterator lit =
239                 buf.params().getTextClass().begin();
240         TextClass::const_iterator const lend =
241                 buf.params().getTextClass().end();
242
243         int const thistoclevel = start->layout()->toclevel;
244         int toclevel;
245         switch (mode) {
246                 case OutlineUp: {
247                         // Move out (down) from this section header
248                         if (finish != end)
249                                 ++finish;
250                         // Seek the one (on same level) below
251                         for (; finish != end; ++finish) {
252                                 toclevel = finish->layout()->toclevel;
253                                 if (toclevel != Layout::NOT_IN_TOC
254                                     && toclevel <= thistoclevel) {
255                                         break;
256                                 }
257                         }
258                         ParagraphList::iterator dest = start;
259                         // Move out (up) from this header
260                         if (dest == bgn)
261                                 break;
262                         // Search previous same-level header above
263                         do {
264                                 --dest;
265                                 toclevel = dest->layout()->toclevel;
266                         } while(dest != bgn
267                                 && (toclevel == Layout::NOT_IN_TOC
268                                     || toclevel > thistoclevel));
269                         // Not found; do nothing
270                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
271                                 break;
272                         pit_type const newpit = std::distance(bgn, dest);
273                         pit_type const len = std::distance(start, finish);
274                         pit_type const deletepit = pit + len;
275                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
276                         pars.insert(dest, start, finish);
277                         start = boost::next(pars.begin(), deletepit);
278                         pit = newpit;
279                         pars.erase(start, finish);
280                         break;
281                 }
282                 case OutlineDown: {
283                         // Go down out of current header:
284                         if (finish != end)
285                                 ++finish;
286                         // Find next same-level header:
287                         for (; finish != end; ++finish) {
288                                 toclevel = finish->layout()->toclevel;
289                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
290                                         break;
291                         }
292                         ParagraphList::iterator dest = finish;
293                         // Go one down from *this* header:
294                         if (dest != end)
295                                 ++dest;
296                         else
297                                 break;
298                         // Go further down to find header to insert in front of:
299                         for (; dest != end; ++dest) {
300                                 toclevel = dest->layout()->toclevel;
301                                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
302                                         break;
303                         }
304                         // One such was found:
305                         pit_type newpit = std::distance(bgn, dest);
306                         pit_type const len = std::distance(start, finish);
307                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
308                         pars.insert(dest, start, finish);
309                         start = boost::next(bgn, pit);
310                         pit = newpit - len;
311                         pars.erase(start, finish);
312                         break;
313                 }
314                 case OutlineIn:
315                         buf.undo().recordUndo(cur);
316                         for (; lit != lend; ++lit) {
317                                 if ((*lit)->toclevel == thistoclevel + 1 &&
318                                     start->layout()->labeltype == (*lit)->labeltype) {
319                                         start->layout((*lit));
320                                         break;
321                                 }
322                         }
323                         break;
324                 case OutlineOut:
325                         buf.undo().recordUndo(cur);
326                         for (; lit != lend; ++lit) {
327                                 if ((*lit)->toclevel == thistoclevel - 1 &&
328                                     start->layout()->labeltype == (*lit)->labeltype) {
329                                         start->layout((*lit));
330                                         break;
331                                 }
332                         }
333                         break;
334                 default:
335                         break;
336         }
337 }
338
339 /// A map from a Text to the associated text metrics
340 typedef std::map<Text const *, TextMetrics> TextMetricsCache;
341
342 } // anon namespace
343
344
345 /////////////////////////////////////////////////////////////////////
346 //
347 // BufferView
348 //
349 /////////////////////////////////////////////////////////////////////
350
351 struct BufferView::Private
352 {
353         Private(BufferView & bv): wh_(0), cursor_(bv),
354                 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
355                 need_centering_(false), last_inset_(0), gui_(0)
356         {}
357
358         ///
359         ScrollbarParameters scrollbarParameters_;
360         ///
361         ViewMetricsInfo metrics_info_;
362         ///
363         CoordCache coord_cache_;
364
365         /// Estimated average par height for scrollbar.
366         int wh_;
367         /// this is used to handle XSelection events in the right manner.
368         struct {
369                 CursorSlice cursor;
370                 CursorSlice anchor;
371                 bool set;
372         } xsel_cache_;
373         ///
374         Cursor cursor_;
375         ///
376         bool multiparsel_cache_;
377         ///
378         pit_type anchor_ref_;
379         ///
380         int offset_ref_;
381         ///
382         bool need_centering_;
383
384         /// keyboard mapping object.
385         Intl intl_;
386
387         /// last visited inset.
388         /** kept to send setMouseHover(false).
389           * Not owned, so don't delete.
390           */
391         Inset * last_inset_;
392
393         mutable TextMetricsCache text_metrics_;
394
395         /// Whom to notify.
396         /** Not owned, so don't delete.
397           */
398         frontend::GuiBufferViewDelegate * gui_;
399 };
400
401
402 BufferView::BufferView(Buffer & buf)
403         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
404 {
405         d->xsel_cache_.set = false;
406         d->intl_.initKeyMapper(lyxrc.use_kbmap);
407
408         d->cursor_.push(buffer_.inset());
409         d->cursor_.resetAnchor();
410         d->cursor_.setCurrentFont();
411
412         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
413                 graphics::Previews::get().generateBufferPreviews(buffer_);
414 }
415
416
417 BufferView::~BufferView()
418 {
419         // current buffer is going to be switched-off, save cursor pos
420         // Ideally, the whole cursor stack should be saved, but session
421         // currently can only handle bottom (whole document) level pit and pos.
422         // That is to say, if a cursor is in a nested inset, it will be
423         // restore to the left of the top level inset.
424         LyX::ref().session().lastFilePos().save(
425                 support::FileName(buffer_.fileName()),
426                 boost::tie(d->cursor_.bottom().pit(), d->cursor_.bottom().pos()) );
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());
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_.buildMacros();
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                 FileName(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_SCREEN_UP:
924         case LFUN_SCREEN_DOWN:
925                 flag.enabled(true);
926                 break;
927
928         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
929         // everywhere else before this can enabled:
930         case LFUN_SCREEN_UP_SELECT:
931         case LFUN_SCREEN_DOWN_SELECT:
932                 flag.enabled(false);
933                 break;
934
935         case LFUN_LAYOUT_TABULAR:
936                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
937                 break;
938
939         case LFUN_LAYOUT:
940         case LFUN_LAYOUT_PARAGRAPH:
941                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
942                 break;
943
944         case LFUN_INSET_SETTINGS: {
945                 InsetCode code = cur.inset().lyxCode();
946                 bool enable = false;
947                 switch (code) {
948                         case TABULAR_CODE:
949                                 enable = cmd.argument() == "tabular";
950                                 break;
951                         case ERT_CODE:
952                                 enable = cmd.argument() == "ert";
953                                 break;
954                         case FLOAT_CODE:
955                                 enable = cmd.argument() == "float";
956                                 break;
957                         case WRAP_CODE:
958                                 enable = cmd.argument() == "wrap";
959                                 break;
960                         case NOTE_CODE:
961                                 enable = cmd.argument() == "note";
962                                 break;
963                         case BRANCH_CODE:
964                                 enable = cmd.argument() == "branch";
965                                 break;
966                         case BOX_CODE:
967                                 enable = cmd.argument() == "box";
968                                 break;
969                         case LISTINGS_CODE:
970                                 enable = cmd.argument() == "listings";
971                                 break;
972                         default:
973                                 break;
974                 }
975                 flag.enabled(enable);
976                 break;
977         }
978
979         case LFUN_DIALOG_SHOW_NEW_INSET:
980                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
981                         cur.inset().lyxCode() != LISTINGS_CODE);
982                 if (cur.inset().lyxCode() == CAPTION_CODE) {
983                         FuncStatus flag;
984                         if (cur.inset().getStatus(cur, cmd, flag))
985                                 return flag;
986                 }
987                 break;
988
989         default:
990                 flag.enabled(false);
991         }
992
993         return flag;
994 }
995
996
997 Update::flags BufferView::dispatch(FuncRequest const & cmd)
998 {
999         //lyxerr << BOOST_CURRENT_FUNCTION
1000         //       << [ cmd = " << cmd << "]" << endl;
1001
1002         // Make sure that the cached BufferView is correct.
1003         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
1004                 << " action[" << cmd.action << ']'
1005                 << " arg[" << to_utf8(cmd.argument()) << ']'
1006                 << " x[" << cmd.x << ']'
1007                 << " y[" << cmd.y << ']'
1008                 << " button[" << cmd.button() << ']'
1009                 << endl;
1010
1011         Cursor & cur = d->cursor_;
1012         // Default Update flags.
1013         Update::flags updateFlags = Update::Force | Update::FitCursor;
1014
1015         switch (cmd.action) {
1016
1017         case LFUN_UNDO:
1018                 cur.message(_("Undo"));
1019                 cur.clearSelection();
1020                 if (!cur.textUndo()) {
1021                         cur.message(_("No further undo information"));
1022                         updateFlags = Update::None;
1023                 }
1024                 break;
1025
1026         case LFUN_REDO:
1027                 cur.message(_("Redo"));
1028                 cur.clearSelection();
1029                 if (!cur.textRedo()) {
1030                         cur.message(_("No further redo information"));
1031                         updateFlags = Update::None;
1032                 }
1033                 break;
1034
1035         case LFUN_FILE_INSERT:
1036                 // FIXME UNICODE
1037                 menuInsertLyXFile(to_utf8(cmd.argument()));
1038                 break;
1039
1040         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1041                 // FIXME UNICODE
1042                 insertPlaintextFile(to_utf8(cmd.argument()), true);
1043                 break;
1044
1045         case LFUN_FILE_INSERT_PLAINTEXT:
1046                 // FIXME UNICODE
1047                 insertPlaintextFile(to_utf8(cmd.argument()), false);
1048                 break;
1049
1050         case LFUN_FONT_STATE:
1051                 cur.message(cur.currentState());
1052                 break;
1053
1054         case LFUN_BOOKMARK_SAVE:
1055                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1056                 break;
1057
1058         case LFUN_LABEL_GOTO: {
1059                 docstring label = cmd.argument();
1060                 if (label.empty()) {
1061                         InsetRef * inset =
1062                                 getInsetByCode<InsetRef>(d->cursor_,
1063                                                          REF_CODE);
1064                         if (inset) {
1065                                 label = inset->getParam("reference");
1066                                 // persistent=false: use temp_bookmark
1067                                 saveBookmark(0);
1068                         }
1069                 }
1070
1071                 if (!label.empty())
1072                         gotoLabel(label);
1073                 break;
1074         }
1075
1076         case LFUN_PARAGRAPH_GOTO: {
1077                 int const id = convert<int>(to_utf8(cmd.argument()));
1078                 int i = 0;
1079                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1080                         b = theBufferList().next(b)) {
1081
1082                         ParIterator par = b->getParFromID(id);
1083                         if (par == b->par_iterator_end()) {
1084                                 LYXERR(Debug::INFO)
1085                                         << "No matching paragraph found! ["
1086                                         << id << "]." << endl;
1087                         } else {
1088                                 LYXERR(Debug::INFO)
1089                                         << "Paragraph " << par->id()
1090                                         << " found in buffer `"
1091                                         << b->fileName() << "'." << endl;
1092
1093                                 if (b == &buffer_) {
1094                                         // Set the cursor
1095                                         setCursor(makeDocIterator(par, 0));
1096                                 } else {
1097                                         // Switch to other buffer view and resend cmd
1098                                         theLyXFunc().dispatch(FuncRequest(
1099                                                 LFUN_BUFFER_SWITCH, b->fileName()));
1100                                         theLyXFunc().dispatch(cmd);
1101                                         updateFlags = Update::None;
1102                                 }
1103                                 break;
1104                         }
1105                         ++i;
1106                 }
1107                 break;
1108         }
1109
1110         case LFUN_OUTLINE_UP:
1111                 outline(OutlineUp, d->cursor_);
1112                 d->cursor_.text()->setCursor(d->cursor_, d->cursor_.pit(), 0);
1113                 updateLabels(buffer_);
1114                 break;
1115         case LFUN_OUTLINE_DOWN:
1116                 outline(OutlineDown, d->cursor_);
1117                 d->cursor_.text()->setCursor(d->cursor_, d->cursor_.pit(), 0);
1118                 updateLabels(buffer_);
1119                 break;
1120         case LFUN_OUTLINE_IN:
1121                 outline(OutlineIn, d->cursor_);
1122                 updateLabels(buffer_);
1123                 break;
1124         case LFUN_OUTLINE_OUT:
1125                 outline(OutlineOut, d->cursor_);
1126                 updateLabels(buffer_);
1127                 break;
1128
1129         case LFUN_NOTE_NEXT:
1130                 gotoInset(this, NOTE_CODE, false);
1131                 break;
1132
1133         case LFUN_REFERENCE_NEXT: {
1134                 vector<InsetCode> tmp;
1135                 tmp.push_back(LABEL_CODE);
1136                 tmp.push_back(REF_CODE);
1137                 gotoInset(this, tmp, true);
1138                 break;
1139         }
1140
1141         case LFUN_CHANGES_TRACK:
1142                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1143                 break;
1144
1145         case LFUN_CHANGES_OUTPUT:
1146                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1147                 if (buffer_.params().outputChanges) {
1148                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1149                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1150                                           LaTeXFeatures::isAvailable("xcolor");
1151
1152                         if (!dvipost && !xcolorsoul) {
1153                                 Alert::warning(_("Changes not shown in LaTeX output"),
1154                                                _("Changes will not be highlighted in LaTeX output, "
1155                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1156                                                  "Please install these packages or redefine "
1157                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1158                         } else if (!xcolorsoul) {
1159                                 Alert::warning(_("Changes not shown in LaTeX output"),
1160                                                _("Changes will not be highlighted in LaTeX output "
1161                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1162                                                  "Please install both packages or redefine "
1163                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1164                         }
1165                 }
1166                 break;
1167
1168         case LFUN_CHANGE_NEXT:
1169                 findNextChange(this);
1170                 break;
1171
1172         case LFUN_CHANGES_MERGE:
1173                 if (findNextChange(this))
1174                         showDialog("changes");
1175                 break;
1176
1177         case LFUN_ALL_CHANGES_ACCEPT:
1178                 // select complete document
1179                 d->cursor_.reset(buffer_.inset());
1180                 d->cursor_.selHandle(true);
1181                 buffer_.text().cursorBottom(d->cursor_);
1182                 // accept everything in a single step to support atomic undo
1183                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1184                 break;
1185
1186         case LFUN_ALL_CHANGES_REJECT:
1187                 // select complete document
1188                 d->cursor_.reset(buffer_.inset());
1189                 d->cursor_.selHandle(true);
1190                 buffer_.text().cursorBottom(d->cursor_);
1191                 // reject everything in a single step to support atomic undo
1192                 // Note: reject does not work recursively; the user may have to repeat the operation
1193                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1194                 break;
1195
1196         case LFUN_WORD_FIND:
1197                 find(this, cmd);
1198                 break;
1199
1200         case LFUN_WORD_REPLACE: {
1201                 bool has_deleted = false;
1202                 if (cur.selection()) {
1203                         DocIterator beg = cur.selectionBegin();
1204                         DocIterator end = cur.selectionEnd();
1205                         if (beg.pit() == end.pit()) {
1206                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1207                                         if (cur.paragraph().isDeleted(p))
1208                                                 has_deleted = true;
1209                                 }
1210                         }
1211                 }
1212                 replace(this, cmd, has_deleted);
1213                 break;
1214         }
1215
1216         case LFUN_MARK_OFF:
1217                 cur.clearSelection();
1218                 cur.resetAnchor();
1219                 cur.message(from_utf8(N_("Mark off")));
1220                 break;
1221
1222         case LFUN_MARK_ON:
1223                 cur.clearSelection();
1224                 cur.mark() = true;
1225                 cur.resetAnchor();
1226                 cur.message(from_utf8(N_("Mark on")));
1227                 break;
1228
1229         case LFUN_MARK_TOGGLE:
1230                 cur.clearSelection();
1231                 if (cur.mark()) {
1232                         cur.mark() = false;
1233                         cur.message(from_utf8(N_("Mark removed")));
1234                 } else {
1235                         cur.mark() = true;
1236                         cur.message(from_utf8(N_("Mark set")));
1237                 }
1238                 cur.resetAnchor();
1239                 break;
1240
1241         case LFUN_SCREEN_RECENTER:
1242                 center();
1243                 break;
1244
1245         case LFUN_BIBTEX_DATABASE_ADD: {
1246                 Cursor tmpcur = d->cursor_;
1247                 findInset(tmpcur, BIBTEX_CODE, false);
1248                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1249                                                 BIBTEX_CODE);
1250                 if (inset) {
1251                         if (inset->addDatabase(to_utf8(cmd.argument())))
1252                                 buffer_.updateBibfilesCache();
1253                 }
1254                 break;
1255         }
1256
1257         case LFUN_BIBTEX_DATABASE_DEL: {
1258                 Cursor tmpcur = d->cursor_;
1259                 findInset(tmpcur, BIBTEX_CODE, false);
1260                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1261                                                 BIBTEX_CODE);
1262                 if (inset) {
1263                         if (inset->delDatabase(to_utf8(cmd.argument())))
1264                                 buffer_.updateBibfilesCache();
1265                 }
1266                 break;
1267         }
1268
1269         case LFUN_WORDS_COUNT: {
1270                 DocIterator from, to;
1271                 if (cur.selection()) {
1272                         from = cur.selectionBegin();
1273                         to = cur.selectionEnd();
1274                 } else {
1275                         from = doc_iterator_begin(buffer_.inset());
1276                         to = doc_iterator_end(buffer_.inset());
1277                 }
1278                 int const count = countWords(from, to);
1279                 docstring message;
1280                 if (count != 1) {
1281                         if (cur.selection())
1282                                 message = bformat(_("%1$d words in selection."),
1283                                           count);
1284                                 else
1285                                         message = bformat(_("%1$d words in document."),
1286                                                           count);
1287                 }
1288                 else {
1289                         if (cur.selection())
1290                                 message = _("One word in selection.");
1291                         else
1292                                 message = _("One word in document.");
1293                 }
1294
1295                 Alert::information(_("Count words"), message);
1296         }
1297                 break;
1298
1299         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1300                 // turn compression on/off
1301                 buffer_.params().compressed = !buffer_.params().compressed;
1302                 break;
1303
1304         case LFUN_NEXT_INSET_TOGGLE: {
1305                 // this is the real function we want to invoke
1306                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1307                 // if there is an inset at cursor, see whether it
1308                 // wants to toggle.
1309                 Inset * inset = cur.nextInset();
1310                 if (inset) {
1311                         if (inset->isActive()) {
1312                                 Cursor tmpcur = cur;
1313                                 tmpcur.pushLeft(*inset);
1314                                 inset->dispatch(tmpcur, tmpcmd);
1315                                 if (tmpcur.result().dispatched()) {
1316                                         cur.dispatched();
1317                                 }
1318                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1319                                 inset->edit(cur, true);
1320                         }
1321                 }
1322                 // if it did not work, try the underlying inset.
1323                 if (!cur.result().dispatched())
1324                         cur.dispatch(tmpcmd);
1325
1326                 if (cur.result().dispatched())
1327                         cur.clearSelection();
1328
1329                 break;
1330         }
1331
1332         case LFUN_SCREEN_UP:
1333         case LFUN_SCREEN_DOWN: {
1334                 Point p = getPos(cur, cur.boundary());
1335                 if (p.y_ < 0 || p.y_ > height_) {
1336                         // The cursor is off-screen so recenter before proceeding.
1337                         center();
1338                         updateMetrics(false);
1339                         //FIXME: updateMetrics() does not update paragraph position
1340                         // This is done at draw() time. So we need a redraw!
1341                         buffer_.changed();
1342                         p = getPos(cur, cur.boundary());
1343                 }
1344                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1345                 cur.reset(buffer_.inset());
1346                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1347                 //FIXME: what to do with cur.x_target()?
1348                 cur.finishUndo();
1349                 // The metrics are already up to date. see scroll()
1350                 updateFlags = Update::None;
1351                 break;
1352         }
1353
1354         case LFUN_SCREEN_UP_SELECT:
1355         case LFUN_SCREEN_DOWN_SELECT: {
1356                 cur.selHandle(true);
1357                 size_t initial_depth = cur.depth();
1358                 Point const p = getPos(cur, cur.boundary());
1359                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1360                 // FIXME: We need to verify if the cursor stayed within an inset...
1361                 //cur.reset(buffer_.inset());
1362                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1363                 cur.finishUndo();
1364                 while (cur.depth() > initial_depth) {
1365                         cur.forwardInset();
1366                 }
1367                 // FIXME: we need to do a redraw again because of the selection
1368                 buffer_.changed();
1369                 updateFlags = Update::Force | Update::FitCursor;
1370                 break;
1371         }
1372
1373         default:
1374                 updateFlags = Update::None;
1375         }
1376
1377         return updateFlags;
1378 }
1379
1380
1381 docstring const BufferView::requestSelection()
1382 {
1383         Cursor & cur = d->cursor_;
1384
1385         if (!cur.selection()) {
1386                 d->xsel_cache_.set = false;
1387                 return docstring();
1388         }
1389
1390         if (!d->xsel_cache_.set ||
1391             cur.top() != d->xsel_cache_.cursor ||
1392             cur.anchor_.top() != d->xsel_cache_.anchor)
1393         {
1394                 d->xsel_cache_.cursor = cur.top();
1395                 d->xsel_cache_.anchor = cur.anchor_.top();
1396                 d->xsel_cache_.set = cur.selection();
1397                 return cur.selectionAsString(false);
1398         }
1399         return docstring();
1400 }
1401
1402
1403 void BufferView::clearSelection()
1404 {
1405         d->cursor_.clearSelection();
1406         // Clear the selection buffer. Otherwise a subsequent
1407         // middle-mouse-button paste would use the selection buffer,
1408         // not the more current external selection.
1409         cap::clearSelection();
1410         d->xsel_cache_.set = false;
1411         // The buffer did not really change, but this causes the
1412         // redraw we need because we cleared the selection above.
1413         buffer_.changed();
1414 }
1415
1416
1417 void BufferView::resize(int width, int height)
1418 {
1419         // Update from work area
1420         width_ = width;
1421         height_ = height;
1422
1423         updateMetrics(false);
1424 }
1425
1426
1427 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1428 {
1429         TextMetrics & tm = d->text_metrics_[&text];
1430         Inset * inset = tm.checkInsetHit(x, y);
1431         if (!inset)
1432                 return 0;
1433
1434         if (!inset->descendable())
1435                 // No need to go further down if the inset is not
1436                 // descendable.
1437                 return inset;
1438
1439         size_t cell_number = inset->nargs();
1440         // Check all the inner cell.
1441         for (size_t i = 0; i != cell_number; ++i) {
1442                 Text const * inner_text = inset->getText(i);
1443                 if (inner_text) {
1444                         // Try deeper.
1445                         Inset const * inset_deeper =
1446                                 getCoveringInset(*inner_text, x, y);
1447                         if (inset_deeper)
1448                                 return inset_deeper;
1449                 }
1450         }
1451
1452         return inset;
1453 }
1454
1455
1456 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1457 {
1458         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1459
1460         // This is only called for mouse related events including
1461         // LFUN_FILE_OPEN generated by drag-and-drop.
1462         FuncRequest cmd = cmd0;
1463
1464         Cursor cur(*this);
1465         cur.push(buffer_.inset());
1466         cur.selection() = d->cursor_.selection();
1467
1468         // Either the inset under the cursor or the
1469         // surrounding Text will handle this event.
1470
1471         // make sure we stay within the screen...
1472         cmd.y = min(max(cmd.y, -1), height_);
1473
1474         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1475
1476                 // Get inset under mouse, if there is one.
1477                 Inset const * covering_inset =
1478                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1479                 if (covering_inset == d->last_inset_)
1480                         // Same inset, no need to do anything...
1481                         return;
1482
1483                 bool need_redraw = false;
1484                 // const_cast because of setMouseHover().
1485                 Inset * inset = const_cast<Inset *>(covering_inset);
1486                 if (d->last_inset_)
1487                         // Remove the hint on the last hovered inset (if any).
1488                         need_redraw |= d->last_inset_->setMouseHover(false);
1489                 if (inset)
1490                         // Highlighted the newly hovered inset (if any).
1491                         need_redraw |= inset->setMouseHover(true);
1492                 d->last_inset_ = inset;
1493                 if (!need_redraw)
1494                         return;
1495
1496                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1497                 // not expose the button for redraw. We adjust here the metrics dimension
1498                 // to enable a full redraw in any case as this is not costly.
1499                 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
1500                 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1501                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1502                 int y1 = firstpm.second->position() - firstpm.second->ascent();
1503                 int y2 = lastpm.second->position() + lastpm.second->descent();
1504                 d->metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1505                         FullScreenUpdate, buffer_.text().paragraphs().size());
1506                 // Reinitialize anchor to first pit.
1507                 d->anchor_ref_ = firstpm.first;
1508                 d->offset_ref_ = -y1;
1509                 LYXERR(Debug::PAINTING)
1510                         << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1511                         << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1512                         << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1513
1514                 // This event (moving without mouse click) is not passed further.
1515                 // This should be changed if it is further utilized.
1516                 buffer_.changed();
1517                 return;
1518         }
1519
1520         // Build temporary cursor.
1521         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1522
1523         // Put anchor at the same position.
1524         cur.resetAnchor();
1525
1526         // Try to dispatch to an non-editable inset near this position
1527         // via the temp cursor. If the inset wishes to change the real
1528         // cursor it has to do so explicitly by using
1529         //  cur.bv().cursor() = cur;  (or similar)
1530         if (inset)
1531                 inset->dispatch(cur, cmd);
1532
1533         // Now dispatch to the temporary cursor. If the real cursor should
1534         // be modified, the inset's dispatch has to do so explicitly.
1535         if (!cur.result().dispatched())
1536                 cur.dispatch(cmd);
1537
1538         //Do we have a selection?
1539         theSelection().haveSelection(cursor().selection());
1540
1541         // If the command has been dispatched,
1542         if (cur.result().dispatched()
1543                 // an update is asked,
1544                 && cur.result().update())
1545                 processUpdateFlags(cur.result().update());
1546 }
1547
1548
1549 void BufferView::scroll(int y)
1550 {
1551         if (y > 0)
1552                 scrollDown(y);
1553         else if (y < 0)
1554                 scrollUp(-y);
1555 }
1556
1557
1558 void BufferView::scrollDown(int offset)
1559 {
1560         Text * text = &buffer_.text();
1561         TextMetrics & tm = d->text_metrics_[text];
1562         int ymax = height_ + offset;
1563         while (true) {
1564                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1565                 int bottom_pos = last.second->position() + last.second->descent();
1566                 if (last.first + 1 == int(text->paragraphs().size())) {
1567                         if (bottom_pos <= height_)
1568                                 return;
1569                         offset = min(offset, bottom_pos - height_);
1570                         break;
1571                 }
1572                 if (bottom_pos > ymax)
1573                         break;
1574                 tm.newParMetricsDown();
1575         }
1576         d->offset_ref_ += offset;
1577         updateMetrics(false);
1578         buffer_.changed();
1579 }
1580
1581
1582 void BufferView::scrollUp(int offset)
1583 {
1584         Text * text = &buffer_.text();
1585         TextMetrics & tm = d->text_metrics_[text];
1586         int ymin = - offset;
1587         while (true) {
1588                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1589                 int top_pos = first.second->position() - first.second->ascent();
1590                 if (first.first == 0) {
1591                         if (top_pos >= 0)
1592                                 return;
1593                         offset = min(offset, - top_pos);
1594                         break;
1595                 }
1596                 if (top_pos < ymin)
1597                         break;
1598                 tm.newParMetricsUp();
1599         }
1600         d->offset_ref_ -= offset;
1601         updateMetrics(false);
1602         buffer_.changed();
1603 }
1604
1605
1606 void BufferView::setCursorFromRow(int row)
1607 {
1608         int tmpid = -1;
1609         int tmppos = -1;
1610
1611         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1612
1613         d->cursor_.reset(buffer_.inset());
1614         if (tmpid == -1)
1615                 buffer_.text().setCursor(d->cursor_, 0, 0);
1616         else
1617                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1618 }
1619
1620
1621 void BufferView::gotoLabel(docstring const & label)
1622 {
1623         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1624                 vector<docstring> labels;
1625                 it->getLabelList(buffer_, labels);
1626                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1627                         setCursor(it);
1628                         processUpdateFlags(Update::FitCursor);
1629                         return;
1630                 }
1631         }
1632 }
1633
1634
1635 TextMetrics const & BufferView::textMetrics(Text const * t) const
1636 {
1637         return const_cast<BufferView *>(this)->textMetrics(t);
1638 }
1639
1640
1641 TextMetrics & BufferView::textMetrics(Text const * t)
1642 {
1643         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1644         if (tmc_it == d->text_metrics_.end()) {
1645                 tmc_it = d->text_metrics_.insert(
1646                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1647         }
1648         return tmc_it->second;
1649 }
1650
1651
1652 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1653                 pit_type pit) const
1654 {
1655         return textMetrics(t).parMetrics(pit);
1656 }
1657
1658
1659 int BufferView::workHeight() const
1660 {
1661         return height_;
1662 }
1663
1664
1665 void BufferView::setCursor(DocIterator const & dit)
1666 {
1667         size_t const n = dit.depth();
1668         for (size_t i = 0; i < n; ++i)
1669                 dit[i].inset().edit(d->cursor_, true);
1670
1671         d->cursor_.setCursor(dit);
1672         d->cursor_.selection() = false;
1673 }
1674
1675
1676 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1677 {
1678         // Would be wrong to delete anything if we have a selection.
1679         if (cur.selection())
1680                 return false;
1681
1682         bool need_anchor_change = false;
1683         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1684                 need_anchor_change);
1685
1686         if (need_anchor_change)
1687                 cur.resetAnchor();
1688
1689         if (!changed)
1690                 return false;
1691
1692         updateLabels(buffer_);
1693
1694         updateMetrics(false);
1695         buffer_.changed();
1696         return true;
1697 }
1698
1699
1700 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1701 {
1702         BOOST_ASSERT(&cur.bv() == this);
1703
1704         if (!select)
1705                 // this event will clear selection so we save selection for
1706                 // persistent selection
1707                 cap::saveSelection(cursor());
1708
1709         // Has the cursor just left the inset?
1710         bool badcursor = false;
1711         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1712         if (leftinset)
1713                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1714
1715         // FIXME: shift-mouse selection doesn't work well across insets.
1716         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1717
1718         // do the dEPM magic if needed
1719         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1720         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1721         // the leftinset bool would not be necessary (badcursor instead).
1722         bool update = leftinset;
1723         if (!do_selection && !badcursor && d->cursor_.inTexted())
1724                 update |= checkDepm(cur, d->cursor_);
1725
1726         // if the cursor was in an empty script inset and the new
1727         // position is in the nucleus of the inset, notifyCursorLeaves
1728         // will kill the script inset itself. So we check all the
1729         // elements of the cursor to make sure that they are correct.
1730         // For an example, see bug 2933:
1731         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1732         // The code below could maybe be moved to a DocIterator method.
1733         //lyxerr << "cur before " << cur <<std::endl;
1734         DocIterator dit(cur.inset());
1735         dit.push_back(cur.bottom());
1736         size_t i = 1;
1737         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1738                 dit.push_back(cur[i]);
1739                 ++i;
1740         }
1741         //lyxerr << "5 cur after" << dit <<std::endl;
1742
1743         d->cursor_.setCursor(dit);
1744         d->cursor_.boundary(cur.boundary());
1745         if (do_selection)
1746                 d->cursor_.setSelection();
1747         else
1748                 d->cursor_.clearSelection();
1749
1750         d->cursor_.finishUndo();
1751         return update;
1752 }
1753
1754
1755 void BufferView::putSelectionAt(DocIterator const & cur,
1756                                 int length, bool backwards)
1757 {
1758         d->cursor_.clearSelection();
1759
1760         setCursor(cur);
1761
1762         if (length) {
1763                 if (backwards) {
1764                         d->cursor_.pos() += length;
1765                         d->cursor_.setSelection(d->cursor_, -length);
1766                 } else
1767                         d->cursor_.setSelection(d->cursor_, length);
1768         }
1769 }
1770
1771
1772 Cursor & BufferView::cursor()
1773 {
1774         return d->cursor_;
1775 }
1776
1777
1778 Cursor const & BufferView::cursor() const
1779 {
1780         return d->cursor_;
1781 }
1782
1783
1784 pit_type BufferView::anchor_ref() const
1785 {
1786         return d->anchor_ref_;
1787 }
1788
1789
1790 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1791 {
1792         return d->metrics_info_;
1793 }
1794
1795
1796 bool BufferView::singleParUpdate()
1797 {
1798         Text & buftext = buffer_.text();
1799         pit_type const bottom_pit = d->cursor_.bottom().pit();
1800         TextMetrics & tm = textMetrics(&buftext);
1801         int old_height = tm.parMetrics(bottom_pit).height();
1802
1803         // In Single Paragraph mode, rebreak only
1804         // the (main text, not inset!) paragraph containing the cursor.
1805         // (if this paragraph contains insets etc., rebreaking will
1806         // recursively descend)
1807         tm.redoParagraph(bottom_pit);
1808         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1809         if (pm.height() != old_height)
1810                 // Paragraph height has changed so we cannot proceed to
1811                 // the singlePar optimisation.
1812                 return false;
1813
1814         int y1 = pm.position() - pm.ascent();
1815         int y2 = pm.position() + pm.descent();
1816         d->metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1817                 SingleParUpdate, buftext.paragraphs().size());
1818         LYXERR(Debug::PAINTING)
1819                 << BOOST_CURRENT_FUNCTION
1820                 << "\ny1: " << y1
1821                 << " y2: " << y2
1822                 << " pit: " << bottom_pit
1823                 << " singlepar: 1"
1824                 << endl;
1825         return true;
1826 }
1827
1828
1829 void BufferView::updateMetrics(bool singlepar)
1830 {
1831         if (singlepar && singleParUpdate())
1832                 // No need to update the full screen metrics.
1833                 return;
1834
1835         Text & buftext = buffer_.text();
1836         pit_type const npit = int(buftext.paragraphs().size());
1837
1838         if (d->anchor_ref_ > int(npit - 1)) {
1839                 d->anchor_ref_ = int(npit - 1);
1840                 d->offset_ref_ = 0;
1841         }
1842
1843         // Clear out the position cache in case of full screen redraw,
1844         d->coord_cache_.clear();
1845
1846         // Clear out paragraph metrics to avoid having invalid metrics
1847         // in the cache from paragraphs not relayouted below
1848         // The complete text metrics will be redone.
1849         d->text_metrics_.clear();
1850
1851         TextMetrics & tm = textMetrics(&buftext);
1852
1853         pit_type const pit = d->anchor_ref_;
1854         int pit1 = pit;
1855         int pit2 = pit;
1856
1857         // Rebreak anchor paragraph.
1858         tm.redoParagraph(pit);
1859
1860         // Take care of anchor offset if case a recentering is needed.
1861         updateOffsetRef();
1862
1863         int y0 = tm.parMetrics(pit).ascent() - d->offset_ref_;
1864
1865         // Redo paragraphs above anchor if necessary.
1866         int y1 = y0;
1867         while (y1 > 0 && pit1 > 0) {
1868                 y1 -= tm.parMetrics(pit1).ascent();
1869                 --pit1;
1870                 tm.redoParagraph(pit1);
1871                 y1 -= tm.parMetrics(pit1).descent();
1872         }
1873
1874         // Take care of ascent of first line
1875         y1 -= tm.parMetrics(pit1).ascent();
1876
1877         // Normalize anchor for next time
1878         d->anchor_ref_ = pit1;
1879         d->offset_ref_ = -y1;
1880
1881         // Grey at the beginning is ugly
1882         if (pit1 == 0 && y1 > 0) {
1883                 y0 -= y1;
1884                 y1 = 0;
1885                 d->anchor_ref_ = 0;
1886         }
1887
1888         // Redo paragraphs below the anchor if necessary.
1889         int y2 = y0;
1890         while (y2 < height_ && pit2 < int(npit) - 1) {
1891                 y2 += tm.parMetrics(pit2).descent();
1892                 ++pit2;
1893                 tm.redoParagraph(pit2);
1894                 y2 += tm.parMetrics(pit2).ascent();
1895         }
1896
1897         // Take care of descent of last line
1898         y2 += tm.parMetrics(pit2).descent();
1899
1900         LYXERR(Debug::PAINTING)
1901                 << BOOST_CURRENT_FUNCTION
1902                 << "\n y1: " << y1
1903                 << " y2: " << y2
1904                 << " pit1: " << pit1
1905                 << " pit2: " << pit2
1906                 << " npit: " << npit
1907                 << " singlepar: 0"
1908                 << endl;
1909
1910         d->metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1911                 FullScreenUpdate, npit);
1912
1913         if (lyxerr.debugging(Debug::WORKAREA)) {
1914                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1915                 d->coord_cache_.dump();
1916         }
1917 }
1918
1919
1920 void BufferView::menuInsertLyXFile(string const & filenm)
1921 {
1922         BOOST_ASSERT(d->cursor_.inTexted());
1923         string filename = filenm;
1924
1925         if (filename.empty()) {
1926                 // Launch a file browser
1927                 // FIXME UNICODE
1928                 string initpath = lyxrc.document_path;
1929                 string const trypath = buffer_.filePath();
1930                 // If directory is writeable, use this as default.
1931                 if (isDirWriteable(FileName(trypath)))
1932                         initpath = trypath;
1933
1934                 // FIXME UNICODE
1935                 FileDialog fileDlg(_("Select LyX document to insert"),
1936                         LFUN_FILE_INSERT,
1937                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1938                         make_pair(_("Examples|#E#e"),
1939                                     from_utf8(addPath(package().system_support().absFilename(),
1940                                     "examples"))));
1941
1942                 FileDialog::Result result =
1943                         fileDlg.open(from_utf8(initpath),
1944                                      FileFilterList(_("LyX Documents (*.lyx)")),
1945                                      docstring());
1946
1947                 if (result.first == FileDialog::Later)
1948                         return;
1949
1950                 // FIXME UNICODE
1951                 filename = to_utf8(result.second);
1952
1953                 // check selected filename
1954                 if (filename.empty()) {
1955                         // emit message signal.
1956                         message(_("Canceled."));
1957                         return;
1958                 }
1959         }
1960
1961         // Get absolute path of file and add ".lyx"
1962         // to the filename if necessary
1963         filename = fileSearch(string(), filename, "lyx").absFilename();
1964
1965         docstring const disp_fn = makeDisplayPath(filename);
1966         // emit message signal.
1967         message(bformat(_("Inserting document %1$s..."), disp_fn));
1968
1969         docstring res;
1970         Buffer buf("", false);
1971         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1972                 ErrorList & el = buffer_.errorList("Parse");
1973                 // Copy the inserted document error list into the current buffer one.
1974                 el = buf.errorList("Parse");
1975                 buffer_.undo().recordUndo(d->cursor_);
1976                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1977                                              buf.params().getTextClassPtr(), el);
1978                 res = _("Document %1$s inserted.");
1979         } else
1980                 res = _("Could not insert document %1$s");
1981
1982         // emit message signal.
1983         message(bformat(res, disp_fn));
1984         buffer_.errors("Parse");
1985         updateMetrics(false);
1986 }
1987
1988
1989 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1990 {
1991         int x = 0;
1992         int y = 0;
1993         int lastw = 0;
1994
1995         // Addup contribution of nested insets, from inside to outside,
1996         // keeping the outer paragraph for a special handling below
1997         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1998                 CursorSlice const & sl = dit[i];
1999                 int xx = 0;
2000                 int yy = 0;
2001                 
2002                 // get relative position inside sl.inset()
2003                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
2004                 
2005                 // Make relative position inside of the edited inset relative to sl.inset()
2006                 x += xx;
2007                 y += yy;
2008                 
2009                 // In case of an RTL inset, the edited inset will be positioned to the left
2010                 // of xx:yy
2011                 if (sl.text()) {
2012                         bool boundary_i = boundary && i + 1 == dit.depth();
2013                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2014                         if (rtl)
2015                                 x -= lastw;
2016                 }
2017
2018                 // remember width for the case that sl.inset() is positioned in an RTL inset
2019                 if (i && dit[i - 1].text()) {
2020                         // If this Inset is inside a Text Inset, retrieve the Dimension
2021                         // from the containing text instead of using Inset::dimension() which
2022                         // might not be implemented.
2023                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
2024                         // elimination of Inset::dim_ cache. This coordOffset() method needs
2025                         // to be rewritten in light of the new design.
2026                         Dimension const & dim = parMetrics(dit[i - 1].text(),
2027                                 dit[i - 1].pit()).insetDimension(&sl.inset());
2028                         lastw = dim.wid;
2029                 } else {
2030                         Dimension const dim = sl.inset().dimension(*this);
2031                         lastw = dim.wid;
2032                 }
2033                 
2034                 //lyxerr << "Cursor::getPos, i: "
2035                 // << i << " x: " << xx << " y: " << y << endl;
2036         }
2037
2038         // Add contribution of initial rows of outermost paragraph
2039         CursorSlice const & sl = dit[0];
2040         TextMetrics const & tm = textMetrics(sl.text());
2041         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2042         BOOST_ASSERT(!pm.rows().empty());
2043         y -= pm.rows()[0].ascent();
2044 #if 1
2045         // FIXME: document this mess
2046         size_t rend;
2047         if (sl.pos() > 0 && dit.depth() == 1) {
2048                 int pos = sl.pos();
2049                 if (pos && boundary)
2050                         --pos;
2051 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << std::endl;
2052                 rend = pm.pos2row(pos);
2053         } else
2054                 rend = pm.pos2row(sl.pos());
2055 #else
2056         size_t rend = pm.pos2row(sl.pos());
2057 #endif
2058         for (size_t rit = 0; rit != rend; ++rit)
2059                 y += pm.rows()[rit].height();
2060         y += pm.rows()[rend].ascent();
2061         
2062         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2063         
2064         // Make relative position from the nested inset now bufferview absolute.
2065         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
2066         x += xx;
2067         
2068         // In the RTL case place the nested inset at the left of the cursor in 
2069         // the outer paragraph
2070         bool boundary_1 = boundary && 1 == dit.depth();
2071         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2072         if (rtl)
2073                 x -= lastw;
2074         
2075         return Point(x, y);
2076 }
2077
2078
2079 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
2080 {
2081         CursorSlice const & bot = dit.bottom();
2082         TextMetrics const & tm = textMetrics(bot.text());
2083         if (!tm.has(bot.pit()))
2084                 return Point(-1, -1);
2085
2086         Point p = coordOffset(dit, boundary); // offset from outer paragraph
2087         p.y_ += tm.parMetrics(bot.pit()).position();
2088         return p;
2089 }
2090
2091
2092 void BufferView::draw(frontend::Painter & pain)
2093 {
2094         PainterInfo pi(this, pain);
2095         // Should the whole screen, including insets, be refreshed?
2096         // FIXME: We should also distinguish DecorationUpdate to avoid text
2097         // drawing if possible. This is not possible to do easily right now
2098         // because of the single backing pixmap.
2099         pi.full_repaint = d->metrics_info_.update_strategy != SingleParUpdate;
2100
2101         if (pi.full_repaint)
2102                 // Clear background (if not delegated to rows)
2103                 pain.fillRectangle(0, d->metrics_info_.y1, width_,
2104                         d->metrics_info_.y2 - d->metrics_info_.y1,
2105                         buffer_.inset().backgroundColor());
2106
2107         LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
2108         Text & text = buffer_.text();
2109         TextMetrics const & tm = d->text_metrics_[&text];
2110         int y = d->metrics_info_.y1 + tm.parMetrics(d->metrics_info_.p1).ascent();
2111         if (!pi.full_repaint)
2112                 tm.drawParagraph(pi, d->metrics_info_.p1, 0, y);
2113         else
2114                 tm.draw(pi, 0, y);
2115         LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING  ***" << endl;
2116
2117         // and grey out above (should not happen later)
2118 //      lyxerr << "par ascent: " << text.getPar(d->metrics_info_.p1).ascent() << endl;
2119         if (d->metrics_info_.y1 > 0
2120                 && d->metrics_info_.update_strategy == FullScreenUpdate)
2121                 pain.fillRectangle(0, 0, width_, d->metrics_info_.y1, Color::bottomarea);
2122
2123         // and possibly grey out below
2124 //      lyxerr << "par descent: " << text.getPar(d->metrics_info_.p1).ascent() << endl;
2125         if (d->metrics_info_.y2 < height_
2126                 && d->metrics_info_.update_strategy == FullScreenUpdate)
2127                 pain.fillRectangle(0, d->metrics_info_.y2, width_,
2128                         height_ - d->metrics_info_.y2, Color::bottomarea);
2129 }
2130
2131
2132 void BufferView::message(docstring const & msg)
2133 {
2134         if (d->gui_)
2135                 d->gui_->message(msg);
2136 }
2137
2138
2139 void BufferView::showDialog(std::string const & name)
2140 {
2141         if (d->gui_)
2142                 d->gui_->showDialog(name);
2143 }
2144
2145
2146 void BufferView::showDialogWithData(std::string const & name,
2147         std::string const & data)
2148 {
2149         if (d->gui_)
2150                 d->gui_->showDialogWithData(name, data);
2151 }
2152
2153
2154 void BufferView::showInsetDialog(std::string const & name,
2155         std::string const & data, Inset * inset)
2156 {
2157         if (d->gui_)
2158                 d->gui_->showInsetDialog(name, data, inset);
2159 }
2160
2161
2162 void BufferView::updateDialog(std::string const & name, std::string const & data)
2163 {
2164         if (d->gui_)
2165                 d->gui_->updateDialog(name, data);
2166 }
2167
2168
2169 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2170 {
2171         d->gui_ = gui;
2172 }
2173
2174
2175 // FIXME: Move this out of BufferView again
2176 docstring BufferView::contentsOfPlaintextFile(string const & f,
2177         bool asParagraph)
2178 {
2179         FileName fname(f);
2180
2181         if (fname.empty()) {
2182                 FileDialog fileDlg(_("Select file to insert"),
2183                                    ( asParagraph
2184                                      ? LFUN_FILE_INSERT_PLAINTEXT_PARA 
2185                                      : LFUN_FILE_INSERT_PLAINTEXT) );
2186
2187                 FileDialog::Result result =
2188                         fileDlg.open(from_utf8(buffer().filePath()),
2189                                      FileFilterList(), docstring());
2190
2191                 if (result.first == FileDialog::Later)
2192                         return docstring();
2193
2194                 fname = makeAbsPath(to_utf8(result.second));
2195
2196                 if (fname.empty())
2197                         return docstring();
2198         }
2199
2200         if (!fs::is_readable(fname.toFilesystemEncoding())) {
2201                 docstring const error = from_ascii(strerror(errno));
2202                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2203                 docstring const text =
2204                   bformat(_("Could not read the specified document\n"
2205                             "%1$s\ndue to the error: %2$s"), file, error);
2206                 Alert::error(_("Could not read file"), text);
2207                 return docstring();
2208         }
2209
2210         ifstream ifs(fname.toFilesystemEncoding().c_str());
2211         if (!ifs) {
2212                 docstring const error = from_ascii(strerror(errno));
2213                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2214                 docstring const text =
2215                   bformat(_("Could not open the specified document\n"
2216                             "%1$s\ndue to the error: %2$s"), file, error);
2217                 Alert::error(_("Could not open file"), text);
2218                 return docstring();
2219         }
2220
2221         ifs.unsetf(std::ios::skipws);
2222         istream_iterator<char> ii(ifs);
2223         istream_iterator<char> end;
2224 #if !defined(USE_INCLUDED_STRING) && !defined(STD_STRING_IS_GOOD)
2225         // We use this until the compilers get better...
2226         std::vector<char> tmp;
2227         copy(ii, end, back_inserter(tmp));
2228         string const tmpstr(tmp.begin(), tmp.end());
2229 #else
2230         // This is what we want to use and what we will use once the
2231         // compilers get good enough.
2232         //string tmpstr(ii, end); // yet a reason for using std::string
2233         // alternate approach to get the file into a string:
2234         string tmpstr;
2235         copy(ii, end, back_inserter(tmpstr));
2236 #endif
2237
2238         // FIXME UNICODE: We don't know the encoding of the file
2239         docstring file_content = from_utf8(tmpstr);
2240         if (file_content.empty()) {
2241                 Alert::error(_("Reading not UTF-8 encoded file"),
2242                              _("The file is not UTF-8 encoded.\n"
2243                                "It will be read as local 8Bit-encoded.\n"
2244                                "If this does not give the correct result\n"
2245                                "then please change the encoding of the file\n"
2246                                "to UTF-8 with a program other than LyX.\n"));
2247                 file_content = from_local8bit(tmpstr);
2248         }
2249
2250         return normalize_c(file_content);
2251 }
2252
2253
2254 void BufferView::insertPlaintextFile(string const & f, bool asParagraph)
2255 {
2256         docstring const tmpstr = contentsOfPlaintextFile(f, asParagraph);
2257
2258         if (tmpstr.empty())
2259                 return;
2260
2261         Cursor & cur = cursor();
2262         cap::replaceSelection(cur);
2263         buffer_.undo().recordUndo(cur);
2264         if (asParagraph)
2265                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2266         else
2267                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2268 }
2269
2270 } // namespace lyx