]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
Give PageDown/Up scrolling a sane behaviour. Does not work with selection yet...
[features.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "callback.h" // added for Dispatch functions
25 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "debug.h"
28 #include "DispatchResult.h"
29 #include "ErrorList.h"
30 #include "factory.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "gettext.h"
35 #include "Intl.h"
36 #include "InsetIterator.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "LyXRC.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "Session.h"
50 #include "TexRow.h"
51 #include "Text.h"
52 #include "TextClass.h"
53 #include "toc.h"
54 #include "Undo.h"
55 #include "VSpace.h"
56 #include "WordLangTuple.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/Package.h"
75 #include "support/types.h"
76
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
79
80 #include <functional>
81 #include <vector>
82
83 using std::distance;
84 using std::endl;
85 using std::istringstream;
86 using std::make_pair;
87 using std::min;
88 using std::max;
89 using std::mem_fun_ref;
90 using std::string;
91 using std::vector;
92
93
94 namespace lyx {
95
96 using support::addPath;
97 using support::bformat;
98 using support::FileFilterList;
99 using support::FileName;
100 using support::fileSearch;
101 using support::isDirWriteable;
102 using support::isFileReadable;
103 using support::makeDisplayPath;
104 using support::package;
105
106 namespace Alert = frontend::Alert;
107
108 namespace {
109
110 /// Return an inset of this class if it exists at the current cursor position
111 template <class T>
112 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 {
114         T * inset = 0;
115         DocIterator it = cur;
116         if (it.nextInset() &&
117             it.nextInset()->lyxCode() == code) {
118                 inset = static_cast<T*>(it.nextInset());
119         }
120         return inset;
121 }
122
123 } // anon namespace
124
125
126 BufferView::BufferView(Buffer & buf)
127         : width_(0), height_(0), buffer_(buf), wh_(0),
128           cursor_(*this),
129           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
130           need_centering_(false), intl_(new Intl), last_inset_(0)
131 {
132         xsel_cache_.set = false;
133         intl_->initKeyMapper(lyxrc.use_kbmap);
134
135         cursor_.push(buffer_.inset());
136         cursor_.resetAnchor();
137         cursor_.setCurrentFont();
138
139         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
140                 graphics::Previews::get().generateBufferPreviews(buffer_);
141 }
142
143
144 BufferView::~BufferView()
145 {
146         // current buffer is going to be switched-off, save cursor pos
147         // Ideally, the whole cursor stack should be saved, but session
148         // currently can only handle bottom (whole document) level pit and pos.
149         // That is to say, if a cursor is in a nested inset, it will be
150         // restore to the left of the top level inset.
151         LyX::ref().session().lastFilePos().save(
152                 support::FileName(buffer_.fileName()),
153                 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
154 }
155
156
157 Buffer & BufferView::buffer()
158 {
159         return buffer_;
160 }
161
162
163 Buffer const & BufferView::buffer() const
164 {
165         return buffer_;
166 }
167
168
169 bool BufferView::fitCursor()
170 {
171         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
172                 frontend::FontMetrics const & fm =
173                         theFontMetrics(cursor_.getFont());
174                 int const asc = fm.maxAscent();
175                 int const des = fm.maxDescent();
176                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
177                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
178                         return false;
179         }
180         center();
181         return true;
182 }
183
184
185 bool BufferView::multiParSel()
186 {
187         if (!cursor_.selection())
188                 return false;
189         bool ret = multiparsel_cache_;
190         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
191         // Either this, or previous selection spans paragraphs
192         return ret || multiparsel_cache_;
193 }
194
195
196 bool BufferView::update(Update::flags flags)
197 {
198         // last_inset_ points to the last visited inset. This pointer may become
199         // invalid because of keyboard editing. Since all such operations
200         // causes screen update(), I reset last_inset_ to avoid such a problem.
201         last_inset_ = 0;
202         // This is close to a hot-path.
203         LYXERR(Debug::DEBUG)
204                 << BOOST_CURRENT_FUNCTION
205                 << "[fitcursor = " << (flags & Update::FitCursor)
206                 << ", forceupdate = " << (flags & Update::Force)
207                 << ", singlepar = " << (flags & Update::SinglePar)
208                 << "]  buffer: " << &buffer_ << endl;
209
210         // Update macro store
211         if (!(cursor().inMathed() && cursor().inMacroMode()))
212                 buffer_.buildMacros();
213
214         // Now do the first drawing step if needed. This consists on updating
215         // the CoordCache in updateMetrics().
216         // The second drawing step is done in WorkArea::redraw() if needed.
217
218         // Case when no explicit update is requested.
219         if (!flags) {
220                 // no need to redraw anything.
221                 metrics_info_.update_strategy = NoScreenUpdate;
222                 return false;
223         }
224
225         if (flags == Update::Decoration) {
226                 metrics_info_.update_strategy = DecorationUpdate;
227                 return true;
228         }
229
230         if (flags == Update::FitCursor
231                 || flags == (Update::Decoration | Update::FitCursor)) {
232                 bool const fit_cursor = fitCursor();
233                 // tell the frontend to update the screen if needed.
234                 if (fit_cursor) {
235                         updateMetrics(false);
236                         return true;
237                 }
238                 if (flags & Update::Decoration) {
239                         metrics_info_.update_strategy = DecorationUpdate;
240                         return true;
241                 }
242                 // no screen update is needed.
243                 metrics_info_.update_strategy = NoScreenUpdate;
244                 return false;
245         }
246
247         bool full_metrics = flags & Update::Force;
248         if (flags & Update::MultiParSel)
249                 full_metrics |= multiParSel();
250
251         bool const single_par = !full_metrics;
252         updateMetrics(single_par);
253
254         if (flags & Update::FitCursor && fitCursor())
255                 updateMetrics(false);
256
257         // tell the frontend to update the screen.
258         return true;
259 }
260
261
262 void BufferView::updateScrollbar()
263 {
264         Text & t = buffer_.text();
265         TextMetrics & tm = text_metrics_[&t];
266
267         int const parsize = int(t.paragraphs().size() - 1);
268         if (anchor_ref_ >  parsize)  {
269                 anchor_ref_ = parsize;
270                 offset_ref_ = 0;
271         }
272
273         LYXERR(Debug::GUI)
274                 << BOOST_CURRENT_FUNCTION
275                 << " Updating scrollbar: height: " << t.paragraphs().size()
276                 << " curr par: " << cursor_.bottom().pit()
277                 << " default height " << defaultRowHeight() << endl;
278
279         // It would be better to fix the scrollbar to understand
280         // values in [0..1] and divide everything by wh
281
282         // estimated average paragraph height:
283         if (wh_ == 0)
284                 wh_ = height_ / 4;
285
286         int h = tm.parMetrics(anchor_ref_).height();
287
288         // Normalize anchor/offset (MV):
289         while (offset_ref_ > h && anchor_ref_ < parsize) {
290                 anchor_ref_++;
291                 offset_ref_ -= h;
292                 h = tm.parMetrics(anchor_ref_).height();
293         }
294         // Look at paragraph heights on-screen
295         int sumh = 0;
296         int nh = 0;
297         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
298                 if (sumh > height_)
299                         break;
300                 int const h2 = tm.parMetrics(pit).height();
301                 sumh += h2;
302                 nh++;
303         }
304
305         BOOST_ASSERT(nh);
306         int const hav = sumh / nh;
307         // More realistic average paragraph height
308         if (hav > wh_)
309                 wh_ = hav;
310
311         BOOST_ASSERT(h);
312         scrollbarParameters_.height = (parsize + 1) * wh_;
313         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
314         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
315 }
316
317
318 ScrollbarParameters const & BufferView::scrollbarParameters() const
319 {
320         return scrollbarParameters_;
321 }
322
323
324 void BufferView::scrollDocView(int value)
325 {
326         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
327                            << "[ value = " << value << "]" << endl;
328
329         Text & t = buffer_.text();
330         TextMetrics & tm = text_metrics_[&t];
331
332         float const bar = value / float(wh_ * t.paragraphs().size());
333
334         anchor_ref_ = int(bar * t.paragraphs().size());
335         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
336                 anchor_ref_ = int(t.paragraphs().size()) - 1;
337
338         tm.redoParagraph(anchor_ref_);
339         int const h = tm.parMetrics(anchor_ref_).height();
340         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
341         updateMetrics(false);
342 }
343
344
345 void BufferView::setCursorFromScrollbar()
346 {
347         TextMetrics & tm = text_metrics_[&buffer_.text()];
348
349         int const height = 2 * defaultRowHeight();
350         int const first = height;
351         int const last = height_ - height;
352         Cursor & cur = cursor_;
353
354         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
355
356         switch (st) {
357         case bv_funcs::CUR_ABOVE:
358                 // We reset the cursor because bv_funcs::status() does not
359                 // work when the cursor is within mathed.
360                 cur.reset(buffer_.inset());
361                 tm.setCursorFromCoordinates(cur, 0, first);
362                 cur.clearSelection();
363                 break;
364         case bv_funcs::CUR_BELOW:
365                 // We reset the cursor because bv_funcs::status() does not
366                 // work when the cursor is within mathed.
367                 cur.reset(buffer_.inset());
368                 tm.setCursorFromCoordinates(cur, 0, last);
369                 cur.clearSelection();
370                 break;
371         case bv_funcs::CUR_INSIDE:
372                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
373                 int const newy = min(last, max(y, first));
374                 if (y != newy) {
375                         cur.reset(buffer_.inset());
376                         tm.setCursorFromCoordinates(cur, 0, newy);
377                 }
378         }
379 }
380
381
382 Change const BufferView::getCurrentChange() const
383 {
384         if (!cursor_.selection())
385                 return Change(Change::UNCHANGED);
386
387         DocIterator dit = cursor_.selectionBegin();
388         return dit.paragraph().lookupChange(dit.pos());
389 }
390
391
392 void BufferView::saveBookmark(unsigned int idx)
393 {
394         // tenatively save bookmark, id and pos will be used to
395         // acturately locate a bookmark in a 'live' lyx session.
396         // pit and pos will be updated with bottom level pit/pos
397         // when lyx exits.
398         LyX::ref().session().bookmarks().save(
399                 FileName(buffer_.fileName()),
400                 cursor_.bottom().pit(),
401                 cursor_.bottom().pos(),
402                 cursor_.paragraph().id(),
403                 cursor_.pos(),
404                 idx
405         );
406         if (idx)
407                 // emit message signal.
408                 message(_("Save bookmark"));
409 }
410
411
412 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
413         int top_id, pos_type top_pos)
414 {
415         bool success = false;
416         DocIterator doc_it;
417
418         cursor_.clearSelection();
419
420         // if a valid par_id is given, try it first
421         // This is the case for a 'live' bookmark when unique paragraph ID
422         // is used to track bookmarks.
423         if (top_id > 0) {
424                 ParIterator par = buffer_.getParFromID(top_id);
425                 if (par != buffer_.par_iterator_end()) {
426                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
427                         // Some slices of the iterator may not be
428                         // reachable (e.g. closed collapsable inset)
429                         // so the dociterator may need to be
430                         // shortened. Otherwise, setCursor may crash
431                         // lyx when the cursor can not be set to these
432                         // insets.
433                         size_t const n = doc_it.depth();
434                         for (size_t i = 0; i < n; ++i)
435                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
436                                         doc_it.resize(i);
437                                         break;
438                                 }
439                         success = true;
440                 }
441         }
442
443         // if top_id == 0, or searching through top_id failed
444         // This is the case for a 'restored' bookmark when only bottom
445         // (document level) pit was saved. Because of this, bookmark
446         // restoration is inaccurate. If a bookmark was within an inset,
447         // it will be restored to the left of the outmost inset that contains
448         // the bookmark.
449         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
450                 doc_it = doc_iterator_begin(buffer_.inset());
451                 doc_it.pit() = bottom_pit;
452                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
453                 success = true;
454         }
455
456         if (success) {
457                 // Note: only bottom (document) level pit is set.
458                 setCursor(doc_it);
459                 // set the current font.
460                 cursor_.setCurrentFont();
461                 // center the screen on this new position.
462                 center();
463         }
464
465         return success;
466 }
467
468
469 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
470 {
471         if (lyxrc.rtl_support) {
472                 if (cursor_.real_current_font.isRightToLeft()) {
473                         if (intl_->keymap == Intl::PRIMARY)
474                                 intl_->keyMapSec();
475                 } else {
476                         if (intl_->keymap == Intl::SECONDARY)
477                                 intl_->keyMapPrim();
478                 }
479         }
480         
481         intl_->getTransManager().translateAndInsert(c, t, cur);
482 }
483
484
485 int BufferView::workWidth() const
486 {
487         return width_;
488 }
489
490
491 void BufferView::updateOffsetRef()
492 {
493         // No need to update offset_ref_ in this case.
494         if (!need_centering_)
495                 return;
496
497         // We are not properly started yet, delay until resizing is
498         // done.
499         if (height_ == 0)
500                 return;
501
502         CursorSlice & bot = cursor_.bottom();
503         TextMetrics & tm = text_metrics_[bot.text()];
504         ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
505         Point p = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary());
506         offset_ref_ = p.y_ + pm.ascent() - height_ / 2;
507
508         need_centering_ = false;
509 }
510
511
512 void BufferView::center()
513 {
514         anchor_ref_ = cursor_.bottom().pit();
515         need_centering_ = true;
516 }
517
518
519 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
520 {
521         FuncStatus flag;
522
523         Cursor & cur = cursor_;
524
525         switch (cmd.action) {
526
527         case LFUN_UNDO:
528                 flag.enabled(!buffer_.undostack().empty());
529                 break;
530         case LFUN_REDO:
531                 flag.enabled(!buffer_.redostack().empty());
532                 break;
533         case LFUN_FILE_INSERT:
534         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
535         case LFUN_FILE_INSERT_PLAINTEXT:
536         case LFUN_BOOKMARK_SAVE:
537                 // FIXME: Actually, these LFUNS should be moved to Text
538                 flag.enabled(cur.inTexted());
539                 break;
540         case LFUN_FONT_STATE:
541         case LFUN_LABEL_INSERT:
542         case LFUN_PARAGRAPH_GOTO:
543         // FIXME handle non-trivially
544         case LFUN_OUTLINE_UP:
545         case LFUN_OUTLINE_DOWN:
546         case LFUN_OUTLINE_IN:
547         case LFUN_OUTLINE_OUT:
548         case LFUN_NOTE_NEXT:
549         case LFUN_REFERENCE_NEXT:
550         case LFUN_WORD_FIND:
551         case LFUN_WORD_REPLACE:
552         case LFUN_MARK_OFF:
553         case LFUN_MARK_ON:
554         case LFUN_MARK_TOGGLE:
555         case LFUN_SCREEN_RECENTER:
556         case LFUN_BIBTEX_DATABASE_ADD:
557         case LFUN_BIBTEX_DATABASE_DEL:
558         case LFUN_WORDS_COUNT:
559         case LFUN_NEXT_INSET_TOGGLE:
560                 flag.enabled(true);
561                 break;
562
563         case LFUN_LABEL_GOTO: {
564                 flag.enabled(!cmd.argument().empty()
565                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
566                 break;
567         }
568
569         case LFUN_CHANGES_TRACK:
570                 flag.enabled(true);
571                 flag.setOnOff(buffer_.params().trackChanges);
572                 break;
573
574         case LFUN_CHANGES_OUTPUT:
575                 flag.enabled(true);
576                 flag.setOnOff(buffer_.params().outputChanges);
577                 break;
578
579         case LFUN_CHANGES_MERGE:
580         case LFUN_CHANGE_NEXT:
581         case LFUN_ALL_CHANGES_ACCEPT:
582         case LFUN_ALL_CHANGES_REJECT:
583                 // TODO: context-sensitive enabling of LFUNs
584                 // In principle, these command should only be enabled if there
585                 // is a change in the document. However, without proper
586                 // optimizations, this will inevitably result in poor performance.
587                 flag.enabled(true);
588                 break;
589
590         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
591                 flag.setOnOff(buffer_.params().compressed);
592                 break;
593         }
594
595         case LFUN_SCREEN_UP:
596         case LFUN_SCREEN_DOWN:
597                 flag.enabled(true);
598                 break;
599
600         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
601         // everywhere else before this can enabled:
602         case LFUN_SCREEN_UP_SELECT:
603         case LFUN_SCREEN_DOWN_SELECT:
604                 flag.enabled(false);
605                 break;
606
607         default:
608                 flag.enabled(false);
609         }
610
611         return flag;
612 }
613
614
615 Update::flags BufferView::dispatch(FuncRequest const & cmd)
616 {
617         //lyxerr << BOOST_CURRENT_FUNCTION
618         //       << [ cmd = " << cmd << "]" << endl;
619
620         // Make sure that the cached BufferView is correct.
621         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
622                 << " action[" << cmd.action << ']'
623                 << " arg[" << to_utf8(cmd.argument()) << ']'
624                 << " x[" << cmd.x << ']'
625                 << " y[" << cmd.y << ']'
626                 << " button[" << cmd.button() << ']'
627                 << endl;
628
629         Cursor & cur = cursor_;
630         // Default Update flags.
631         Update::flags updateFlags = Update::Force | Update::FitCursor;
632
633         switch (cmd.action) {
634
635         case LFUN_UNDO:
636                 cur.message(_("Undo"));
637                 cur.clearSelection();
638                 if (!textUndo(*this)) {
639                         cur.message(_("No further undo information"));
640                         updateFlags = Update::None;
641                 }
642                 break;
643
644         case LFUN_REDO:
645                 cur.message(_("Redo"));
646                 cur.clearSelection();
647                 if (!textRedo(*this)) {
648                         cur.message(_("No further redo information"));
649                         updateFlags = Update::None;
650                 }
651                 break;
652
653         case LFUN_FILE_INSERT:
654                 // FIXME UNICODE
655                 menuInsertLyXFile(to_utf8(cmd.argument()));
656                 break;
657
658         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
659                 // FIXME UNICODE
660                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
661                 break;
662
663         case LFUN_FILE_INSERT_PLAINTEXT:
664                 // FIXME UNICODE
665                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
666                 break;
667
668         case LFUN_FONT_STATE:
669                 cur.message(cur.currentState());
670                 break;
671
672         case LFUN_BOOKMARK_SAVE:
673                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
674                 break;
675
676         case LFUN_LABEL_GOTO: {
677                 docstring label = cmd.argument();
678                 if (label.empty()) {
679                         InsetRef * inset =
680                                 getInsetByCode<InsetRef>(cursor_,
681                                                          Inset::REF_CODE);
682                         if (inset) {
683                                 label = inset->getParam("reference");
684                                 // persistent=false: use temp_bookmark
685                                 saveBookmark(0);
686                         }
687                 }
688
689                 if (!label.empty())
690                         gotoLabel(label);
691                 break;
692         }
693
694         case LFUN_PARAGRAPH_GOTO: {
695                 int const id = convert<int>(to_utf8(cmd.argument()));
696                 int i = 0;
697                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
698                         b = theBufferList().next(b)) {
699
700                         ParIterator par = b->getParFromID(id);
701                         if (par == b->par_iterator_end()) {
702                                 LYXERR(Debug::INFO)
703                                         << "No matching paragraph found! ["
704                                         << id << "]." << endl;
705                         } else {
706                                 LYXERR(Debug::INFO)
707                                         << "Paragraph " << par->id()
708                                         << " found in buffer `"
709                                         << b->fileName() << "'." << endl;
710
711                                 if (b == &buffer_) {
712                                         // Set the cursor
713                                         setCursor(makeDocIterator(par, 0));
714                                 } else {
715                                         // Switch to other buffer view and resend cmd
716                                         theLyXFunc().dispatch(FuncRequest(
717                                                 LFUN_BUFFER_SWITCH, b->fileName()));
718                                         theLyXFunc().dispatch(cmd);
719                                         updateFlags = Update::None;
720                                 }
721                                 break;
722                         }
723                         ++i;
724                 }
725                 break;
726         }
727
728         case LFUN_OUTLINE_UP:
729                 toc::outline(toc::Up, cursor_);
730                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
731                 updateLabels(buffer_);
732                 break;
733         case LFUN_OUTLINE_DOWN:
734                 toc::outline(toc::Down, cursor_);
735                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
736                 updateLabels(buffer_);
737                 break;
738         case LFUN_OUTLINE_IN:
739                 toc::outline(toc::In, cursor_);
740                 updateLabels(buffer_);
741                 break;
742         case LFUN_OUTLINE_OUT:
743                 toc::outline(toc::Out, cursor_);
744                 updateLabels(buffer_);
745                 break;
746
747         case LFUN_NOTE_NEXT:
748                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
749                 break;
750
751         case LFUN_REFERENCE_NEXT: {
752                 vector<Inset_code> tmp;
753                 tmp.push_back(Inset::LABEL_CODE);
754                 tmp.push_back(Inset::REF_CODE);
755                 bv_funcs::gotoInset(this, tmp, true);
756                 break;
757         }
758
759         case LFUN_CHANGES_TRACK:
760                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
761                 break;
762
763         case LFUN_CHANGES_OUTPUT:
764                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
765                 if (buffer_.params().outputChanges) {
766                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
767                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
768                                           LaTeXFeatures::isAvailable("xcolor");
769
770                         if (!dvipost && !xcolorsoul) {
771                                 Alert::warning(_("Changes not shown in LaTeX output"),
772                                                _("Changes will not be highlighted in LaTeX output, "
773                                                  "because neither dvipost nor xcolor/soul are installed.\n"
774                                                  "Please install these packages or redefine "
775                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
776                         } else if (!xcolorsoul) {
777                                 Alert::warning(_("Changes not shown in LaTeX output"),
778                                                _("Changes will not be highlighted in LaTeX output "
779                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
780                                                  "Please install both packages or redefine "
781                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
782                         }
783                 }
784                 break;
785
786         case LFUN_CHANGE_NEXT:
787                 findNextChange(this);
788                 break;
789
790         case LFUN_CHANGES_MERGE:
791                 if (findNextChange(this))
792                         showDialog("changes");
793                 break;
794
795         case LFUN_ALL_CHANGES_ACCEPT:
796                 // select complete document
797                 cursor_.reset(buffer_.inset());
798                 cursor_.selHandle(true);
799                 buffer_.text().cursorBottom(cursor_);
800                 // accept everything in a single step to support atomic undo
801                 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
802                 break;
803
804         case LFUN_ALL_CHANGES_REJECT:
805                 // select complete document
806                 cursor_.reset(buffer_.inset());
807                 cursor_.selHandle(true);
808                 buffer_.text().cursorBottom(cursor_);
809                 // reject everything in a single step to support atomic undo
810                 // Note: reject does not work recursively; the user may have to repeat the operation
811                 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
812                 break;
813
814         case LFUN_WORD_FIND:
815                 find(this, cmd);
816                 break;
817
818         case LFUN_WORD_REPLACE: {
819                 bool has_deleted = false;
820                 if (cur.selection()) {
821                         DocIterator beg = cur.selectionBegin();
822                         DocIterator end = cur.selectionEnd();
823                         if (beg.pit() == end.pit()) {
824                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
825                                         if (cur.paragraph().isDeleted(p))
826                                                 has_deleted = true;
827                                 }
828                         }
829                 }
830                 replace(this, cmd, has_deleted);
831                 break;
832         }
833
834         case LFUN_MARK_OFF:
835                 cur.clearSelection();
836                 cur.resetAnchor();
837                 cur.message(from_utf8(N_("Mark off")));
838                 break;
839
840         case LFUN_MARK_ON:
841                 cur.clearSelection();
842                 cur.mark() = true;
843                 cur.resetAnchor();
844                 cur.message(from_utf8(N_("Mark on")));
845                 break;
846
847         case LFUN_MARK_TOGGLE:
848                 cur.clearSelection();
849                 if (cur.mark()) {
850                         cur.mark() = false;
851                         cur.message(from_utf8(N_("Mark removed")));
852                 } else {
853                         cur.mark() = true;
854                         cur.message(from_utf8(N_("Mark set")));
855                 }
856                 cur.resetAnchor();
857                 break;
858
859         case LFUN_SCREEN_RECENTER:
860                 center();
861                 break;
862
863         case LFUN_BIBTEX_DATABASE_ADD: {
864                 Cursor tmpcur = cursor_;
865                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
866                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
867                                                 Inset::BIBTEX_CODE);
868                 if (inset) {
869                         if (inset->addDatabase(to_utf8(cmd.argument())))
870                                 buffer_.updateBibfilesCache();
871                 }
872                 break;
873         }
874
875         case LFUN_BIBTEX_DATABASE_DEL: {
876                 Cursor tmpcur = cursor_;
877                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
878                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
879                                                 Inset::BIBTEX_CODE);
880                 if (inset) {
881                         if (inset->delDatabase(to_utf8(cmd.argument())))
882                                 buffer_.updateBibfilesCache();
883                 }
884                 break;
885         }
886
887         case LFUN_WORDS_COUNT: {
888                 DocIterator from, to;
889                 if (cur.selection()) {
890                         from = cur.selectionBegin();
891                         to = cur.selectionEnd();
892                 } else {
893                         from = doc_iterator_begin(buffer_.inset());
894                         to = doc_iterator_end(buffer_.inset());
895                 }
896                 int const count = countWords(from, to);
897                 docstring message;
898                 if (count != 1) {
899                         if (cur.selection())
900                                 message = bformat(_("%1$d words in selection."),
901                                           count);
902                                 else
903                                         message = bformat(_("%1$d words in document."),
904                                                           count);
905                 }
906                 else {
907                         if (cur.selection())
908                                 message = _("One word in selection.");
909                         else
910                                 message = _("One word in document.");
911                 }
912
913                 Alert::information(_("Count words"), message);
914         }
915                 break;
916
917         case LFUN_BUFFER_TOGGLE_COMPRESSION:
918                 // turn compression on/off
919                 buffer_.params().compressed = !buffer_.params().compressed;
920                 break;
921
922         case LFUN_NEXT_INSET_TOGGLE: {
923                 // this is the real function we want to invoke
924                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
925                 // if there is an inset at cursor, see whether it
926                 // wants to toggle.
927                 Inset * inset = cur.nextInset();
928                 if (inset) {
929                         if (inset->isActive()) {
930                                 Cursor tmpcur = cur;
931                                 tmpcur.pushLeft(*inset);
932                                 inset->dispatch(tmpcur, tmpcmd);
933                                 if (tmpcur.result().dispatched()) {
934                                         cur.dispatched();
935                                 }
936                         } else if (inset->editable() == Inset::IS_EDITABLE) {
937                                 inset->edit(cur, true);
938                         }
939                 }
940                 // if it did not work, try the underlying inset.
941                 if (!cur.result().dispatched())
942                         cur.dispatch(tmpcmd);
943
944                 if (cur.result().dispatched())
945                         cur.clearSelection();
946
947                 break;
948         }
949
950         case LFUN_SCREEN_UP:
951         case LFUN_SCREEN_DOWN: {
952                 Point const p = bv_funcs::getPos(*this, cur, cur.boundary());
953                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
954                 cur.reset(buffer_.inset());
955                 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
956                 //FIXME: what to do with cur.x_target()?
957                 finishUndo();
958                 // The metrics are already up to date. see scroll()
959                 updateFlags = Update::None;
960                 break;
961         }
962
963         case LFUN_SCREEN_UP_SELECT:
964         case LFUN_SCREEN_DOWN_SELECT: {
965                 cur.selHandle(true);
966                 size_t initial_depth = cur.depth();
967                 Point const p = bv_funcs::getPos(*this, cur, cur.boundary());
968                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
969                 // FIXME: We need to verify if the cursor stayed within an inset...
970                 //cur.reset(buffer_.inset());
971                 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
972                 finishUndo();
973                 while (cur.depth() > initial_depth) {
974                         cur.forwardInset();
975                 }
976                 // FIXME: we need to do a redraw again because of the selection
977                 buffer_.changed();
978                 updateFlags = Update::Force | Update::FitCursor;
979                 break;
980         }
981
982         default:
983                 updateFlags = Update::None;
984         }
985
986         return updateFlags;
987 }
988
989
990 docstring const BufferView::requestSelection()
991 {
992         Cursor & cur = cursor_;
993
994         if (!cur.selection()) {
995                 xsel_cache_.set = false;
996                 return docstring();
997         }
998
999         if (!xsel_cache_.set ||
1000             cur.top() != xsel_cache_.cursor ||
1001             cur.anchor_.top() != xsel_cache_.anchor)
1002         {
1003                 xsel_cache_.cursor = cur.top();
1004                 xsel_cache_.anchor = cur.anchor_.top();
1005                 xsel_cache_.set = cur.selection();
1006                 return cur.selectionAsString(false);
1007         }
1008         return docstring();
1009 }
1010
1011
1012 void BufferView::clearSelection()
1013 {
1014         cursor_.clearSelection();
1015         // Clear the selection buffer. Otherwise a subsequent
1016         // middle-mouse-button paste would use the selection buffer,
1017         // not the more current external selection.
1018         cap::clearSelection();
1019         xsel_cache_.set = false;
1020         // The buffer did not really change, but this causes the
1021         // redraw we need because we cleared the selection above.
1022         buffer_.changed();
1023 }
1024
1025
1026 void BufferView::resize(int width, int height)
1027 {
1028         // Update from work area
1029         width_ = width;
1030         height_ = height;
1031
1032         updateMetrics(false);
1033 }
1034
1035
1036 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1037 {
1038         pit_type pit = text_metrics_[&text].getPitNearY(y);
1039         BOOST_ASSERT(pit != -1);
1040         Paragraph const & par = text.getPar(pit);
1041
1042         LYXERR(Debug::DEBUG)
1043                 << BOOST_CURRENT_FUNCTION
1044                 << ": x: " << x
1045                 << " y: " << y
1046                 << "  pit: " << pit
1047                 << endl;
1048         InsetList::const_iterator iit = par.insetlist.begin();
1049         InsetList::const_iterator iend = par.insetlist.end();
1050         for (; iit != iend; ++iit) {
1051                 Inset * const inset = iit->inset;
1052                 if (inset->covers(*this, x, y)) {
1053                         if (!inset->descendable())
1054                                 // No need to go further down if the inset is not
1055                                 // descendable.
1056                                 return inset;
1057
1058                         size_t cell_number = inset->nargs();
1059                         // Check all the inner cell.
1060                         for (size_t i = 0; i != cell_number; ++i) {
1061                                 Text const * inner_text = inset->getText(i);
1062                                 if (inner_text) {
1063                                         // Try deeper.
1064                                         Inset const * inset_deeper =
1065                                                 getCoveringInset(*inner_text, x, y);
1066                                         if (inset_deeper)
1067                                                 return inset_deeper;
1068                                 }
1069                         }
1070
1071                         LYXERR(Debug::DEBUG)
1072                                 << BOOST_CURRENT_FUNCTION
1073                                 << ": Hit inset: " << inset << endl;
1074                         return inset;
1075                 }
1076         }
1077         LYXERR(Debug::DEBUG)
1078                 << BOOST_CURRENT_FUNCTION
1079                 << ": No inset hit. " << endl;
1080         return 0;
1081 }
1082
1083
1084 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1085 {
1086         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1087
1088         // This is only called for mouse related events including
1089         // LFUN_FILE_OPEN generated by drag-and-drop.
1090         FuncRequest cmd = cmd0;
1091
1092         Cursor cur(*this);
1093         cur.push(buffer_.inset());
1094         cur.selection() = cursor_.selection();
1095
1096         // Either the inset under the cursor or the
1097         // surrounding Text will handle this event.
1098
1099         // make sure we stay within the screen...
1100         cmd.y = min(max(cmd.y, -1), height_);
1101
1102         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1103
1104                 // Get inset under mouse, if there is one.
1105                 Inset const * covering_inset =
1106                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1107                 if (covering_inset == last_inset_)
1108                         // Same inset, no need to do anything...
1109                         return false;
1110
1111                 bool need_redraw = false;
1112                 // const_cast because of setMouseHover().
1113                 Inset * inset = const_cast<Inset *>(covering_inset);
1114                 if (last_inset_)
1115                         // Remove the hint on the last hovered inset (if any).
1116                         need_redraw |= last_inset_->setMouseHover(false);
1117                 if (inset)
1118                         // Highlighted the newly hovered inset (if any).
1119                         need_redraw |= inset->setMouseHover(true);
1120                 last_inset_ = inset;
1121
1122                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1123                 // not expose the button for redraw. We adjust here the metrics dimension
1124                 // to enable a full redraw.
1125                 // FIXME: It is possible to redraw only the area around the button!
1126                 if (need_redraw
1127                         && metrics_info_.update_strategy == SingleParUpdate) {
1128                         // FIXME: It should be possible to redraw only the area around
1129                         // the button by doing this:
1130                         //
1131                         //metrics_info_.singlepar = false;
1132                         //metrics_info_.y1 = ymin of button;
1133                         //metrics_info_.y2 = ymax of button;
1134                         //
1135                         // Unfortunately, BufferView::draw() does not distinguish
1136                         // between background updates and text updates. So we use the hammer
1137                         // solution for now. We could also avoid the updateMetrics() below
1138                         // by using the first and last pit of the CoordCache. Have a look
1139                         // at Text::getPitNearY() to see what I mean.
1140                         //
1141                         //metrics_info_.pit1 = first pit of CoordCache;
1142                         //metrics_info_.pit2 = last pit of CoordCache;
1143                         //metrics_info_.singlepar = false;
1144                         //metrics_info_.y1 = 0;
1145                         //metrics_info_.y2 = height_;
1146                         //
1147                         updateMetrics(false);
1148                 }
1149
1150                 // This event (moving without mouse click) is not passed further.
1151                 // This should be changed if it is further utilized.
1152                 return need_redraw;
1153         }
1154
1155         // Build temporary cursor.
1156         Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1157
1158         // Put anchor at the same position.
1159         cur.resetAnchor();
1160
1161         // Try to dispatch to an non-editable inset near this position
1162         // via the temp cursor. If the inset wishes to change the real
1163         // cursor it has to do so explicitly by using
1164         //  cur.bv().cursor() = cur;  (or similar)
1165         if (inset) {
1166                 inset->dispatch(cur, cmd);
1167         }
1168
1169         // Now dispatch to the temporary cursor. If the real cursor should
1170         // be modified, the inset's dispatch has to do so explicitly.
1171         if (!cur.result().dispatched())
1172                 cur.dispatch(cmd);
1173
1174         //Do we have a selection?
1175         theSelection().haveSelection(cursor().selection());
1176
1177         // Redraw if requested and necessary.
1178         if (cur.result().dispatched() && cur.result().update())
1179                 return update(cur.result().update());
1180
1181         return false;
1182 }
1183
1184
1185 void BufferView::scroll(int y)
1186 {
1187         if (y > 0)
1188                 scrollDown(y);
1189         else if (y < 0)
1190                 scrollUp(-y);
1191 }
1192
1193
1194 void BufferView::scrollDown(int offset)
1195 {
1196         Text * text = &buffer_.text();
1197         TextMetrics & tm = text_metrics_[text];
1198         int ymax = height_ + offset;
1199         while (true) {
1200                 std::pair<pit_type, ParagraphMetrics> const & last = tm.last();
1201                 int bottom_pos = last.second.position() + last.second.descent();
1202                 if (last.first == text->paragraphs().size() - 1) {
1203                         if (bottom_pos <= height_)
1204                                 return;
1205                         offset = min(offset, bottom_pos - height_);
1206                         break;
1207                 }
1208                 if (bottom_pos > ymax)
1209                         break;
1210                 tm.newParMetricsDown();
1211         }
1212         offset_ref_ += offset;
1213         updateMetrics(false);
1214         buffer_.changed();
1215 }
1216
1217
1218 void BufferView::scrollUp(int offset)
1219 {
1220         Text * text = &buffer_.text();
1221         TextMetrics & tm = text_metrics_[text];
1222         int ymin = - offset;
1223         while (true) {
1224                 std::pair<pit_type, ParagraphMetrics> const & first = tm.first();
1225                 int top_pos = first.second.position() - first.second.ascent();
1226                 if (first.first == 0) {
1227                         if (top_pos >= 0)
1228                                 return;
1229                         offset = min(offset, - top_pos);
1230                         break;
1231                 }
1232                 if (top_pos < ymin)
1233                         break;
1234                 tm.newParMetricsUp();
1235         }
1236         offset_ref_ -= offset;
1237         updateMetrics(false);
1238         buffer_.changed();
1239 }
1240
1241
1242 void BufferView::setCursorFromRow(int row)
1243 {
1244         int tmpid = -1;
1245         int tmppos = -1;
1246
1247         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1248
1249         cursor_.reset(buffer_.inset());
1250         if (tmpid == -1)
1251                 buffer_.text().setCursor(cursor_, 0, 0);
1252         else
1253                 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1254 }
1255
1256
1257 void BufferView::gotoLabel(docstring const & label)
1258 {
1259         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1260                 vector<docstring> labels;
1261                 it->getLabelList(buffer_, labels);
1262                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1263                         setCursor(it);
1264                         update();
1265                         return;
1266                 }
1267         }
1268 }
1269
1270
1271 TextMetrics const & BufferView::textMetrics(Text const * t) const
1272 {
1273         return const_cast<BufferView *>(this)->textMetrics(t);
1274 }
1275
1276
1277 TextMetrics & BufferView::textMetrics(Text const * t)
1278 {
1279         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1280         if (tmc_it == text_metrics_.end()) {
1281                 tmc_it = text_metrics_.insert(
1282                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1283         }
1284         return tmc_it->second;
1285 }
1286
1287
1288 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1289                 pit_type pit) const
1290 {
1291         return textMetrics(t).parMetrics(pit);
1292 }
1293
1294
1295 int BufferView::workHeight() const
1296 {
1297         return height_;
1298 }
1299
1300
1301 void BufferView::setCursor(DocIterator const & dit)
1302 {
1303         size_t const n = dit.depth();
1304         for (size_t i = 0; i < n; ++i)
1305                 dit[i].inset().edit(cursor_, true);
1306
1307         cursor_.setCursor(dit);
1308         cursor_.selection() = false;
1309 }
1310
1311
1312 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1313 {
1314         // Would be wrong to delete anything if we have a selection.
1315         if (cur.selection())
1316                 return false;
1317
1318         bool need_anchor_change = false;
1319         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1320                 need_anchor_change);
1321
1322         if (need_anchor_change)
1323                 cur.resetAnchor();
1324
1325         if (!changed)
1326                 return false;
1327
1328         updateLabels(buffer_);
1329
1330         updateMetrics(false);
1331         buffer_.changed();
1332         return true;
1333 }
1334
1335
1336 bool BufferView::mouseSetCursor(Cursor & cur)
1337 {
1338         BOOST_ASSERT(&cur.bv() == this);
1339
1340         // this event will clear selection so we save selection for
1341         // persistent selection
1342         cap::saveSelection(cursor());
1343
1344         // Has the cursor just left the inset?
1345         bool badcursor = false;
1346         bool leftinset = (&cursor_.inset() != &cur.inset());
1347         if (leftinset)
1348                 badcursor = notifyCursorLeaves(cursor_, cur);
1349
1350         // do the dEPM magic if needed
1351         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1352         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1353         // the leftinset bool would not be necessary (badcursor instead).
1354         bool update = leftinset;
1355         if (!badcursor && cursor_.inTexted())
1356                 update |= checkDepm(cur, cursor_);
1357
1358         // if the cursor was in an empty script inset and the new
1359         // position is in the nucleus of the inset, notifyCursorLeaves
1360         // will kill the script inset itself. So we check all the
1361         // elements of the cursor to make sure that they are correct.
1362         // For an example, see bug 2933:
1363         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1364         // The code below could maybe be moved to a DocIterator method.
1365         //lyxerr << "cur before " << cur <<std::endl;
1366         DocIterator dit(cur.inset());
1367         dit.push_back(cur.bottom());
1368         size_t i = 1;
1369         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1370                 dit.push_back(cur[i]);
1371                 ++i;
1372         }
1373         //lyxerr << "5 cur after" << dit <<std::endl;
1374
1375         cursor_.setCursor(dit);
1376         cursor_.boundary(cur.boundary());
1377         cursor_.clearSelection();
1378         finishUndo();
1379         return update;
1380 }
1381
1382
1383 void BufferView::putSelectionAt(DocIterator const & cur,
1384                                 int length, bool backwards)
1385 {
1386         cursor_.clearSelection();
1387
1388         setCursor(cur);
1389
1390         if (length) {
1391                 if (backwards) {
1392                         cursor_.pos() += length;
1393                         cursor_.setSelection(cursor_, -length);
1394                 } else
1395                         cursor_.setSelection(cursor_, length);
1396         }
1397 }
1398
1399
1400 Cursor & BufferView::cursor()
1401 {
1402         return cursor_;
1403 }
1404
1405
1406 Cursor const & BufferView::cursor() const
1407 {
1408         return cursor_;
1409 }
1410
1411
1412 pit_type BufferView::anchor_ref() const
1413 {
1414         return anchor_ref_;
1415 }
1416
1417
1418 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1419 {
1420         return metrics_info_;
1421 }
1422
1423
1424 // FIXME: We should split-up updateMetrics() for the singlepar case.
1425 void BufferView::updateMetrics(bool singlepar)
1426 {
1427         Text & buftext = buffer_.text();
1428         pit_type const npit = int(buftext.paragraphs().size());
1429
1430         if (anchor_ref_ > int(npit - 1)) {
1431                 anchor_ref_ = int(npit - 1);
1432                 offset_ref_ = 0;
1433         }
1434
1435         if (!singlepar) {
1436                 // Clear out the position cache in case of full screen redraw,
1437                 coord_cache_.clear();
1438         
1439                 // Clear out paragraph metrics to avoid having invalid metrics
1440                 // in the cache from paragraphs not relayouted below
1441                 // The complete text metrics will be redone.
1442                 text_metrics_.clear();
1443         }
1444
1445         TextMetrics & tm = textMetrics(&buftext);
1446
1447         pit_type const bottom_pit = cursor_.bottom().pit();
1448         // If the paragraph metrics has changed, we can not
1449         // use the singlepar optimisation.
1450         if (singlepar
1451                 // In Single Paragraph mode, rebreak only
1452                 // the (main text, not inset!) paragraph containing the cursor.
1453                 // (if this paragraph contains insets etc., rebreaking will
1454                 // recursively descend)
1455                 && !tm.redoParagraph(bottom_pit)) {
1456
1457                 updateOffsetRef();
1458                 // collect cursor paragraph iter bounds
1459                 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1460                 int y1 = pm.position() - pm.ascent();
1461                 int y2 = pm.position() + pm.descent();
1462                 metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1463                         SingleParUpdate, npit);
1464                 LYXERR(Debug::PAINTING)
1465                         << BOOST_CURRENT_FUNCTION
1466                         << "\ny1: " << y1
1467                         << " y2: " << y2
1468                         << " pit: " << bottom_pit
1469                         << " singlepar: " << singlepar
1470                         << endl;
1471                 return;
1472         }
1473
1474         pit_type const pit = anchor_ref_;
1475         int pit1 = pit;
1476         int pit2 = pit;
1477
1478         // Rebreak anchor paragraph.
1479         tm.redoParagraph(pit);
1480
1481         updateOffsetRef();
1482
1483         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1484
1485         // Redo paragraphs above anchor if necessary.
1486         int y1 = y0;
1487         while (y1 > 0 && pit1 > 0) {
1488                 y1 -= tm.parMetrics(pit1).ascent();
1489                 --pit1;
1490                 tm.redoParagraph(pit1);
1491                 y1 -= tm.parMetrics(pit1).descent();
1492         }
1493
1494         // Take care of ascent of first line
1495         y1 -= tm.parMetrics(pit1).ascent();
1496
1497         // Normalize anchor for next time
1498         anchor_ref_ = pit1;
1499         offset_ref_ = -y1;
1500
1501         // Grey at the beginning is ugly
1502         if (pit1 == 0 && y1 > 0) {
1503                 y0 -= y1;
1504                 y1 = 0;
1505                 anchor_ref_ = 0;
1506         }
1507
1508         // Redo paragraphs below the anchor if necessary.
1509         int y2 = y0;
1510         while (y2 < height_ && pit2 < int(npit) - 1) {
1511                 y2 += tm.parMetrics(pit2).descent();
1512                 ++pit2;
1513                 tm.redoParagraph(pit2);
1514                 y2 += tm.parMetrics(pit2).ascent();
1515         }
1516
1517         // Take care of descent of last line
1518         y2 += tm.parMetrics(pit2).descent();
1519
1520         LYXERR(Debug::PAINTING)
1521                 << BOOST_CURRENT_FUNCTION
1522                 << "\n y1: " << y1
1523                 << " y2: " << y2
1524                 << " pit1: " << pit1
1525                 << " pit2: " << pit2
1526                 << " npit: " << npit
1527                 << " singlepar: " << singlepar
1528                 << endl;
1529
1530         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1531                 FullScreenUpdate, npit);
1532
1533         if (lyxerr.debugging(Debug::WORKAREA)) {
1534                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1535                 coord_cache_.dump();
1536         }
1537 }
1538
1539
1540 void BufferView::menuInsertLyXFile(string const & filenm)
1541 {
1542         BOOST_ASSERT(cursor_.inTexted());
1543         string filename = filenm;
1544
1545         if (filename.empty()) {
1546                 // Launch a file browser
1547                 // FIXME UNICODE
1548                 string initpath = lyxrc.document_path;
1549                 string const trypath = buffer_.filePath();
1550                 // If directory is writeable, use this as default.
1551                 if (isDirWriteable(FileName(trypath)))
1552                         initpath = trypath;
1553
1554                 // FIXME UNICODE
1555                 FileDialog fileDlg(_("Select LyX document to insert"),
1556                         LFUN_FILE_INSERT,
1557                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1558                         make_pair(_("Examples|#E#e"),
1559                                     from_utf8(addPath(package().system_support().absFilename(),
1560                                     "examples"))));
1561
1562                 FileDialog::Result result =
1563                         fileDlg.open(from_utf8(initpath),
1564                                      FileFilterList(_("LyX Documents (*.lyx)")),
1565                                      docstring());
1566
1567                 if (result.first == FileDialog::Later)
1568                         return;
1569
1570                 // FIXME UNICODE
1571                 filename = to_utf8(result.second);
1572
1573                 // check selected filename
1574                 if (filename.empty()) {
1575                         // emit message signal.
1576                         message(_("Canceled."));
1577                         return;
1578                 }
1579         }
1580
1581         // Get absolute path of file and add ".lyx"
1582         // to the filename if necessary
1583         filename = fileSearch(string(), filename, "lyx").absFilename();
1584
1585         docstring const disp_fn = makeDisplayPath(filename);
1586         // emit message signal.
1587         message(bformat(_("Inserting document %1$s..."), disp_fn));
1588
1589         docstring res;
1590         Buffer buf("", false);
1591         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1592                 ErrorList & el = buffer_.errorList("Parse");
1593                 // Copy the inserted document error list into the current buffer one.
1594                 el = buf.errorList("Parse");
1595                 recordUndo(cursor_);
1596                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1597                                              buf.params().getTextClass_ptr(), el);
1598                 res = _("Document %1$s inserted.");
1599         } else
1600                 res = _("Could not insert document %1$s");
1601
1602         // emit message signal.
1603         message(bformat(res, disp_fn));
1604         buffer_.errors("Parse");
1605         updateMetrics(false);
1606 }
1607
1608
1609 void BufferView::draw(frontend::Painter & pain)
1610 {
1611         PainterInfo pi(this, pain);
1612         // Should the whole screen, including insets, be refreshed?
1613         // FIXME: We should also distinguish DecorationUpdate to avoid text
1614         // drawing if possible. This is not possible to do easily right now
1615         // because of the single backing pixmap.
1616         pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1617
1618         if (pi.full_repaint)
1619                 // Clear background (if not delegated to rows)
1620                 pain.fillRectangle(0, metrics_info_.y1, width_,
1621                         metrics_info_.y2 - metrics_info_.y1,
1622                         buffer_.inset().backgroundColor());
1623
1624         LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1625         Text & text = buffer_.text();
1626         TextMetrics const & tm = text_metrics_[&text];
1627         int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1628         if (!pi.full_repaint)
1629                 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1630         else
1631                 tm.draw(pi, 0, y);
1632         LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING  ***" << endl;
1633
1634         // and grey out above (should not happen later)
1635 //      lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1636         if (metrics_info_.y1 > 0 
1637                 && metrics_info_.update_strategy == FullScreenUpdate)
1638                 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1639
1640         // and possibly grey out below
1641 //      lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1642         if (metrics_info_.y2 < height_ 
1643                 && metrics_info_.update_strategy == FullScreenUpdate)
1644                 pain.fillRectangle(0, metrics_info_.y2, width_,
1645                         height_ - metrics_info_.y2, Color::bottomarea);
1646 }
1647
1648 } // namespace lyx