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