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