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