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