3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "bufferview_funcs.h"
24 #include "coordcache.h"
25 #include "CutAndPaste.h"
27 #include "dispatchresult.h"
28 #include "errorlist.h"
30 #include "FloatList.h"
31 #include "funcrequest.h"
32 #include "FuncStatus.h"
35 #include "insetiterator.h"
37 #include "LaTeXFeatures.h"
38 #include "lyx_cb.h" // added for Dispatch functions
42 #include "lyxlayout.h"
44 #include "lyxtextclass.h"
47 #include "paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "pariterator.h"
55 #include "WordLangTuple.h"
56 #include "metricsinfo.h"
58 #include "insets/insetbibtex.h"
59 #include "insets/insetcommand.h" // ChangeRefs
60 #include "insets/insetref.h"
61 #include "insets/insettext.h"
63 #include "frontends/Alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Selection.h"
68 #include "graphics/Previews.h"
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"
76 #include <boost/bind.hpp>
77 #include <boost/current_function.hpp>
85 using support::addPath;
86 using support::bformat;
87 using support::FileFilterList;
88 using support::FileName;
89 using support::fileSearch;
90 using support::isDirWriteable;
91 using support::isFileReadable;
92 using support::makeDisplayPath;
93 using support::package;
97 using std::istringstream;
101 using std::mem_fun_ref;
105 namespace Alert = frontend::Alert;
109 /// Return an inset of this class if it exists at the current cursor position
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
114 DocIterator it = cur;
115 if (it.nextInset() &&
116 it.nextInset()->lyxCode() == code) {
117 inset = static_cast<T*>(it.nextInset());
125 BufferView::BufferView()
126 : width_(0), height_(0), buffer_(0), wh_(0),
128 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129 intl_(new Intl), last_inset_(0)
131 xsel_cache_.set = false;
132 intl_->initKeyMapper(lyxrc.use_kbmap);
136 BufferView::~BufferView()
141 Buffer * BufferView::buffer() const
147 void BufferView::setBuffer(Buffer * b)
149 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
150 << "[ b = " << b << "]" << endl;
153 // Save the actual cursor position and anchor inside the
154 // buffer so that it can be restored in case we rechange
155 // to this buffer later on.
156 buffer_->saveCursor(cursor_.selectionBegin(),
157 cursor_.selectionEnd());
158 // current buffer is going to be switched-off, save cursor pos
159 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
160 boost::tie(cursor_.pit(), cursor_.pos()) );
163 // If we're quitting lyx, don't bother updating stuff
169 // If we are closing current buffer, switch to the first in
172 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
173 << " No Buffer!" << endl;
174 // We are closing the buffer, use the first buffer as current
175 buffer_ = theBufferList().first();
177 // Set current buffer
182 cursor_ = LCursor(*this);
187 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
188 << "Buffer addr: " << buffer_ << endl;
189 cursor_.push(buffer_->inset());
190 cursor_.resetAnchor();
191 buffer_->text().setCurrentFont(cursor_);
192 if (buffer_->getCursor().size() > 0 &&
193 buffer_->getAnchor().size() > 0)
195 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
196 cursor_.resetAnchor();
197 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
198 cursor_.setSelection();
199 theSelection().haveSelection(cursor_.selection());
204 updateMetrics(false);
206 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
207 graphics::Previews::get().generateBufferPreviews(*buffer_);
211 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
213 // File already open?
214 if (theBufferList().exists(filename.absFilename())) {
215 docstring const file = makeDisplayPath(filename.absFilename(), 20);
216 docstring text = bformat(_("The document %1$s is already "
217 "loaded.\n\nDo you want to revert "
218 "to the saved version?"), file);
219 int const ret = Alert::prompt(_("Revert to saved document?"),
220 text, 0, 1, _("&Revert"), _("&Switch to document"));
223 setBuffer(theBufferList().getBuffer(filename.absFilename()));
226 // FIXME: should be LFUN_REVERT
227 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
229 // Fall through to new load. (Asger)
235 if (isFileReadable(filename)) {
236 b = theBufferList().newBuffer(filename.absFilename());
237 if (!lyx::loadLyXFile(b, filename)) {
238 theBufferList().release(b);
242 docstring text = bformat(_("The document %1$s does not yet "
243 "exist.\n\nDo you want to create "
244 "a new document?"), from_utf8(filename.absFilename()));
245 int const ret = Alert::prompt(_("Create new document?"),
246 text, 0, 1, _("&Create"), _("Cancel"));
249 b = newFile(filename.absFilename(), string(), true);
257 // Send the "errors" signal in case of parsing errors
260 // Update the labels and section numbering.
261 updateLabels(*buffer_);
262 // scroll to the position when the file was last closed
263 if (lyxrc.use_lastfilepos) {
266 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
267 // if successfully move to pit (returned par_id is not zero), update metrics
268 if (moveToPosition(pit, 0, pos).get<1>()) {
270 updateMetrics(false);
275 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
281 void BufferView::reload()
283 if (theBufferList().close(buffer_, false))
284 loadLyXFile(FileName(buffer_->fileName()));
288 void BufferView::resize()
293 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
295 updateMetrics(false);
300 bool BufferView::fitCursor()
302 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
303 frontend::FontMetrics const & fm =
304 theFontMetrics(cursor_.getFont());
305 int const asc = fm.maxAscent();
306 int const des = fm.maxDescent();
307 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
308 if (p.y_ - asc >= 0 && p.y_ + des < height_)
316 bool BufferView::multiParSel()
318 if (!cursor_.selection())
320 bool ret = multiparsel_cache_;
321 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
322 // Either this, or previous selection spans paragraphs
323 return ret || multiparsel_cache_;
327 bool BufferView::update(Update::flags flags)
329 // last_inset_ points to the last visited inset. This pointer may become
330 // invalid because of keyboard editing. Since all such operations
331 // causes screen update(), I reset last_inset_ to avoid such a problem.
333 // This is close to a hot-path.
334 if (lyxerr.debugging(Debug::DEBUG)) {
336 << BOOST_CURRENT_FUNCTION
337 << "[fitcursor = " << (flags & Update::FitCursor)
338 << ", forceupdate = " << (flags & Update::Force)
339 << ", singlepar = " << (flags & Update::SinglePar)
340 << "] buffer: " << buffer_ << endl;
343 // Check needed to survive LyX startup
347 if (lyxerr.debugging(Debug::WORKAREA)) {
348 lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
351 // Update macro store
352 buffer_->buildMacros();
354 // Now do the first drawing step if needed. This consists on updating
355 // the CoordCache in updateMetrics().
356 // The second drawing step is done in WorkArea::redraw() if needed.
358 // Case when no explicit update is requested.
360 // no need to redraw anything.
364 if (flags == Update::FitCursor) {
365 bool const fit_cursor = fitCursor();
367 updateMetrics(false);
368 // tell the frontend to update the screen if needed.
372 bool full_metrics = flags & Update::Force;
373 if (flags & Update::MultiParSel)
374 full_metrics |= multiParSel();
376 bool const single_par = !full_metrics;
377 updateMetrics(single_par);
379 if (flags & Update::FitCursor && fitCursor())
380 updateMetrics(false);
382 // tell the frontend to update the screen.
387 void BufferView::updateScrollbar()
390 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
391 << " no text in updateScrollbar" << endl;
392 scrollbarParameters_.reset();
396 LyXText & t = buffer_->text();
397 TextMetrics & tm = text_metrics_[&t];
399 int const parsize = int(t.paragraphs().size() - 1);
400 if (anchor_ref_ > parsize) {
401 anchor_ref_ = parsize;
405 if (lyxerr.debugging(Debug::GUI)) {
407 << BOOST_CURRENT_FUNCTION
408 << " Updating scrollbar: height: " << t.paragraphs().size()
409 << " curr par: " << cursor_.bottom().pit()
410 << " default height " << defaultRowHeight() << endl;
413 // It would be better to fix the scrollbar to understand
414 // values in [0..1] and divide everything by wh
416 // estimated average paragraph height:
420 int h = tm.parMetrics(anchor_ref_).height();
422 // Normalize anchor/offset (MV):
423 while (offset_ref_ > h && anchor_ref_ < parsize) {
426 h = tm.parMetrics(anchor_ref_).height();
428 // Look at paragraph heights on-screen
431 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
434 int const h2 = tm.parMetrics(pit).height();
440 int const hav = sumh / nh;
441 // More realistic average paragraph height
446 scrollbarParameters_.height = (parsize + 1) * wh_;
447 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
448 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
452 ScrollbarParameters const & BufferView::scrollbarParameters() const
454 return scrollbarParameters_;
458 void BufferView::scrollDocView(int value)
460 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
461 << "[ value = " << value << "]" << endl;
466 LyXText & t = buffer_->text();
467 TextMetrics & tm = text_metrics_[&t];
469 float const bar = value / float(wh_ * t.paragraphs().size());
471 anchor_ref_ = int(bar * t.paragraphs().size());
472 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
473 anchor_ref_ = int(t.paragraphs().size()) - 1;
475 tm.redoParagraph(anchor_ref_);
476 int const h = tm.parMetrics(anchor_ref_).height();
477 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
478 updateMetrics(false);
482 void BufferView::setCursorFromScrollbar()
484 LyXText & t = buffer_->text();
486 int const height = 2 * defaultRowHeight();
487 int const first = height;
488 int const last = height_ - height;
489 LCursor & cur = cursor_;
491 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
494 case bv_funcs::CUR_ABOVE:
495 t.setCursorFromCoordinates(cur, 0, first);
496 cur.clearSelection();
498 case bv_funcs::CUR_BELOW:
499 t.setCursorFromCoordinates(cur, 0, last);
500 cur.clearSelection();
502 case bv_funcs::CUR_INSIDE:
503 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
504 int const newy = min(last, max(y, first));
506 cur.reset(buffer_->inset());
507 t.setCursorFromCoordinates(cur, 0, newy);
513 Change const BufferView::getCurrentChange() const
515 if (!cursor_.selection())
516 return Change(Change::UNCHANGED);
518 DocIterator dit = cursor_.selectionBegin();
519 return dit.paragraph().lookupChange(dit.pos());
523 void BufferView::saveBookmark(bool persistent)
525 LyX::ref().session().bookmarks().save(
526 FileName(buffer_->fileName()),
528 cursor_.paragraph().id(),
533 // emit message signal.
534 message(_("Save bookmark"));
538 boost::tuple<pit_type, int> BufferView::moveToPosition(pit_type par_pit, int par_id, pos_type par_pos)
540 cursor_.clearSelection();
542 // if a valid par_id is given, try it first
544 ParIterator par = buffer_->getParFromID(par_id);
545 if (par != buffer_->par_iterator_end()) {
546 setCursor(makeDocIterator(par, min(par->size(), par_pos)));
547 return boost::make_tuple(cursor_.pit(), par_id);
550 // if par_id == 0, or searching through par_id failed
551 if (static_cast<size_t>(par_pit) < buffer_->paragraphs().size()) {
552 ParIterator it = buffer_->par_iterator_begin();
553 ParIterator const end = buffer_->par_iterator_end();
554 for (; it != end; ++it)
555 if (it.pit() == par_pit) {
556 // restored pos may be bigger than it->size
557 setCursor(makeDocIterator(it, min(par_pos, it->size())));
558 return boost::make_tuple(par_pit, it->id());
562 return boost::make_tuple(pit_type(0), 0);
566 void BufferView::switchKeyMap()
568 if (!lyxrc.rtl_support)
571 if (getLyXText()->real_current_font.isRightToLeft()) {
572 if (intl_->keymap == Intl::PRIMARY)
575 if (intl_->keymap == Intl::SECONDARY)
581 int BufferView::workWidth() const
587 void BufferView::center()
589 CursorSlice & bot = cursor_.bottom();
590 TextMetrics & tm = text_metrics_[bot.text()];
591 pit_type const pit = bot.pit();
592 tm.redoParagraph(pit);
593 ParagraphMetrics const & pm = tm.parMetrics(pit);
595 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
596 + pm.ascent() - height_ / 2;
600 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
604 switch (cmd.action) {
607 flag.enabled(!buffer_->undostack().empty());
610 flag.enabled(!buffer_->redostack().empty());
612 case LFUN_FILE_INSERT:
613 case LFUN_FILE_INSERT_ASCII_PARA:
614 case LFUN_FILE_INSERT_ASCII:
615 case LFUN_BOOKMARK_SAVE:
616 // FIXME: Actually, these LFUNS should be moved to LyXText
617 flag.enabled(cursor_.inTexted());
619 case LFUN_FONT_STATE:
620 case LFUN_LABEL_INSERT:
621 case LFUN_PARAGRAPH_GOTO:
622 // FIXME handle non-trivially
623 case LFUN_OUTLINE_UP:
624 case LFUN_OUTLINE_DOWN:
625 case LFUN_OUTLINE_IN:
626 case LFUN_OUTLINE_OUT:
628 case LFUN_REFERENCE_NEXT:
630 case LFUN_WORD_REPLACE:
633 case LFUN_MARK_TOGGLE:
634 case LFUN_SCREEN_RECENTER:
635 case LFUN_BIBTEX_DATABASE_ADD:
636 case LFUN_BIBTEX_DATABASE_DEL:
637 case LFUN_WORDS_COUNT:
638 case LFUN_NEXT_INSET_TOGGLE:
642 case LFUN_LABEL_GOTO: {
643 flag.enabled(!cmd.argument().empty()
644 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
648 case LFUN_CHANGES_TRACK:
650 flag.setOnOff(buffer_->params().trackChanges);
653 case LFUN_CHANGES_OUTPUT: {
654 OutputParams runparams;
655 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
656 flag.enabled(buffer_ && features.isAvailable("dvipost"));
657 flag.setOnOff(buffer_->params().outputChanges);
661 case LFUN_CHANGES_MERGE:
662 case LFUN_CHANGE_NEXT:
663 case LFUN_ALL_CHANGES_ACCEPT:
664 case LFUN_ALL_CHANGES_REJECT:
665 // TODO: context-sensitive enabling of LFUNs
666 // In principle, these command should only be enabled if there
667 // is a change in the document. However, without proper
668 // optimizations, this will inevitably result in poor performance.
669 flag.enabled(buffer_);
672 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
673 flag.setOnOff(buffer_->params().compressed);
685 bool BufferView::dispatch(FuncRequest const & cmd)
687 //lyxerr << BOOST_CURRENT_FUNCTION
688 // << [ cmd = " << cmd << "]" << endl;
690 // Make sure that the cached BufferView is correct.
691 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
692 << " action[" << cmd.action << ']'
693 << " arg[" << to_utf8(cmd.argument()) << ']'
694 << " x[" << cmd.x << ']'
695 << " y[" << cmd.y << ']'
696 << " button[" << cmd.button() << ']'
699 LCursor & cur = cursor_;
701 switch (cmd.action) {
705 cur.message(_("Undo"));
706 cur.clearSelection();
707 if (!textUndo(*this))
708 cur.message(_("No further undo information"));
716 cur.message(_("Redo"));
717 cur.clearSelection();
718 if (!textRedo(*this))
719 cur.message(_("No further redo information"));
725 case LFUN_FILE_INSERT:
727 menuInsertLyXFile(to_utf8(cmd.argument()));
730 case LFUN_FILE_INSERT_ASCII_PARA:
732 insertAsciiFile(this, to_utf8(cmd.argument()), true);
735 case LFUN_FILE_INSERT_ASCII:
737 insertAsciiFile(this, to_utf8(cmd.argument()), false);
740 case LFUN_FONT_STATE:
741 cur.message(cur.currentState());
744 case LFUN_BOOKMARK_SAVE:
745 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
748 case LFUN_LABEL_GOTO: {
749 docstring label = cmd.argument();
752 getInsetByCode<InsetRef>(cursor_,
753 InsetBase::REF_CODE);
755 label = inset->getParam("reference");
756 // persistent=false: use temp_bookmark
766 case LFUN_PARAGRAPH_GOTO: {
767 int const id = convert<int>(to_utf8(cmd.argument()));
769 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
770 ParIterator par = b->getParFromID(id);
771 if (par == b->par_iterator_end()) {
773 << "No matching paragraph found! ["
774 << id << "]." << endl;
777 << "Paragraph " << par->id()
778 << " found in buffer `"
779 << b->fileName() << "'." << endl;
783 setCursor(makeDocIterator(par, 0));
787 // Switch to other buffer view and resend cmd
788 theLyXFunc().dispatch(FuncRequest(
789 LFUN_BUFFER_SWITCH, b->fileName()));
790 theLyXFunc().dispatch(cmd);
799 case LFUN_OUTLINE_UP:
800 toc::outline(toc::Up, cursor_);
801 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
802 updateLabels(*buffer_);
804 case LFUN_OUTLINE_DOWN:
805 toc::outline(toc::Down, cursor_);
806 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
807 updateLabels(*buffer_);
809 case LFUN_OUTLINE_IN:
810 toc::outline(toc::In, cursor_);
811 updateLabels(*buffer_);
813 case LFUN_OUTLINE_OUT:
814 toc::outline(toc::Out, cursor_);
815 updateLabels(*buffer_);
819 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
822 case LFUN_REFERENCE_NEXT: {
823 vector<InsetBase_code> tmp;
824 tmp.push_back(InsetBase::LABEL_CODE);
825 tmp.push_back(InsetBase::REF_CODE);
826 bv_funcs::gotoInset(this, tmp, true);
830 case LFUN_CHANGES_TRACK:
831 buffer_->params().trackChanges = !buffer_->params().trackChanges;
834 case LFUN_CHANGES_OUTPUT: {
835 buffer_->params().outputChanges = !buffer_->params().outputChanges;
839 case LFUN_CHANGE_NEXT:
840 findNextChange(this);
843 case LFUN_CHANGES_MERGE:
844 if (findNextChange(this))
845 showDialog("changes");
848 case LFUN_ALL_CHANGES_ACCEPT: {
849 cursor_.reset(buffer_->inset());
851 #warning FIXME changes
853 while (findNextChange(this))
854 getLyXText()->acceptChange(cursor_);
859 case LFUN_ALL_CHANGES_REJECT: {
860 cursor_.reset(buffer_->inset());
862 #warning FIXME changes
864 while (findNextChange(this))
865 getLyXText()->rejectChange(cursor_);
873 case LFUN_WORD_REPLACE:
878 cur.clearSelection();
880 cur.message(from_utf8(N_("Mark off")));
884 cur.clearSelection();
887 cur.message(from_utf8(N_("Mark on")));
890 case LFUN_MARK_TOGGLE:
891 cur.clearSelection();
894 cur.message(from_utf8(N_("Mark removed")));
897 cur.message(from_utf8(N_("Mark set")));
902 case LFUN_SCREEN_RECENTER:
906 case LFUN_BIBTEX_DATABASE_ADD: {
907 LCursor tmpcur = cursor_;
908 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
909 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
910 InsetBase::BIBTEX_CODE);
912 if (inset->addDatabase(to_utf8(cmd.argument())))
913 buffer_->updateBibfilesCache();
918 case LFUN_BIBTEX_DATABASE_DEL: {
919 LCursor tmpcur = cursor_;
920 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
921 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
922 InsetBase::BIBTEX_CODE);
924 if (inset->delDatabase(to_utf8(cmd.argument())))
925 buffer_->updateBibfilesCache();
930 case LFUN_WORDS_COUNT: {
931 DocIterator from, to;
932 if (cur.selection()) {
933 from = cur.selectionBegin();
934 to = cur.selectionEnd();
936 from = doc_iterator_begin(buffer_->inset());
937 to = doc_iterator_end(buffer_->inset());
939 int const count = countWords(from, to);
943 message = bformat(_("%1$d words in selection."),
946 message = bformat(_("%1$d words in document."),
951 message = _("One word in selection.");
953 message = _("One word in document.");
956 Alert::information(_("Count words"), message);
960 case LFUN_BUFFER_TOGGLE_COMPRESSION:
961 // turn compression on/off
962 buffer_->params().compressed = !buffer_->params().compressed;
965 case LFUN_NEXT_INSET_TOGGLE: {
966 // this is the real function we want to invoke
967 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
968 // if there is an inset at cursor, see whether it
970 InsetBase * inset = cur.nextInset();
971 if (inset && inset->isActive()) {
972 LCursor tmpcur = cur;
973 tmpcur.pushLeft(*inset);
974 inset->dispatch(tmpcur, tmpcmd);
975 if (tmpcur.result().dispatched()) {
979 // if it did not work, try the underlying inset.
980 if (!cur.result().dispatched())
981 cur.dispatch(tmpcmd);
983 if (cur.result().dispatched())
984 cur.clearSelection();
997 docstring const BufferView::requestSelection()
1002 LCursor & cur = cursor_;
1004 if (!cur.selection()) {
1005 xsel_cache_.set = false;
1009 if (!xsel_cache_.set ||
1010 cur.top() != xsel_cache_.cursor ||
1011 cur.anchor_.top() != xsel_cache_.anchor)
1013 xsel_cache_.cursor = cur.top();
1014 xsel_cache_.anchor = cur.anchor_.top();
1015 xsel_cache_.set = cur.selection();
1016 return cur.selectionAsString(false);
1022 void BufferView::clearSelection()
1025 cursor_.clearSelection();
1026 xsel_cache_.set = false;
1027 // The buffer did not really change, but this causes the
1028 // redraw we need because we cleared the selection above.
1034 void BufferView::workAreaResize(int width, int height)
1036 // Update from work area
1040 // The complete text metrics will be redone.
1041 text_metrics_.clear();
1048 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1050 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1052 // This is only called for mouse related events including
1053 // LFUN_FILE_OPEN generated by drag-and-drop.
1054 FuncRequest cmd = cmd0;
1056 // E.g. Qt mouse press when no buffer
1061 cur.push(buffer_->inset());
1062 cur.selection() = cursor_.selection();
1064 // Either the inset under the cursor or the
1065 // surrounding LyXText will handle this event.
1067 // Build temporary cursor.
1068 cmd.y = min(max(cmd.y, -1), height_);
1069 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1071 //lyxerr << BOOST_CURRENT_FUNCTION
1072 // << " * hit inset at tip: " << inset << endl;
1073 //lyxerr << BOOST_CURRENT_FUNCTION
1074 // << " * created temp cursor:" << cur << endl;
1076 // NOTE: editXY returns the top level inset of nested insets. If you happen
1077 // to move from a text (inset=0) to a text inside an inset (e.g. an opened
1078 // footnote inset, again inset=0), that inset will not be redrawn.
1079 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1080 bool need_redraw = false;
1082 if (inset != last_inset_) {
1084 need_redraw |= last_inset_->setMouseHover(false);
1086 need_redraw |= inset->setMouseHover(true);
1087 last_inset_ = inset;
1090 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1091 // not expose the button for redraw. We adjust here the metrics dimension
1092 // to enable a full redraw.
1093 // FIXME: It is possible to redraw only the area around the button!
1094 if (need_redraw && metrics_info_.singlepar) {
1095 // FIXME: It should be possible to redraw only the area around
1096 // the button by doing this:
1098 //metrics_info_.singlepar = false;
1099 //metrics_info_.y1 = ymin of button;
1100 //metrics_info_.y2 = ymax of button;
1102 // Unfortunately, rowpainter.C:paintText() does not distinguish
1103 // between background updates and text updates. So we use the hammer
1104 // solution for now. We could also avoid the updateMetrics() below
1105 // by using the first and last pit of the CoordCache. Have a look
1106 // at LyXText::getPitNearY() to see what I mean.
1108 //metrics_info_.pit1 = first pit of CoordCache;
1109 //metrics_info_.pit2 = last pit of CoordCache;
1110 //metrics_info_.singlepar = false;
1111 //metrics_info_.y1 = 0;
1112 //metrics_info_.y2 = height_;
1114 updateMetrics(false);
1117 // This event (moving without mouse click) is not passed further.
1118 // This should be changed if it is further utilized.
1122 // Put anchor at the same position.
1125 // Try to dispatch to an non-editable inset near this position
1126 // via the temp cursor. If the inset wishes to change the real
1127 // cursor it has to do so explicitly by using
1128 // cur.bv().cursor() = cur; (or similar)
1130 inset->dispatch(cur, cmd);
1133 // Now dispatch to the temporary cursor. If the real cursor should
1134 // be modified, the inset's dispatch has to do so explicitly.
1135 if (!cur.result().dispatched())
1138 // Redraw if requested and necessary.
1139 if (cur.result().dispatched() && cur.result().update())
1140 return update(cur.result().update());
1146 void BufferView::scroll(int /*lines*/)
1151 // LyXText const * t = &buffer_->text();
1152 // int const line_height = defaultRowHeight();
1154 // // The new absolute coordinate
1155 // int new_top_y = top_y() + lines * line_height;
1157 // // Restrict to a valid value
1158 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1159 // new_top_y = std::max(0, new_top_y);
1161 // scrollDocView(new_top_y);
1166 void BufferView::setCursorFromRow(int row)
1171 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1174 buffer_->text().setCursor(cursor_, 0, 0);
1176 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1180 void BufferView::gotoLabel(docstring const & label)
1182 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1183 vector<docstring> labels;
1184 it->getLabelList(*buffer_, labels);
1185 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1194 LyXText * BufferView::getLyXText()
1196 LyXText * text = cursor_.innerText();
1202 LyXText const * BufferView::getLyXText() const
1204 LyXText const * text = cursor_.innerText();
1210 TextMetrics const & BufferView::textMetrics(LyXText const * t) const
1212 return const_cast<BufferView *>(this)->textMetrics(t);
1216 TextMetrics & BufferView::textMetrics(LyXText const * t)
1218 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1219 if (tmc_it == text_metrics_.end()) {
1220 tmc_it = text_metrics_.insert(
1221 make_pair(t, TextMetrics(this, const_cast<LyXText *>(t)))).first;
1223 return tmc_it->second;
1227 ParagraphMetrics const & BufferView::parMetrics(LyXText const * t,
1230 return textMetrics(t).parMetrics(pit);
1234 int BufferView::workHeight() const
1240 void BufferView::setCursor(DocIterator const & dit)
1242 size_t const n = dit.depth();
1243 for (size_t i = 0; i < n; ++i)
1244 dit[i].inset().edit(cursor_, true);
1246 cursor_.setCursor(dit);
1247 // remember new position.
1248 cursor_.setTargetX();
1249 cursor_.selection() = false;
1253 bool BufferView::checkDepm(LCursor & cur, LCursor & old)
1255 // Would be wrong to delete anything if we have a selection.
1256 if (cur.selection())
1259 bool need_anchor_change = false;
1260 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1261 need_anchor_change);
1263 if (need_anchor_change)
1269 updateMetrics(false);
1275 bool BufferView::mouseSetCursor(LCursor & cur)
1277 BOOST_ASSERT(&cur.bv() == this);
1279 // Has the cursor just left the inset?
1280 bool badcursor = false;
1281 if (&cursor_.inset() != &cur.inset())
1282 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1284 // do the dEPM magic if needed
1285 // FIXME: move this to InsetText::notifyCursorLeaves?
1286 bool update = false;
1287 if (!badcursor && cursor_.inTexted())
1288 checkDepm(cur, cursor_);
1291 cursor_.clearSelection();
1292 // remember new position.
1293 cursor_.setTargetX();
1299 void BufferView::putSelectionAt(DocIterator const & cur,
1300 int length, bool backwards)
1302 cursor_.clearSelection();
1308 cursor_.pos() += length;
1309 cursor_.setSelection(cursor_, -length);
1311 cursor_.setSelection(cursor_, length);
1312 theSelection().haveSelection(cursor_.selection());
1317 LCursor & BufferView::cursor()
1323 LCursor const & BufferView::cursor() const
1329 pit_type BufferView::anchor_ref() const
1335 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1337 return metrics_info_;
1341 // FIXME: We should split-up updateMetrics() for the singlepar case.
1342 void BufferView::updateMetrics(bool singlepar)
1344 LyXText & buftext = buffer_->text();
1345 TextMetrics & tm = textMetrics(&buftext);
1346 pit_type size = int(buftext.paragraphs().size());
1348 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1349 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1353 // If the paragraph metrics has changed, we can not
1354 // use the singlepar optimisation.
1356 // In Single Paragraph mode, rebreak only
1357 // the (main text, not inset!) paragraph containing the cursor.
1358 // (if this paragraph contains insets etc., rebreaking will
1359 // recursively descend)
1360 && tm.redoParagraph(cursor_.bottom().pit()))
1363 pit_type const pit = anchor_ref_;
1366 size_t const npit = buftext.paragraphs().size();
1368 // Rebreak anchor paragraph.
1370 tm.redoParagraph(pit);
1372 // Clear out the position cache in case of full screen redraw.
1374 coord_cache_.clear();
1376 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1378 // Redo paragraphs above anchor if necessary.
1380 while (y1 > 0 && pit1 > 0) {
1381 y1 -= tm.parMetrics(pit1).ascent();
1384 tm.redoParagraph(pit1);
1385 y1 -= tm.parMetrics(pit1).descent();
1389 // Take care of ascent of first line
1390 y1 -= tm.parMetrics(pit1).ascent();
1392 // Normalize anchor for next time
1396 // Grey at the beginning is ugly
1397 if (pit1 == 0 && y1 > 0) {
1403 // Redo paragraphs below the anchor if necessary.
1405 while (y2 < height_ && pit2 < int(npit) - 1) {
1406 y2 += tm.parMetrics(pit2).descent();
1409 tm.redoParagraph(pit2);
1410 y2 += tm.parMetrics(pit2).ascent();
1413 // Take care of descent of last line
1414 y2 += tm.parMetrics(pit2).descent();
1416 // The coordinates of all these paragraphs are correct, cache them
1418 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1419 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1420 ParagraphMetrics const & pm = tm.parMetrics(pit);
1422 parPos[pit] = Point(0, y);
1423 if (singlepar && pit == cursor_.bottom().pit()) {
1424 // In Single Paragraph mode, collect here the
1425 // y1 and y2 of the (one) paragraph the cursor is in
1426 y1 = y - pm.ascent();
1427 y2 = y + pm.descent();
1433 // collect cursor paragraph iter bounds
1434 pit1 = cursor_.bottom().pit();
1435 pit2 = cursor_.bottom().pit();
1438 lyxerr[Debug::DEBUG]
1439 << BOOST_CURRENT_FUNCTION
1442 << " pit1: " << pit1
1443 << " pit2: " << pit2
1444 << " npit: " << npit
1445 << " singlepar: " << singlepar
1449 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1451 if (lyxerr.debugging(Debug::WORKAREA)) {
1452 lyxerr[Debug::WORKAREA] << "BufferView::updateMetrics" << endl;
1453 coord_cache_.dump();
1458 void BufferView::menuInsertLyXFile(string const & filenm)
1460 BOOST_ASSERT(cursor_.inTexted());
1461 string filename = filenm;
1463 if (filename.empty()) {
1464 // Launch a file browser
1466 string initpath = lyxrc.document_path;
1469 string const trypath = buffer_->filePath();
1470 // If directory is writeable, use this as default.
1471 if (isDirWriteable(FileName(trypath)))
1476 FileDialog fileDlg(_("Select LyX document to insert"),
1478 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1479 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1481 FileDialog::Result result =
1482 fileDlg.open(from_utf8(initpath),
1483 FileFilterList(_("LyX Documents (*.lyx)")),
1486 if (result.first == FileDialog::Later)
1490 filename = to_utf8(result.second);
1492 // check selected filename
1493 if (filename.empty()) {
1494 // emit message signal.
1495 message(_("Canceled."));
1500 // Get absolute path of file and add ".lyx"
1501 // to the filename if necessary
1502 filename = fileSearch(string(), filename, "lyx").absFilename();
1504 docstring const disp_fn = makeDisplayPath(filename);
1505 // emit message signal.
1506 message(bformat(_("Inserting document %1$s..."), disp_fn));
1509 Buffer buf("", false);
1510 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1511 ErrorList & el = buffer_->errorList("Parse");
1512 // Copy the inserted document error list into the current buffer one.
1513 el = buf.errorList("Parse");
1514 recordUndo(cursor_);
1515 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1516 buf.params().textclass, el);
1517 res = _("Document %1$s inserted.");
1519 res = _("Could not insert document %1$s");
1521 // emit message signal.
1522 message(bformat(res, disp_fn));
1523 buffer_->errors("Parse");