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