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"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
20 #include "dociterator.h"
22 #include "errorlist.h"
24 #include "FloatList.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "ParagraphList_fwd.h"
30 #include "ParagraphParameters.h"
31 #include "pariterator.h"
34 #include "vc-backend.h"
36 #include "frontends/Alert.h"
38 #include "insets/insetbibitem.h"
40 #include "support/filetools.h"
41 #include "support/fs_extras.h"
42 #include "support/lyxlib.h"
44 #include <boost/bind.hpp>
45 #include <boost/filesystem/operations.hpp>
48 using lyx::support::bformat;
49 using lyx::support::LibFileSearch;
50 using lyx::support::MakeDisplayPath;
51 using lyx::support::OnlyFilename;
52 using lyx::support::OnlyPath;
53 using lyx::support::unlink;
58 namespace fs = boost::filesystem;
60 extern BufferList bufferlist;
64 bool readFile(Buffer * const b, string const & s)
68 // File information about normal file
70 string const file = MakeDisplayPath(s, 50);
71 string text = bformat(_("The specified document\n%1$s"
72 "\ncould not be read."), file);
73 Alert::error(_("Could not read document"), text);
77 // Check if emergency save file exists and is newer.
78 string const e = OnlyPath(s) + OnlyFilename(s) + ".emergency";
80 if (fs::exists(e) && fs::exists(s)
81 && fs::last_write_time(e) > fs::last_write_time(s))
83 string const file = MakeDisplayPath(s, 20);
85 bformat(_("An emergency save of the document "
87 "Recover emergency save?"), file);
88 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
89 _("&Recover"), _("&Load Original"),
93 // the file is not saved if we load the emergency file.
95 return b->readFile(e);
103 // Now check if autosave file is newer.
104 string const a = OnlyPath(s) + '#' + OnlyFilename(s) + '#';
106 if (fs::exists(a) && fs::exists(s)
107 && fs::last_write_time(a) > fs::last_write_time(s))
109 string const file = MakeDisplayPath(s, 20);
111 bformat(_("The backup of the document "
112 "%1$s is newer.\n\nLoad the "
113 "backup instead?"), file);
114 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
115 _("&Load backup"), _("Load &original"),
119 // the file is not saved if we load the autosave file.
121 return b->readFile(a);
123 // Here we delete the autosave
130 return b->readFile(s);
138 bool loadLyXFile(Buffer * b, string const & s)
142 if (fs::is_readable(s)) {
143 if (readFile(b, s)) {
144 b->lyxvc().file_found_hook(s);
145 if (!fs::is_writable(s))
146 b->setReadonly(true);
150 string const file = MakeDisplayPath(s, 20);
151 // Here we probably should run
152 if (LyXVC::file_not_found_hook(s)) {
154 bformat(_("Do you want to retrieve the document"
155 " %1$s from version control?"), file);
156 int const ret = Alert::prompt(_("Retrieve from version control?"),
157 text, 0, 1, _("&Retrieve"), _("&Cancel"));
160 // How can we know _how_ to do the checkout?
161 // With the current VC support it has to be,
162 // a RCS file since CVS do not have special ,v files.
164 return loadLyXFile(b, s);
172 Buffer * newFile(string const & filename, string const & templatename,
176 Buffer * b = bufferlist.newBuffer(filename);
180 // use defaults.lyx as a default template if it exists.
181 if (templatename.empty())
182 tname = LibFileSearch("templates", "defaults.lyx");
184 tname = templatename;
186 if (!tname.empty()) {
187 if (!b->readFile(tname)) {
188 string const file = MakeDisplayPath(tname, 50);
189 string const text = bformat(_("The specified document template\n%1$s\ncould not be read."), file);
190 Alert::error(_("Could not read template"), text);
191 // no template, start with empty buffer
197 b->setFileName(filename);
200 b->setReadonly(false);
201 b->fully_loaded(true);
202 b->updateDocLang(b->params().language);
208 void bufferErrors(Buffer const & buf, TeXErrors const & terr)
210 TeXErrors::Errors::const_iterator cit = terr.begin();
211 TeXErrors::Errors::const_iterator end = terr.end();
213 for (; cit != end; ++cit) {
216 int const errorrow = cit->error_in_line;
217 buf.texrow().getIdFromRow(errorrow, par_id, posstart);
219 buf.texrow().getIdFromRow(errorrow + 1, par_id, posend);
220 buf.error(ErrorItem(cit->error_desc,
222 par_id, posstart, posend));
227 void bufferErrors(Buffer const & buf, ErrorList const & el)
229 for_each(el.begin(), el.end(), bind(ref(buf.error), _1));
233 string const BufferFormat(Buffer const & buffer)
235 if (buffer.isLinuxDoc())
237 else if (buffer.isDocBook())
239 else if (buffer.isLiterate())
246 int countWords(DocIterator const & from, DocIterator const & to)
250 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
251 // Copied and adapted from isLetter() in ControlSpellChecker
253 && dit.pos() != dit.lastpos()
254 && dit.paragraph().isLetter(dit.pos())
255 && !isDeletedText(dit.paragraph(), dit.pos())) {
270 void incrementItemDepth(ParagraphList & pars, pit_type pit, pit_type first_pit)
272 int const cur_labeltype = pars[pit].layout()->labeltype;
274 if (cur_labeltype != LABEL_ENUMERATE && cur_labeltype != LABEL_ITEMIZE)
277 int const cur_depth = pars[pit].getDepth();
279 pit_type prev_pit = pit - 1;
281 int const prev_depth = pars[prev_pit].getDepth();
282 int const prev_labeltype = pars[prev_pit].layout()->labeltype;
283 if (prev_depth == 0 && cur_depth > 0) {
284 if (prev_labeltype == cur_labeltype) {
285 pars[pit].itemdepth = pars[prev_pit].itemdepth + 1;
288 } else if (prev_depth < cur_depth) {
289 if (prev_labeltype == cur_labeltype) {
290 pars[pit].itemdepth = pars[prev_pit].itemdepth + 1;
293 } else if (prev_depth == cur_depth) {
294 if (prev_labeltype == cur_labeltype) {
295 pars[pit].itemdepth = pars[prev_pit].itemdepth;
299 if (prev_pit == first_pit)
307 void resetEnumCounterIfNeeded(ParagraphList & pars, pit_type pit,
308 pit_type firstpit, Counters & counters)
313 int const cur_depth = pars[pit].getDepth();
314 pit_type prev_pit = pit - 1;
316 int const prev_depth = pars[prev_pit].getDepth();
317 int const prev_labeltype = pars[prev_pit].layout()->labeltype;
318 if (prev_depth <= cur_depth) {
319 if (prev_labeltype != LABEL_ENUMERATE) {
320 switch (pars[pit].itemdepth) {
322 counters.reset("enumi");
324 counters.reset("enumii");
326 counters.reset("enumiii");
328 counters.reset("enumiv");
334 if (prev_pit == firstpit)
342 // set the counter of a paragraph. This includes the labels
343 void setCounter(Buffer const & buf, ParIterator & it)
345 Paragraph & par = *it;
346 BufferParams const & bufparams = buf.params();
347 LyXTextClass const & textclass = bufparams.getLyXTextClass();
348 LyXLayout_ptr const & layout = par.layout();
349 Counters & counters = textclass.counters();
355 par.params().appendix(par.params().startOfAppendix());
357 par.params().appendix(it.plist()[it.pit() - 1].params().appendix());
358 if (!par.params().appendix() &&
359 par.params().startOfAppendix()) {
360 par.params().appendix(true);
361 textclass.counters().reset();
364 // Maybe we have to increment the item depth.
365 incrementItemDepth(it.plist(), it.pit(), 0);
368 // erase what was there before
369 par.params().labelString(string());
371 if (layout->margintype == MARGIN_MANUAL) {
372 if (par.params().labelWidthString().empty())
373 par.setLabelWidthString(layout->labelstring());
375 par.setLabelWidthString(string());
378 // is it a layout that has an automatic label?
379 if (layout->labeltype == LABEL_COUNTER) {
380 counters.step(layout->counter);
381 string label = expandLabel(textclass, layout, par.params().appendix());
382 par.params().labelString(label);
383 } else if (layout->labeltype == LABEL_ITEMIZE) {
384 // At some point of time we should do something more
385 // clever here, like:
386 // par.params().labelString(
387 // bufparams.user_defined_bullet(par.itemdepth).getText());
388 // for now, use a simple hardcoded label
390 switch (par.itemdepth) {
405 par.params().labelString(itemlabel);
406 } else if (layout->labeltype == LABEL_ENUMERATE) {
407 // Maybe we have to reset the enumeration counter.
408 resetEnumCounterIfNeeded(it.plist(), it.pit(), 0, counters);
411 // Yes I know this is a really, really! bad solution
413 string enumcounter = "enum";
415 switch (par.itemdepth) {
427 // not a valid enumdepth...
431 counters.step(enumcounter);
433 par.params().labelString(counters.enumLabel(enumcounter));
434 } else if (layout->labeltype == LABEL_BIBLIO) {// ale970302
435 counters.step("bibitem");
436 int number = counters.value("bibitem");
438 par.bibitem()->setCounter(number);
439 par.params().labelString(layout->labelstring());
441 // In biblio should't be following counters but...
442 } else if (layout->labeltype == LABEL_SENSITIVE) {
443 // Search for the first float or wrap inset in the iterator
445 size_t i = it.depth();
448 InsetBase * const in = &it[i].inset();
449 if (in->lyxCode() == InsetBase::FLOAT_CODE
450 || in->lyxCode() == InsetBase::WRAP_CODE)
451 type = in->getInsetName();
457 Floating const & fl = textclass.floats().getType(type);
459 counters.step(fl.type());
461 // Doesn't work... yet.
462 s = bformat(_("%1$s #:"), buf.B_(fl.name()));
464 // par->SetLayout(0);
465 s = buf.B_(layout->labelstring());
468 par.params().labelString(s);
470 par.params().labelString(buf.B_(layout->labelstring()));
476 void updateCounters(Buffer const & buf)
479 buf.params().getLyXTextClass().counters().reset();
481 for (ParIterator it = par_iterator_begin(buf.inset()); it; ++it) {
482 // reduce depth if necessary
484 Paragraph const & prevpar = it.plist()[it.pit() - 1];
485 it->params().depth(min(it->params().depth(),
486 prevpar.getMaxDepthAfter()));
488 it->params().depth(0);
490 // set the counter for this paragraph
496 string expandLabel(LyXTextClass const & textclass,
497 LyXLayout_ptr const & layout, bool appendix)
499 string fmt = appendix ?
500 layout->labelstring_appendix() : layout->labelstring();
502 // handle 'inherited level parts' in 'fmt',
503 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
504 size_t const i = fmt.find('@', 0);
505 if (i != string::npos) {
506 size_t const j = fmt.find('@', i + 1);
507 if (j != string::npos) {
508 string parent(fmt, i + 1, j - i - 1);
509 string label = expandLabel(textclass, textclass[parent], appendix);
510 fmt = string(fmt, 0, i) + label + string(fmt, j + 1, string::npos);
514 return textclass.counters().counterLabel(fmt);