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 "bufferparams.h"
22 #include "coordcache.h"
23 #include "CutAndPaste.h"
25 #include "dispatchresult.h"
26 #include "errorlist.h"
28 #include "FloatList.h"
29 #include "funcrequest.h"
30 #include "FuncStatus.h"
33 #include "insetiterator.h"
35 #include "LaTeXFeatures.h"
36 #include "lyx_cb.h" // added for Dispatch functions
40 #include "lyxlayout.h"
42 #include "lyxtextclass.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "pariterator.h"
53 #include "WordLangTuple.h"
54 #include "metricsinfo.h"
56 #include "insets/insetbibtex.h"
57 #include "insets/insetcommand.h" // ChangeRefs
58 #include "insets/insetref.h"
59 #include "insets/insettext.h"
61 #include "frontends/Alert.h"
62 #include "frontends/Application.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/font_metrics.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
84 using lyx::support::addPath;
85 using lyx::support::bformat;
86 using lyx::support::FileFilterList;
87 using lyx::support::fileSearch;
88 using lyx::support::isDirWriteable;
89 using lyx::support::makeDisplayPath;
90 using lyx::support::makeAbsPath;
91 using lyx::support::package;
95 using std::istringstream;
100 using std::mem_fun_ref;
107 unsigned int const saved_positions_num = 20;
110 /// Return an inset of this class if it exists at the current cursor position
112 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
115 DocIterator it = cur;
116 if (it.nextInset() &&
117 it.nextInset()->lyxCode() == code) {
118 inset = static_cast<T*>(it.nextInset());
126 BufferView::BufferView()
127 : buffer_(0), wh_(0),
129 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
132 xsel_cache_.set = false;
134 saved_positions.resize(saved_positions_num);
135 // load saved bookmarks
136 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
137 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
138 bm != bmList.end(); ++bm)
139 if (bm->get<0>() < saved_positions_num)
140 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
141 // and then clear them
144 intl_->initKeyMapper(lyxrc.use_kbmap);
148 BufferView::~BufferView()
153 Buffer * BufferView::buffer() const
159 void BufferView::setBuffer(Buffer * b)
161 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
162 << "[ b = " << b << "]" << endl;
165 // Save the actual cursor position and anchor inside the
166 // buffer so that it can be restored in case we rechange
167 // to this buffer later on.
168 buffer_->saveCursor(cursor_.selectionBegin(),
169 cursor_.selectionEnd());
170 // current buffer is going to be switched-off, save cursor pos
171 LyX::ref().session().saveFilePosition(buffer_->fileName(),
172 boost::tie(cursor_.pit(), cursor_.pos()) );
175 // If we're quitting lyx, don't bother updating stuff
181 // If we are closing current buffer, switch to the first in
184 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
185 << " No Buffer!" << endl;
186 // We are closing the buffer, use the first buffer as current
187 buffer_ = theApp->bufferList().first();
189 // Set current buffer
194 cursor_ = LCursor(*this);
199 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
200 << "Buffer addr: " << buffer_ << endl;
201 cursor_.push(buffer_->inset());
202 cursor_.resetAnchor();
203 buffer_->text().init(this);
204 buffer_->text().setCurrentFont(cursor_);
205 if (buffer_->getCursor().size() > 0 &&
206 buffer_->getAnchor().size() > 0)
208 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
209 cursor_.resetAnchor();
210 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
211 cursor_.setSelection();
217 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
218 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
222 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
224 // Get absolute path of file and add ".lyx"
225 // to the filename if necessary
226 string s = fileSearch(string(), filename, "lyx");
228 bool const found = !s.empty();
233 // File already open?
234 if (theApp->bufferList().exists(s)) {
235 docstring const file = makeDisplayPath(s, 20);
236 docstring text = bformat(_("The document %1$s is already "
237 "loaded.\n\nDo you want to revert "
238 "to the saved version?"), file);
239 int const ret = Alert::prompt(_("Revert to saved document?"),
240 text, 0, 1, _("&Revert"), _("&Switch to document"));
243 setBuffer(theApp->bufferList().getBuffer(s));
246 // FIXME: should be LFUN_REVERT
247 if (!theApp->bufferList().close(theApp->bufferList().getBuffer(s), false))
249 // Fall through to new load. (Asger)
255 b = theApp->bufferList().newBuffer(s);
256 if (!::loadLyXFile(b, s)) {
257 theApp->bufferList().release(b);
261 docstring text = bformat(_("The document %1$s does not yet "
262 "exist.\n\nDo you want to create "
263 "a new document?"), lyx::from_utf8(s));
264 int const ret = Alert::prompt(_("Create new document?"),
265 text, 0, 1, _("&Create"), _("Cancel"));
268 b = newFile(s, string(), true);
276 // Send the "errors" signal in case of parsing errors
279 // scroll to the position when the file was last closed
280 if (lyxrc.use_lastfilepos) {
283 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
284 // I am not sure how to separate the following part to a function
285 // so I will leave this to Lars.
287 // check pit since the document may be externally changed.
288 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
289 ParIterator it = b->par_iterator_begin();
290 ParIterator const end = b->par_iterator_end();
291 for (; it != end; ++it)
292 if (it.pit() == pit) {
293 // restored pos may be bigger than it->size
294 setCursor(makeDocIterator(it, min(pos, it->size())));
295 update(Update::FitCursor);
302 LyX::ref().session().addLastFile(b->fileName());
308 void BufferView::reload()
310 string const fn = buffer_->fileName();
311 if (theApp->bufferList().close(buffer_, false))
316 void BufferView::resize()
321 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
323 buffer_->text().init(this);
329 bool BufferView::fitCursor()
331 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
332 LyXFont const font = cursor_.getFont();
333 int const asc = font_metrics::maxAscent(font);
334 int const des = font_metrics::maxDescent(font);
335 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
336 if (p.y_ - asc >= 0 && p.y_ + des < height_)
344 bool BufferView::multiParSel()
346 if (!cursor_.selection())
348 bool ret = multiparsel_cache_;
349 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
350 // Either this, or previous selection spans paragraphs
351 return ret || multiparsel_cache_;
355 bool BufferView::update(Update::flags flags)
357 // This is close to a hot-path.
358 if (lyxerr.debugging(Debug::DEBUG)) {
360 << BOOST_CURRENT_FUNCTION
361 << "[fitcursor = " << (flags & Update::FitCursor)
362 << ", forceupdate = " << (flags & Update::Force)
363 << ", singlepar = " << (flags & Update::SinglePar)
364 << "] buffer: " << buffer_ << endl;
367 // Check needed to survive LyX startup
371 // Update macro store
372 buffer_->buildMacros();
374 // First drawing step
375 updateMetrics(flags & Update::SinglePar);
377 // The second drawing step is done in WorkArea::redraw() if needed.
378 bool const need_second_step =
379 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
380 && (fitCursor() || multiParSel());
382 return need_second_step;
386 void BufferView::updateScrollbar()
389 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
390 << " no text in updateScrollbar" << endl;
391 scrollbarParameters_.reset();
395 LyXText & t = buffer_->text();
396 int const parsize = int(t.paragraphs().size() - 1);
397 if (anchor_ref_ > parsize) {
398 anchor_ref_ = parsize;
403 << BOOST_CURRENT_FUNCTION
404 << " Updating scrollbar: height: " << t.paragraphs().size()
405 << " curr par: " << cursor_.bottom().pit()
406 << " default height " << defaultRowHeight() << endl;
408 // It would be better to fix the scrollbar to understand
409 // values in [0..1] and divide everything by wh
411 // estimated average paragraph height:
414 int h = t.getPar(anchor_ref_).height();
416 // Normalize anchor/offset (MV):
417 while (offset_ref_ > h && anchor_ref_ < parsize) {
420 h = t.getPar(anchor_ref_).height();
422 // Look at paragraph heights on-screen
425 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
428 int const h2 = t.getPar(pit).height();
432 int const hav = sumh / nh;
433 // More realistic average paragraph height
437 scrollbarParameters_.height = (parsize + 1) * wh_;
438 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
439 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
443 ScrollbarParameters const & BufferView::scrollbarParameters() const
445 return scrollbarParameters_;
449 void BufferView::scrollDocView(int value)
451 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
452 << "[ value = " << value << "]" << endl;
457 LyXText & t = buffer_->text();
459 float const bar = value / float(wh_ * t.paragraphs().size());
461 anchor_ref_ = int(bar * t.paragraphs().size());
462 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
463 anchor_ref_ = int(t.paragraphs().size()) - 1;
464 t.redoParagraph(anchor_ref_);
465 int const h = t.getPar(anchor_ref_).height();
466 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
470 void BufferView::setCursorFromScrollbar()
472 LyXText & t = buffer_->text();
474 int const height = 2 * defaultRowHeight();
475 int const first = height;
476 int const last = height_ - height;
477 LCursor & cur = cursor_;
479 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
482 case bv_funcs::CUR_ABOVE:
483 t.setCursorFromCoordinates(cur, 0, first);
484 cur.clearSelection();
486 case bv_funcs::CUR_BELOW:
487 t.setCursorFromCoordinates(cur, 0, last);
488 cur.clearSelection();
490 case bv_funcs::CUR_INSIDE:
491 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
492 int const newy = min(last, max(y, first));
494 cur.reset(buffer_->inset());
495 t.setCursorFromCoordinates(cur, 0, newy);
501 Change const BufferView::getCurrentChange()
503 if (!buffer_->params().tracking_changes || !cursor_.selection())
504 return Change(Change::UNCHANGED);
506 DocIterator dit = cursor_.selectionBegin();
507 return dit.paragraph().lookupChange(dit.pos());
511 void BufferView::savePosition(unsigned int i)
513 if (i >= saved_positions_num)
515 BOOST_ASSERT(cursor_.inTexted());
516 saved_positions[i] = Position(buffer_->fileName(),
517 cursor_.paragraph().id(),
520 // emit message signal.
521 message(bformat(_("Saved bookmark %1$d"), i));
525 void BufferView::restorePosition(unsigned int i)
527 if (i >= saved_positions_num)
530 string const fname = saved_positions[i].filename;
532 cursor_.clearSelection();
534 if (fname != buffer_->fileName()) {
536 if (theApp->bufferList().exists(fname))
537 b = theApp->bufferList().getBuffer(fname);
539 b = theApp->bufferList().newBuffer(fname);
540 // Don't ask, just load it
541 ::loadLyXFile(b, fname);
547 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
548 if (par == buffer_->par_iterator_end())
551 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
554 // emit message signal.
555 message(bformat(_("Moved to bookmark %1$d"), i));
559 bool BufferView::isSavedPosition(unsigned int i)
561 return i < saved_positions_num && !saved_positions[i].filename.empty();
564 void BufferView::saveSavedPositions()
566 // save bookmarks. It is better to use the pit interface
567 // but I do not know how to effectively convert between
569 for (unsigned int i=1; i < saved_positions_num; ++i) {
570 if ( isSavedPosition(i) )
571 LyX::ref().session().saveBookmark( boost::tie(
573 saved_positions[i].filename,
574 saved_positions[i].par_id,
575 saved_positions[i].par_pos) );
579 void BufferView::switchKeyMap()
581 if (!lyxrc.rtl_support)
584 if (getLyXText()->real_current_font.isRightToLeft()) {
585 if (intl_->keymap == Intl::PRIMARY)
588 if (intl_->keymap == Intl::SECONDARY)
594 int BufferView::workWidth() const
600 void BufferView::center()
602 CursorSlice & bot = cursor_.bottom();
603 lyx::pit_type const pit = bot.pit();
604 bot.text()->redoParagraph(pit);
605 Paragraph const & par = bot.text()->paragraphs()[pit];
607 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
608 + par.ascent() - height_ / 2;
612 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
616 switch (cmd.action) {
619 flag.enabled(!buffer_->undostack().empty());
622 flag.enabled(!buffer_->redostack().empty());
624 case LFUN_FILE_INSERT:
625 case LFUN_FILE_INSERT_ASCII_PARA:
626 case LFUN_FILE_INSERT_ASCII:
627 case LFUN_BOOKMARK_SAVE:
628 // FIXME: Actually, these LFUNS should be moved to LyXText
629 flag.enabled(cursor_.inTexted());
631 case LFUN_FONT_STATE:
632 case LFUN_LABEL_INSERT:
633 case LFUN_PARAGRAPH_GOTO:
634 // FIXME handle non-trivially
635 case LFUN_OUTLINE_UP:
636 case LFUN_OUTLINE_DOWN:
637 case LFUN_OUTLINE_IN:
638 case LFUN_OUTLINE_OUT:
640 case LFUN_REFERENCE_NEXT:
642 case LFUN_WORD_REPLACE:
645 case LFUN_MARK_TOGGLE:
646 case LFUN_SCREEN_RECENTER:
647 case LFUN_BIBTEX_DATABASE_ADD:
648 case LFUN_BIBTEX_DATABASE_DEL:
649 case LFUN_WORDS_COUNT:
650 case LFUN_NEXT_INSET_TOGGLE:
654 case LFUN_LABEL_GOTO: {
655 flag.enabled(!cmd.argument().empty()
656 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
660 case LFUN_BOOKMARK_GOTO:
661 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
663 case LFUN_CHANGES_TRACK:
665 flag.setOnOff(buffer_->params().tracking_changes);
668 case LFUN_CHANGES_OUTPUT: {
669 OutputParams runparams;
670 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
671 flag.enabled(buffer_ && buffer_->params().tracking_changes
672 && features.isAvailable("dvipost"));
673 flag.setOnOff(buffer_->params().output_changes);
677 case LFUN_CHANGES_MERGE:
678 case LFUN_CHANGE_ACCEPT: // what about these two
679 case LFUN_CHANGE_REJECT: // what about these two
680 case LFUN_ALL_CHANGES_ACCEPT:
681 case LFUN_ALL_CHANGES_REJECT:
682 flag.enabled(buffer_ && buffer_->params().tracking_changes);
685 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
686 flag.setOnOff(buffer_->params().compressed);
698 bool BufferView::dispatch(FuncRequest const & cmd)
700 //lyxerr << BOOST_CURRENT_FUNCTION
701 // << [ cmd = " << cmd << "]" << endl;
703 // Make sure that the cached BufferView is correct.
704 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
705 << " action[" << cmd.action << ']'
706 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
707 << " x[" << cmd.x << ']'
708 << " y[" << cmd.y << ']'
709 << " button[" << cmd.button() << ']'
712 LCursor & cur = cursor_;
714 switch (cmd.action) {
718 cur.message(_("Undo"));
719 cur.clearSelection();
720 if (!textUndo(*this))
721 cur.message(_("No further undo information"));
729 cur.message(_("Redo"));
730 cur.clearSelection();
731 if (!textRedo(*this))
732 cur.message(_("No further redo information"));
738 case LFUN_FILE_INSERT:
739 // FIXME: We don't know the encoding of filenames
740 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
743 case LFUN_FILE_INSERT_ASCII_PARA:
744 // FIXME: We don't know the encoding of filenames
745 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
748 case LFUN_FILE_INSERT_ASCII:
749 // FIXME: We don't know the encoding of filenames
750 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
753 case LFUN_FONT_STATE:
754 cur.message(lyx::from_utf8(cur.currentState()));
757 case LFUN_BOOKMARK_SAVE:
758 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
761 case LFUN_BOOKMARK_GOTO:
762 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
765 case LFUN_LABEL_GOTO: {
766 string label = lyx::to_utf8(cmd.argument());
769 getInsetByCode<InsetRef>(cursor_,
770 InsetBase::REF_CODE);
772 label = inset->getContents();
782 case LFUN_PARAGRAPH_GOTO: {
783 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
784 ParIterator par = buffer_->getParFromID(id);
785 if (par == buffer_->par_iterator_end()) {
786 lyxerr[Debug::INFO] << "No matching paragraph found! ["
787 << id << ']' << endl;
790 lyxerr[Debug::INFO] << "Paragraph " << par->id()
791 << " found." << endl;
795 setCursor(makeDocIterator(par, 0));
802 case LFUN_OUTLINE_UP:
803 lyx::toc::outline(lyx::toc::Up, cursor_);
804 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
805 updateLabels(*buffer_);
807 case LFUN_OUTLINE_DOWN:
808 lyx::toc::outline(lyx::toc::Down, cursor_);
809 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
810 updateLabels(*buffer_);
812 case LFUN_OUTLINE_IN:
813 lyx::toc::outline(lyx::toc::In, cursor_);
814 updateLabels(*buffer_);
816 case LFUN_OUTLINE_OUT:
817 lyx::toc::outline(lyx::toc::Out, cursor_);
818 updateLabels(*buffer_);
822 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
825 case LFUN_REFERENCE_NEXT: {
826 vector<InsetBase_code> tmp;
827 tmp.push_back(InsetBase::LABEL_CODE);
828 tmp.push_back(InsetBase::REF_CODE);
829 bv_funcs::gotoInset(this, tmp, true);
833 case LFUN_CHANGES_TRACK:
837 case LFUN_CHANGES_OUTPUT: {
838 bool const state = buffer_->params().output_changes;
839 buffer_->params().output_changes = !state;
843 case LFUN_CHANGES_MERGE:
844 if (lyx::find::findNextChange(this))
845 showDialog("changes");
848 case LFUN_ALL_CHANGES_ACCEPT: {
849 cursor_.reset(buffer_->inset());
851 #warning FIXME changes
853 while (lyx::find::findNextChange(this))
854 getLyXText()->acceptChange(cursor_);
859 case LFUN_ALL_CHANGES_REJECT: {
860 cursor_.reset(buffer_->inset());
862 #warning FIXME changes
864 while (lyx::find::findNextChange(this))
865 getLyXText()->rejectChange(cursor_);
870 lyx::find::find(this, cmd);
873 case LFUN_WORD_REPLACE:
874 lyx::find::replace(this, cmd);
878 cur.clearSelection();
880 cur.message(lyx::from_utf8(N_("Mark off")));
884 cur.clearSelection();
887 cur.message(lyx::from_utf8(N_("Mark on")));
890 case LFUN_MARK_TOGGLE:
891 cur.clearSelection();
894 cur.message(lyx::from_utf8(N_("Mark removed")));
897 cur.message(lyx::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(lyx::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(lyx::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;
1031 void BufferView::workAreaResize(int width, int height)
1033 bool const widthChange = width != width_;
1034 bool const heightChange = height != height_;
1036 // Update from work area
1040 if (buffer_ && widthChange) {
1041 // The WorkArea content needs a resize
1045 if (widthChange || heightChange)
1050 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1052 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1054 // This is only called for mouse related events including
1055 // LFUN_FILE_OPEN generated by drag-and-drop.
1056 FuncRequest cmd = cmd0;
1062 cur.push(buffer_->inset());
1063 cur.selection() = cursor_.selection();
1065 // Doesn't go through lyxfunc, so we need to update
1066 // the layout choice etc. ourselves
1068 // E.g. Qt mouse press when no buffer
1072 // Either the inset under the cursor or the
1073 // surrounding LyXText will handle this event.
1075 // Build temporary cursor.
1076 cmd.y = min(max(cmd.y, -1), height_);
1077 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1078 //lyxerr << BOOST_CURRENT_FUNCTION
1079 // << " * hit inset at tip: " << inset << endl;
1080 //lyxerr << BOOST_CURRENT_FUNCTION
1081 // << " * created temp cursor:" << cur << endl;
1083 // Put anchor at the same position.
1086 // Try to dispatch to an non-editable inset near this position
1087 // via the temp cursor. If the inset wishes to change the real
1088 // cursor it has to do so explicitly by using
1089 // cur.bv().cursor() = cur; (or similar)
1091 inset->dispatch(cur, cmd);
1093 // Now dispatch to the temporary cursor. If the real cursor should
1094 // be modified, the inset's dispatch has to do so explicitly.
1095 if (!cur.result().dispatched())
1098 if (cur.result().dispatched()) {
1099 // Redraw if requested or necessary.
1100 if (cur.result().update())
1101 update(Update::FitCursor | Update::Force);
1103 update(Update::FitCursor | Update::MultiParSel);
1110 void BufferView::scroll(int lines)
1115 // LyXText const * t = &buffer_->text();
1116 // int const line_height = defaultRowHeight();
1118 // // The new absolute coordinate
1119 // int new_top_y = top_y() + lines * line_height;
1121 // // Restrict to a valid value
1122 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1123 // new_top_y = std::max(0, new_top_y);
1125 // scrollDocView(new_top_y);
1127 // // Update the scrollbar.
1128 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1132 void BufferView::setCursorFromRow(int row)
1137 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1140 buffer_->text().setCursor(cursor_, 0, 0);
1142 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1146 void BufferView::gotoLabel(string const & label)
1148 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1149 vector<string> labels;
1150 it->getLabelList(*buffer_, labels);
1151 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1160 LyXText * BufferView::getLyXText()
1162 LyXText * text = cursor_.innerText();
1168 LyXText const * BufferView::getLyXText() const
1170 LyXText const * text = cursor_.innerText();
1176 int BufferView::workHeight() const
1182 void BufferView::setCursor(DocIterator const & dit)
1184 size_t const n = dit.depth();
1185 for (size_t i = 0; i < n; ++i)
1186 dit[i].inset().edit(cursor_, true);
1188 cursor_.setCursor(dit);
1189 cursor_.selection() = false;
1193 void BufferView::mouseSetCursor(LCursor & cur)
1195 BOOST_ASSERT(&cur.bv() == this);
1197 // Has the cursor just left the inset?
1198 bool badcursor = false;
1199 if (&cursor_.inset() != &cur.inset())
1200 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1202 // do the dEPM magic if needed
1203 // FIXME: move this to InsetText::notifyCursorLeaves?
1204 if (!badcursor && cursor_.inTexted())
1205 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1208 cursor_.clearSelection();
1209 cursor_.setTargetX();
1215 void BufferView::putSelectionAt(DocIterator const & cur,
1216 int length, bool backwards)
1218 cursor_.clearSelection();
1224 cursor_.pos() += length;
1225 cursor_.setSelection(cursor_, -length);
1227 cursor_.setSelection(cursor_, length);
1232 LCursor & BufferView::cursor()
1238 LCursor const & BufferView::cursor() const
1244 lyx::pit_type BufferView::anchor_ref() const
1250 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1252 return metrics_info_;
1256 void BufferView::updateMetrics(bool singlepar)
1258 // Remove old position cache
1260 LyXText & buftext = buffer_->text();
1261 lyx::pit_type size = int(buftext.paragraphs().size());
1263 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1264 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1268 lyx::pit_type const pit = anchor_ref_;
1271 size_t const npit = buftext.paragraphs().size();
1273 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1274 // the (main text, not inset!) paragraph containing the cursor.
1275 // (if this paragraph contains insets etc., rebreaking will
1276 // recursively descend)
1277 if (!singlepar || pit == cursor_.bottom().pit())
1278 buftext.redoParagraph(pit);
1279 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1281 // Redo paragraphs above anchor if necessary; again, in Single Par
1282 // mode, only if we encounter the (main text) one having the cursor.
1284 while (y1 > 0 && pit1 > 0) {
1285 y1 -= buftext.getPar(pit1).ascent();
1287 if (!singlepar || pit1 == cursor_.bottom().pit())
1288 buftext.redoParagraph(pit1);
1289 y1 -= buftext.getPar(pit1).descent();
1293 // Take care of ascent of first line
1294 y1 -= buftext.getPar(pit1).ascent();
1296 // Normalize anchor for next time
1300 // Grey at the beginning is ugly
1301 if (pit1 == 0 && y1 > 0) {
1307 // Redo paragraphs below the anchor if necessary. Single par mode:
1308 // only the one containing the cursor if encountered.
1310 while (y2 < height_ && pit2 < int(npit) - 1) {
1311 y2 += buftext.getPar(pit2).descent();
1313 if (!singlepar || pit2 == cursor_.bottom().pit())
1314 buftext.redoParagraph(pit2);
1315 y2 += buftext.getPar(pit2).ascent();
1318 // Take care of descent of last line
1319 y2 += buftext.getPar(pit2).descent();
1321 // The coordinates of all these paragraphs are correct, cache them
1323 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1324 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1325 Paragraph const & par = buftext.getPar(pit);
1327 parPos[pit] = Point(0, y);
1328 if (singlepar && pit == cursor_.bottom().pit()) {
1329 // In Single Paragraph mode, collect here the
1330 // y1 and y2 of the (one) paragraph the cursor is in
1331 y1 = y - par.ascent();
1332 y2 = y + par.descent();
1338 // collect cursor paragraph iter bounds
1339 pit1 = cursor_.bottom().pit();
1340 pit2 = cursor_.bottom().pit();
1343 lyxerr[Debug::DEBUG]
1344 << BOOST_CURRENT_FUNCTION
1347 << " pit1: " << pit1
1348 << " pit2: " << pit2
1349 << " npit: " << npit
1350 << " singlepar: " << singlepar
1354 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1358 void BufferView::menuInsertLyXFile(string const & filenm)
1360 BOOST_ASSERT(cursor_.inTexted());
1361 string filename = filenm;
1363 if (filename.empty()) {
1364 // Launch a file browser
1365 string initpath = lyxrc.document_path;
1368 string const trypath = buffer_->filePath();
1369 // If directory is writeable, use this as default.
1370 if (isDirWriteable(trypath))
1374 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1376 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1377 string(lyxrc.document_path)),
1378 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1379 string(addPath(package().system_support(), "examples"))));
1381 FileDialog::Result result =
1382 fileDlg.open(initpath,
1383 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1386 if (result.first == FileDialog::Later)
1389 filename = result.second;
1391 // check selected filename
1392 if (filename.empty()) {
1393 // emit message signal.
1394 message(_("Canceled."));
1399 // Get absolute path of file and add ".lyx"
1400 // to the filename if necessary
1401 filename = fileSearch(string(), filename, "lyx");
1403 docstring const disp_fn = makeDisplayPath(filename);
1404 // emit message signal.
1405 message(bformat(_("Inserting document %1$s..."), disp_fn));
1408 Buffer buf("", false);
1409 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1410 ErrorList & el = buffer_->errorList("Parse");
1411 // Copy the inserted document error list into the current buffer one.
1412 el = buf.errorList("Parse");
1413 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1414 buf.params().textclass, el);
1415 res = _("Document %1$s inserted.");
1417 res = _("Could not insert document %1$s");
1419 // emit message signal.
1420 message(bformat(res, disp_fn));
1421 buffer_->errors("Parse");
1426 void BufferView::trackChanges()
1428 bool const tracking = buffer_->params().tracking_changes;
1431 for_each(buffer_->par_iterator_begin(),
1432 buffer_->par_iterator_end(),
1433 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1434 buffer_->params().tracking_changes = true;
1436 // We cannot allow undos beyond the freeze point
1437 buffer_->undostack().clear();
1439 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1440 if (lyx::find::findNextChange(this)) {
1441 showDialog("changes");
1445 for_each(buffer_->par_iterator_begin(),
1446 buffer_->par_iterator_end(),
1447 mem_fun_ref(&Paragraph::untrackChanges));
1449 buffer_->params().tracking_changes = false;
1452 buffer_->redostack().clear();