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