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