3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "dociterator.h"
21 #include "errorlist.h"
23 #include "FloatList.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "paragraph_funcs.h"
30 #include "ParagraphList.h"
31 #include "ParagraphParameters.h"
32 #include "pariterator.h"
35 #include "TocBackend.h"
36 #include "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
41 #include "insets/insetinclude.h"
43 #include "support/filetools.h"
44 #include "support/fs_extras.h"
45 #include "support/lyxlib.h"
47 #include <boost/bind.hpp>
48 #include <boost/filesystem/operations.hpp>
55 using support::bformat;
56 using support::FileName;
57 using support::libFileSearch;
58 using support::makeAbsPath;
59 using support::makeDisplayPath;
60 using support::onlyFilename;
61 using support::onlyPath;
62 using support::unlink;
67 namespace Alert = frontend::Alert;
68 namespace fs = boost::filesystem;
72 bool readFile(Buffer * const b, FileName const & s)
76 // File information about normal file
77 if (!fs::exists(s.toFilesystemEncoding())) {
78 docstring const file = makeDisplayPath(s.absFilename(), 50);
79 docstring text = bformat(_("The specified document\n%1$s"
80 "\ncould not be read."), file);
81 Alert::error(_("Could not read document"), text);
85 // Check if emergency save file exists and is newer.
86 FileName const e(s.absFilename() + ".emergency");
88 if (fs::exists(e.toFilesystemEncoding()) &&
89 fs::exists(s.toFilesystemEncoding()) &&
90 fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
92 docstring const file = makeDisplayPath(s.absFilename(), 20);
93 docstring const text =
94 bformat(_("An emergency save of the document "
96 "Recover emergency save?"), file);
97 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
98 _("&Recover"), _("&Load Original"),
102 // the file is not saved if we load the emergency file.
104 return b->readFile(e);
112 // Now check if autosave file is newer.
113 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
115 if (fs::exists(a.toFilesystemEncoding()) &&
116 fs::exists(s.toFilesystemEncoding()) &&
117 fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
119 docstring const file = makeDisplayPath(s.absFilename(), 20);
120 docstring const text =
121 bformat(_("The backup of the document "
122 "%1$s is newer.\n\nLoad the "
123 "backup instead?"), file);
124 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
125 _("&Load backup"), _("Load &original"),
129 // the file is not saved if we load the autosave file.
131 return b->readFile(a);
133 // Here we delete the autosave
140 return b->readFile(s);
148 bool loadLyXFile(Buffer * b, FileName const & s)
152 if (fs::is_readable(s.toFilesystemEncoding())) {
153 if (readFile(b, s)) {
154 b->lyxvc().file_found_hook(s);
155 if (!fs::is_writable(s.toFilesystemEncoding()))
156 b->setReadonly(true);
160 docstring const file = makeDisplayPath(s.absFilename(), 20);
161 // Here we probably should run
162 if (LyXVC::file_not_found_hook(s)) {
163 docstring const text =
164 bformat(_("Do you want to retrieve the document"
165 " %1$s from version control?"), file);
166 int const ret = Alert::prompt(_("Retrieve from version control?"),
167 text, 0, 1, _("&Retrieve"), _("&Cancel"));
170 // How can we know _how_ to do the checkout?
171 // With the current VC support it has to be,
172 // a RCS file since CVS do not have special ,v files.
174 return loadLyXFile(b, s);
181 // FIXME newFile() should probably be a member method of Application...
182 Buffer * newFile(string const & filename, string const & templatename,
186 Buffer * b = theBufferList().newBuffer(filename);
190 // use defaults.lyx as a default template if it exists.
191 if (templatename.empty())
192 tname = libFileSearch("templates", "defaults.lyx");
194 tname = makeAbsPath(templatename);
196 if (!tname.empty()) {
197 if (!b->readFile(tname)) {
198 docstring const file = makeDisplayPath(tname.absFilename(), 50);
199 docstring const text = bformat(
200 _("The specified document template\n%1$s\ncould not be read."),
202 Alert::error(_("Could not read template"), text);
203 theBufferList().release(b);
210 b->setFileName(filename);
213 b->setReadonly(false);
214 b->fully_loaded(true);
215 b->updateDocLang(b->params().language);
221 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
222 ErrorList & errorList)
224 TeXErrors::Errors::const_iterator cit = terr.begin();
225 TeXErrors::Errors::const_iterator end = terr.end();
227 for (; cit != end; ++cit) {
230 int errorrow = cit->error_in_line;
231 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
237 found = buf.texrow().getIdFromRow(errorrow, id_end,
239 } while (found && id_start == id_end && pos_start == pos_end);
241 errorList.push_back(ErrorItem(cit->error_desc,
242 cit->error_text, id_start, pos_start, pos_end));
247 string const bufferFormat(Buffer const & buffer)
249 if (buffer.isDocBook())
251 else if (buffer.isLiterate())
258 int countWords(DocIterator const & from, DocIterator const & to)
262 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
263 // Copied and adapted from isLetter() in ControlSpellChecker
265 && dit.pos() != dit.lastpos()
266 && dit.paragraph().isLetter(dit.pos())
267 && !dit.paragraph().isDeleted(dit.pos())) {
282 depth_type getDepth(DocIterator const & it)
284 depth_type depth = 0;
285 for (size_t i = 0 ; i < it.depth() ; ++i)
286 if (!it[i].inset().inMathed())
287 depth += it[i].paragraph().getDepth() + 1;
288 // remove 1 since the outer inset does not count
292 depth_type getItemDepth(ParIterator const & it)
294 Paragraph const & par = *it;
295 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
297 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
300 // this will hold the lowest depth encountered up to now.
301 depth_type min_depth = getDepth(it);
302 ParIterator prev_it = it;
305 --prev_it.top().pit();
307 // start of nested inset: go to outer par
309 if (prev_it.empty()) {
310 // start of document: nothing to do
315 // We search for the first paragraph with same label
316 // that is not more deeply nested.
317 Paragraph & prev_par = *prev_it;
318 depth_type const prev_depth = getDepth(prev_it);
319 if (labeltype == prev_par.layout()->labeltype) {
320 if (prev_depth < min_depth) {
321 return prev_par.itemdepth + 1;
323 else if (prev_depth == min_depth) {
324 return prev_par.itemdepth;
327 min_depth = std::min(min_depth, prev_depth);
328 // small optimization: if we are at depth 0, we won't
329 // find anything else
330 if (prev_depth == 0) {
337 bool needEnumCounterReset(ParIterator const & it)
339 Paragraph const & par = *it;
340 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
341 depth_type const cur_depth = par.getDepth();
342 ParIterator prev_it = it;
343 while (prev_it.pit()) {
344 --prev_it.top().pit();
345 Paragraph const & prev_par = *prev_it;
346 if (prev_par.getDepth() <= cur_depth)
347 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
349 // start of nested inset: reset
354 // set the label of a paragraph. This includes the counters.
355 void setLabel(Buffer const & buf, ParIterator & it, LyXTextClass const & textclass)
357 Paragraph & par = *it;
358 LyXLayout_ptr const & layout = par.layout();
359 Counters & counters = textclass.counters();
362 par.params().appendix(par.params().startOfAppendix());
364 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
365 if (!par.params().appendix() &&
366 par.params().startOfAppendix()) {
367 par.params().appendix(true);
368 textclass.counters().reset();
372 // Compute the item depth of the paragraph
373 par.itemdepth = getItemDepth(it);
375 if (layout->margintype == MARGIN_MANUAL) {
376 if (par.params().labelWidthString().empty())
377 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
379 par.params().labelWidthString(docstring());
382 // Optimisation: setLabel() can be called for each for each
383 // paragraph of the document. So we make the string static to
384 // avoid the repeated instanciation.
385 static docstring itemlabel;
387 // is it a layout that has an automatic label?
388 if (layout->labeltype == LABEL_COUNTER) {
389 if (layout->toclevel <= buf.params().secnumdepth
390 && (layout->latextype != LATEX_ENVIRONMENT
391 || isFirstInSequence(it.pit(), it.plist()))) {
392 counters.step(layout->counter);
393 par.params().labelString(
394 par.expandLabel(layout, buf.params()));
396 par.params().labelString(docstring());
398 } else if (layout->labeltype == LABEL_ITEMIZE) {
399 // At some point of time we should do something more
400 // clever here, like:
401 // par.params().labelString(
402 // buf.params().user_defined_bullet(par.itemdepth).getText());
403 // for now, use a simple hardcoded label
404 switch (par.itemdepth) {
406 itemlabel = char_type(0x2022);
409 itemlabel = char_type(0x2013);
412 itemlabel = char_type(0x2217);
415 itemlabel = char_type(0x2219); // or 0x00b7
418 par.params().labelString(itemlabel);
420 } else if (layout->labeltype == LABEL_ENUMERATE) {
422 // Yes I know this is a really, really! bad solution
424 docstring enumcounter = from_ascii("enum");
426 switch (par.itemdepth) {
438 // not a valid enumdepth...
442 // Maybe we have to reset the enumeration counter.
443 if (needEnumCounterReset(it))
444 counters.reset(enumcounter);
446 counters.step(enumcounter);
450 switch (par.itemdepth) {
452 format = N_("\\arabic{enumi}.");
455 format = N_("(\\alph{enumii})");
458 format = N_("\\roman{enumiii}.");
461 format = N_("\\Alph{enumiv}.");
464 // not a valid enumdepth...
468 par.params().labelString(counters.counterLabel(
469 par.translateIfPossible(from_ascii(format), buf.params())));
471 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
472 counters.step(from_ascii("bibitem"));
473 int number = counters.value(from_ascii("bibitem"));
475 par.bibitem()->setCounter(number);
477 par.params().labelString(
478 par.translateIfPossible(layout->labelstring(), buf.params()));
479 // In biblio shouldn't be following counters but...
480 } else if (layout->labeltype == LABEL_SENSITIVE) {
481 // Search for the first float or wrap inset in the iterator
482 size_t i = it.depth();
487 if (in->lyxCode() == InsetBase::FLOAT_CODE
488 || in->lyxCode() == InsetBase::WRAP_CODE)
491 docstring const & type = in->getInsetName();
494 Floating const & fl = textclass.floats().getType(to_ascii(type));
496 counters.step(from_ascii(fl.type()));
498 // Doesn't work... yet.
499 par.params().labelString(par.translateIfPossible(
500 bformat(from_ascii("%1$s #:"), from_utf8(fl.name())),
503 // par->SetLayout(0);
504 par.params().labelString(par.translateIfPossible(
505 layout->labelstring(), buf.params()));
508 } else if (layout->labeltype == LABEL_NO_LABEL)
509 par.params().labelString(docstring());
511 par.params().labelString(
512 par.translateIfPossible(layout->labelstring(), buf.params()));
518 bool updateCurrentLabel(Buffer const & buf,
521 if (it == par_iterator_end(buf.inset()))
524 // if (it.lastpit == 0 && LyXText::isMainText(buf))
527 switch (it->layout()->labeltype) {
532 case LABEL_TOP_ENVIRONMENT:
533 case LABEL_CENTERED_TOP_ENVIRONMENT:
536 setLabel(buf, it, buf.params().getLyXTextClass());
539 case LABEL_SENSITIVE:
541 // do more things with enumerate later
542 case LABEL_ENUMERATE:
546 // This is dead code which get rid of a warning:
551 void updateLabels(Buffer const & buf,
552 ParIterator & from, ParIterator & to, bool childonly)
554 for (ParIterator it = from; it != to; ++it) {
555 if (it.pit() > it.lastpit())
557 if (!updateCurrentLabel (buf, it)) {
558 updateLabels(buf, childonly);
565 void updateLabels(Buffer const & buf, ParIterator & iter, bool childonly)
567 if (updateCurrentLabel(buf, iter))
570 updateLabels(buf, childonly);
574 void updateLabels(Buffer const & buf, bool childonly)
576 // Use the master text class also for child documents
577 LyXTextClass const & textclass = buf.params().getLyXTextClass();
580 // If this is a child document start with the master
581 Buffer const * const master = buf.getMasterBuffer();
582 if (master != &buf) {
583 updateLabels(*master);
587 // start over the counters
588 textclass.counters().reset();
591 ParIterator const end = par_iterator_end(buf.inset());
593 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
594 // reduce depth if necessary
596 Paragraph const & prevpar = it.plist()[it.pit() - 1];
597 it->params().depth(min(it->params().depth(),
598 prevpar.getMaxDepthAfter()));
600 it->params().depth(0);
602 // set the counter for this paragraph
603 setLabel(buf, it, textclass);
606 InsetList::const_iterator iit = it->insetlist.begin();
607 InsetList::const_iterator end = it->insetlist.end();
608 for (; iit != end; ++iit) {
609 if (iit->inset->lyxCode() == InsetBase::INCLUDE_CODE)
610 static_cast<InsetInclude const *>(iit->inset)
615 const_cast<Buffer &>(buf).tocBackend().update();