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