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