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