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