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