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