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