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