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 "vc-backend.h"
38 #include "frontends/Alert.h"
40 #include "insets/insetbibitem.h"
42 #include "support/filetools.h"
43 #include "support/fs_extras.h"
44 #include "support/lyxlib.h"
48 #include <boost/bind.hpp>
49 #include <boost/filesystem/operations.hpp>
55 using lyx::support::bformat;
56 using lyx::support::libFileSearch;
57 using lyx::support::makeDisplayPath;
58 using lyx::support::onlyFilename;
59 using lyx::support::onlyPath;
60 using lyx::support::unlink;
65 namespace Alert = lyx::frontend::Alert;
66 namespace fs = boost::filesystem;
70 bool readFile(Buffer * const b, string const & s)
74 // File information about normal file
76 docstring const file = makeDisplayPath(s, 50);
77 docstring text = bformat(_("The specified document\n%1$s"
78 "\ncould not be read."), file);
79 Alert::error(_("Could not read document"), text);
83 // Check if emergency save file exists and is newer.
84 string const e = onlyPath(s) + onlyFilename(s) + ".emergency";
86 if (fs::exists(e) && fs::exists(s)
87 && fs::last_write_time(e) > fs::last_write_time(s))
89 docstring const file = makeDisplayPath(s, 20);
90 docstring const text =
91 bformat(_("An emergency save of the document "
93 "Recover emergency save?"), file);
94 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
95 _("&Recover"), _("&Load Original"),
99 // the file is not saved if we load the emergency file.
101 return b->readFile(e);
109 // Now check if autosave file is newer.
110 string const a = onlyPath(s) + '#' + onlyFilename(s) + '#';
112 if (fs::exists(a) && fs::exists(s)
113 && fs::last_write_time(a) > fs::last_write_time(s))
115 docstring const file = makeDisplayPath(s, 20);
116 docstring const text =
117 bformat(_("The backup of the document "
118 "%1$s is newer.\n\nLoad the "
119 "backup instead?"), file);
120 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
121 _("&Load backup"), _("Load &original"),
125 // the file is not saved if we load the autosave file.
127 return b->readFile(a);
129 // Here we delete the autosave
136 return b->readFile(s);
144 bool loadLyXFile(Buffer * b, string const & s)
148 if (fs::is_readable(s)) {
149 if (readFile(b, s)) {
150 b->lyxvc().file_found_hook(s);
151 if (!fs::is_writable(s))
152 b->setReadonly(true);
156 docstring const file = makeDisplayPath(s, 20);
157 // Here we probably should run
158 if (LyXVC::file_not_found_hook(s)) {
159 docstring const text =
160 bformat(_("Do you want to retrieve the document"
161 " %1$s from version control?"), file);
162 int const ret = Alert::prompt(_("Retrieve from version control?"),
163 text, 0, 1, _("&Retrieve"), _("&Cancel"));
166 // How can we know _how_ to do the checkout?
167 // With the current VC support it has to be,
168 // a RCS file since CVS do not have special ,v files.
170 return loadLyXFile(b, s);
177 // FIXME newFile() should probably be a member method of Application...
178 Buffer * newFile(string const & filename, string const & templatename,
182 Buffer * b = theBufferList().newBuffer(filename);
186 // use defaults.lyx as a default template if it exists.
187 if (templatename.empty())
188 tname = libFileSearch("templates", "defaults.lyx");
190 tname = templatename;
192 if (!tname.empty()) {
193 if (!b->readFile(tname)) {
194 docstring const file = makeDisplayPath(tname, 50);
195 docstring const text = bformat(
196 _("The specified document template\n%1$s\ncould not be read."),
198 Alert::error(_("Could not read template"), text);
199 theBufferList().release(b);
206 b->setFileName(filename);
209 b->setReadonly(false);
210 b->fully_loaded(true);
211 b->updateDocLang(b->params().language);
217 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
218 ErrorList & errorList)
220 TeXErrors::Errors::const_iterator cit = terr.begin();
221 TeXErrors::Errors::const_iterator end = terr.end();
223 for (; cit != end; ++cit) {
226 int errorrow = cit->error_in_line;
227 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
233 found = buf.texrow().getIdFromRow(errorrow, id_end,
235 } while (found && id_start == id_end && pos_start == pos_end);
237 errorList.push_back(ErrorItem(lyx::from_utf8(cit->error_desc),
238 lyx::from_utf8(cit->error_text), id_start, pos_start, pos_end));
243 string const bufferFormat(Buffer const & buffer)
245 if (buffer.isDocBook())
247 else if (buffer.isLiterate())
254 int countWords(DocIterator const & from, DocIterator const & to)
258 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
259 // Copied and adapted from isLetter() in ControlSpellChecker
261 && dit.pos() != dit.lastpos()
262 && dit.paragraph().isLetter(dit.pos())
263 && !dit.paragraph().isDeleted(dit.pos())) {
278 lyx::depth_type getDepth(DocIterator const & it)
280 lyx::depth_type depth = 0;
281 for (size_t i = 0 ; i < it.depth() ; ++i)
282 if (!it[i].inset().inMathed())
283 depth += it[i].paragraph().getDepth() + 1;
284 // remove 1 since the outer inset does not count
288 lyx::depth_type getItemDepth(ParIterator const & it)
290 Paragraph const & par = *it;
291 LYX_LABEL_TYPES const labeltype = par.layout()->labeltype;
293 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
296 // this will hold the lowest depth encountered up to now.
297 lyx::depth_type min_depth = getDepth(it);
298 ParIterator prev_it = it;
301 --prev_it.top().pit();
303 // start of nested inset: go to outer par
305 if (prev_it.empty()) {
306 // start of document: nothing to do
311 // We search for the first paragraph with same label
312 // that is not more deeply nested.
313 Paragraph & prev_par = *prev_it;
314 lyx::depth_type const prev_depth = getDepth(prev_it);
315 if (labeltype == prev_par.layout()->labeltype) {
316 if (prev_depth < min_depth) {
317 return prev_par.itemdepth + 1;
319 else if (prev_depth == min_depth) {
320 return prev_par.itemdepth;
323 min_depth = std::min(min_depth, prev_depth);
324 // small optimization: if we are at depth 0, we won't
325 // find anything else
326 if (prev_depth == 0) {
333 bool needEnumCounterReset(ParIterator const & it)
335 Paragraph const & par = *it;
336 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
337 lyx::depth_type const cur_depth = par.getDepth();
338 ParIterator prev_it = it;
339 while (prev_it.pit()) {
340 --prev_it.top().pit();
341 Paragraph const & prev_par = *prev_it;
342 if (prev_par.getDepth() <= cur_depth)
343 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
345 // start of nested inset: reset
350 // set the label of a paragraph. This includes the counters.
351 void setLabel(Buffer const & buf, ParIterator & it)
353 Paragraph & par = *it;
354 BufferParams const & bufparams = buf.params();
355 LyXTextClass const & textclass = bufparams.getLyXTextClass();
356 LyXLayout_ptr const & layout = par.layout();
357 Counters & counters = textclass.counters();
360 par.params().appendix(par.params().startOfAppendix());
362 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
363 if (!par.params().appendix() &&
364 par.params().startOfAppendix()) {
365 par.params().appendix(true);
366 textclass.counters().reset();
370 // Compute the item depth of the paragraph
371 par.itemdepth = getItemDepth(it);
373 // erase what was there before
374 par.params().labelString(docstring());
376 if (layout->margintype == MARGIN_MANUAL) {
377 if (par.params().labelWidthString().empty())
379 par.setLabelWidthString(lyx::from_ascii(layout->labelstring()));
381 par.setLabelWidthString(docstring());
384 // is it a layout that has an automatic label?
385 if (layout->labeltype == LABEL_COUNTER) {
386 if (layout->toclevel <= buf.params().secnumdepth
387 && (layout->latextype != LATEX_ENVIRONMENT
388 || isFirstInSequence(it.pit(), it.plist()))) {
390 counters.step(lyx::from_ascii(layout->counter));
391 docstring label = expandLabel(buf, layout,
392 par.params().appendix());
393 par.params().labelString(label);
395 } else if (layout->labeltype == LABEL_ITEMIZE) {
396 // At some point of time we should do something more
397 // clever here, like:
398 // par.params().labelString(
399 // bufparams.user_defined_bullet(par.itemdepth).getText());
400 // for now, use a simple hardcoded label
402 switch (par.itemdepth) {
404 itemlabel = lyx::char_type(0x2022);
407 itemlabel = lyx::char_type(0x2013);
410 itemlabel = lyx::char_type(0x2217);
413 itemlabel += lyx::char_type(0x2219); // or 0x00b7
417 par.params().labelString(itemlabel);
418 } else if (layout->labeltype == LABEL_ENUMERATE) {
420 // Yes I know this is a really, really! bad solution
422 docstring enumcounter = lyx::from_ascii("enum");
424 switch (par.itemdepth) {
436 // not a valid enumdepth...
440 // Maybe we have to reset the enumeration counter.
441 if (needEnumCounterReset(it))
442 counters.reset(enumcounter);
444 counters.step(enumcounter);
448 switch (par.itemdepth) {
450 format = N_("\\arabic{enumi}.");
453 format = N_("(\\alph{enumii})");
456 format = N_("\\roman{enumiii}.");
459 format = N_("\\Alph{enumiv}.");
462 // not a valid enumdepth...
466 par.params().labelString(counters.counterLabel(buf.B_(format)));
467 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
468 counters.step(lyx::from_ascii("bibitem"));
469 int number = counters.value(lyx::from_ascii("bibitem"));
471 par.bibitem()->setCounter(number);
472 par.params().labelString(buf.B_(layout->labelstring()));
473 // In biblio should't be following counters but...
474 } else if (layout->labeltype == LABEL_SENSITIVE) {
475 // Search for the first float or wrap inset in the iterator
477 size_t i = it.depth();
480 InsetBase * const in = &it[i].inset();
481 if (in->lyxCode() == InsetBase::FLOAT_CODE
482 || in->lyxCode() == InsetBase::WRAP_CODE) {
483 type = in->getInsetName();
490 Floating const & fl = textclass.floats().getType(type);
492 counters.step(lyx::from_ascii(fl.type()));
494 // Doesn't work... yet.
495 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
497 // par->SetLayout(0);
498 s = buf.B_(layout->labelstring());
501 par.params().labelString(s);
502 } else if (layout->labeltype == LABEL_NO_LABEL)
503 par.params().labelString(docstring());
505 par.params().labelString(buf.B_(layout->labelstring()));
511 bool updateCurrentLabel(Buffer const & buf,
514 if (it == par_iterator_end(buf.inset()))
517 // if (it.lastpit == 0 && LyXText::isMainText())
520 switch (it->layout()->labeltype) {
525 case LABEL_TOP_ENVIRONMENT:
526 case LABEL_CENTERED_TOP_ENVIRONMENT:
532 case LABEL_SENSITIVE:
534 // do more things with enumerate later
535 case LABEL_ENUMERATE:
539 // This is dead code which get rid of a warning:
544 void updateLabels(Buffer const & buf,
545 ParIterator & from, ParIterator & to)
547 for (ParIterator it = from; it != to; ++it) {
548 if (it.pit() > it.lastpit())
550 if (!updateCurrentLabel (buf, it)) {
558 void updateLabels(Buffer const & buf,
561 if (updateCurrentLabel(buf, iter))
568 void updateLabels(Buffer const & buf)
570 // start over the counters
571 buf.params().getLyXTextClass().counters().reset();
573 ParIterator const end = par_iterator_end(buf.inset());
575 for (ParIterator it = par_iterator_begin(buf.inset()); it != end; ++it) {
576 // reduce depth if necessary
578 Paragraph const & prevpar = it.plist()[it.pit() - 1];
579 it->params().depth(min(it->params().depth(),
580 prevpar.getMaxDepthAfter()));
582 it->params().depth(0);
584 // set the counter for this paragraph
588 lyx::toc::updateToc(buf);
592 docstring expandLabel(Buffer const & buf,
593 LyXLayout_ptr const & layout, bool appendix)
595 LyXTextClass const & tclass = buf.params().getLyXTextClass();
597 docstring fmt = buf.B_(appendix ? layout->labelstring_appendix()
598 : layout->labelstring());
600 // handle 'inherited level parts' in 'fmt',
601 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
602 size_t const i = fmt.find('@', 0);
603 if (i != docstring::npos) {
604 size_t const j = fmt.find('@', i + 1);
605 if (j != docstring::npos) {
606 docstring parent(fmt, i + 1, j - i - 1);
608 docstring label = expandLabel(buf, tclass[lyx::to_utf8(parent)], appendix);
609 fmt = docstring(fmt, 0, i) + label + docstring(fmt, j + 1, docstring::npos);
613 return tclass.counters().counterLabel(fmt);