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