]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.C
Add fig_copy.sh and lyxpreview_tools.py to the dist.
[lyx.git] / src / buffer_funcs.C
1 /**
2  * \file buffer_funcs.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16
17 #include "buffer.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
20 #include "dociterator.h"
21 #include "counters.h"
22 #include "errorlist.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "LaTeX.h"
27 #include "lyxtextclass.h"
28 #include "paragraph.h"
29 #include "ParagraphList_fwd.h"
30 #include "ParagraphParameters.h"
31 #include "pariterator.h"
32 #include "lyxvc.h"
33 #include "texrow.h"
34 #include "vc-backend.h"
35
36 #include "frontends/Alert.h"
37
38 #include "insets/insetbibitem.h"
39
40 #include "support/filetools.h"
41 #include "support/fs_extras.h"
42 #include "support/lyxlib.h"
43
44 #include <boost/bind.hpp>
45 #include <boost/filesystem/operations.hpp>
46
47 using lyx::pit_type;
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;
54
55 using std::min;
56 using std::string;
57
58 namespace fs = boost::filesystem;
59
60 extern BufferList bufferlist;
61
62 namespace {
63
64 bool readFile(Buffer * const b, string const & s)
65 {
66         BOOST_ASSERT(b);
67
68         // File information about normal file
69         if (!fs::exists(s)) {
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);
74                 return false;
75         }
76
77         // Check if emergency save file exists and is newer.
78         string const e = OnlyPath(s) + OnlyFilename(s) + ".emergency";
79
80         if (fs::exists(e) && fs::exists(s)
81             && fs::last_write_time(e) > fs::last_write_time(s))
82         {
83                 string const file = MakeDisplayPath(s, 20);
84                 string const text =
85                         bformat(_("An emergency save of the document "
86                                   "%1$s exists.\n\n"
87                                   "Recover emergency save?"), file);
88                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
89                                       _("&Recover"),  _("&Load Original"),
90                                       _("&Cancel")))
91                 {
92                 case 0:
93                         // the file is not saved if we load the emergency file.
94                         b->markDirty();
95                         return b->readFile(e);
96                 case 1:
97                         break;
98                 default:
99                         return false;
100                 }
101         }
102
103         // Now check if autosave file is newer.
104         string const a = OnlyPath(s) + '#' + OnlyFilename(s) + '#';
105
106         if (fs::exists(a) && fs::exists(s)
107             && fs::last_write_time(a) > fs::last_write_time(s))
108         {
109                 string const file = MakeDisplayPath(s, 20);
110                 string const text =
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"),
116                                       _("&Cancel") ))
117                 {
118                 case 0:
119                         // the file is not saved if we load the autosave file.
120                         b->markDirty();
121                         return b->readFile(a);
122                 case 1:
123                         // Here we delete the autosave
124                         unlink(a);
125                         break;
126                 default:
127                         return false;
128                 }
129         }
130         return b->readFile(s);
131 }
132
133
134 } // namespace anon
135
136
137
138 bool loadLyXFile(Buffer * b, string const & s)
139 {
140         BOOST_ASSERT(b);
141
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);
147                         return true;
148                 }
149         } else {
150                 string const file = MakeDisplayPath(s, 20);
151                 // Here we probably should run
152                 if (LyXVC::file_not_found_hook(s)) {
153                         string const text =
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"));
158
159                         if (ret == 0) {
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.
163                                 RCS::retrieve(s);
164                                 return loadLyXFile(b, s);
165                         }
166                 }
167         }
168         return false;
169 }
170
171
172 Buffer * newFile(string const & filename, string const & templatename,
173                  bool const isNamed)
174 {
175         // get a free buffer
176         Buffer * b = bufferlist.newBuffer(filename);
177         BOOST_ASSERT(b);
178
179         string tname;
180         // use defaults.lyx as a default template if it exists.
181         if (templatename.empty())
182                 tname = LibFileSearch("templates", "defaults.lyx");
183         else
184                 tname = templatename;
185
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
192                 }
193         }
194
195         if (!isNamed) {
196                 b->setUnnamed();
197                 b->setFileName(filename);
198         }
199
200         b->setReadonly(false);
201         b->fully_loaded(true);
202         b->updateDocLang(b->params().language);
203
204         return b;
205 }
206
207
208 void bufferErrors(Buffer const & buf, TeXErrors const & terr)
209 {
210         TeXErrors::Errors::const_iterator cit = terr.begin();
211         TeXErrors::Errors::const_iterator end = terr.end();
212
213         for (; cit != end; ++cit) {
214                 int par_id = -1;
215                 int posstart = -1;
216                 int const errorrow = cit->error_in_line;
217                 buf.texrow().getIdFromRow(errorrow, par_id, posstart);
218                 int posend = -1;
219                 buf.texrow().getIdFromRow(errorrow + 1, par_id, posend);
220                 buf.error(ErrorItem(cit->error_desc,
221                                          cit->error_text,
222                                          par_id, posstart, posend));
223         }
224 }
225
226
227 void bufferErrors(Buffer const & buf, ErrorList const & el)
228 {
229         for_each(el.begin(), el.end(), bind(ref(buf.error), _1));
230 }
231
232
233 string const BufferFormat(Buffer const & buffer)
234 {
235         if (buffer.isLinuxDoc())
236                 return "linuxdoc";
237         else if (buffer.isDocBook())
238                 return "docbook";
239         else if (buffer.isLiterate())
240                 return "literate";
241         else
242                 return "latex";
243 }
244
245
246 int countWords(DocIterator const & from, DocIterator const & to)
247 {
248         int count = 0;
249         bool inword = false;
250         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
251                 // Copied and adapted from isLetter() in ControlSpellChecker
252                 if (dit.inTexted()
253                     && dit.pos() != dit.lastpos()
254                     && dit.paragraph().isLetter(dit.pos())
255                     && !isDeletedText(dit.paragraph(), dit.pos())) {
256                         if (!inword) {
257                                 ++count;
258                                 inword = true;
259                         }
260                 } else if (inword)
261                         inword = false;
262         }
263
264         return count;
265 }
266
267
268 namespace {
269
270 void incrementItemDepth(ParagraphList & pars, pit_type pit, pit_type first_pit)
271 {
272         int const cur_labeltype = pars[pit].layout()->labeltype;
273
274         if (cur_labeltype != LABEL_ENUMERATE && cur_labeltype != LABEL_ITEMIZE)
275                 return;
276
277         int const cur_depth = pars[pit].getDepth();
278
279         pit_type prev_pit = pit - 1;
280         while (true) {
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;
286                         }
287                         break;
288                 } else if (prev_depth < cur_depth) {
289                         if (prev_labeltype == cur_labeltype) {
290                                 pars[pit].itemdepth = pars[prev_pit].itemdepth + 1;
291                                 break;
292                         }
293                 } else if (prev_depth == cur_depth) {
294                         if (prev_labeltype == cur_labeltype) {
295                                 pars[pit].itemdepth = pars[prev_pit].itemdepth;
296                                 break;
297                         }
298                 }
299                 if (prev_pit == first_pit)
300                         break;
301
302                 --prev_pit;
303         }
304 }
305
306
307 void resetEnumCounterIfNeeded(ParagraphList & pars, pit_type pit,
308         pit_type firstpit, Counters & counters)
309 {
310         if (pit == firstpit)
311                 return;
312
313         int const cur_depth = pars[pit].getDepth();
314         pit_type prev_pit = pit - 1;
315         while (true) {
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) {
321                                 case 0:
322                                         counters.reset("enumi");
323                                 case 1:
324                                         counters.reset("enumii");
325                                 case 2:
326                                         counters.reset("enumiii");
327                                 case 3:
328                                         counters.reset("enumiv");
329                                 }
330                         }
331                         break;
332                 }
333
334                 if (prev_pit == firstpit)
335                         break;
336
337                 --prev_pit;
338         }
339 }
340
341
342 // set the counter of a paragraph. This includes the labels
343 void setCounter(Buffer const & buf, ParIterator & it)
344 {
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();
350
351         // Always reset
352         par.itemdepth = 0;
353
354         if (it.pit() == 0) {
355                 par.params().appendix(par.params().startOfAppendix());
356         } else {
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();
362                 }
363
364                 // Maybe we have to increment the item depth.
365                 incrementItemDepth(it.plist(), it.pit(), 0);
366         }
367
368         // erase what was there before
369         par.params().labelString(string());
370
371         if (layout->margintype == MARGIN_MANUAL) {
372                 if (par.params().labelWidthString().empty())
373                         par.setLabelWidthString(layout->labelstring());
374         } else {
375                 par.setLabelWidthString(string());
376         }
377
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
389                 string itemlabel;
390                 switch (par.itemdepth) {
391                 case 0:
392                         itemlabel = "*";
393                         break;
394                 case 1:
395                         itemlabel = "-";
396                         break;
397                 case 2:
398                         itemlabel = "@";
399                         break;
400                 case 3:
401                         itemlabel = "·";
402                         break;
403                 }
404
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);
409
410                 // FIXME
411                 // Yes I know this is a really, really! bad solution
412                 // (Lgb)
413                 string enumcounter = "enum";
414
415                 switch (par.itemdepth) {
416                 case 2:
417                         enumcounter += 'i';
418                 case 1:
419                         enumcounter += 'i';
420                 case 0:
421                         enumcounter += 'i';
422                         break;
423                 case 3:
424                         enumcounter += "iv";
425                         break;
426                 default:
427                         // not a valid enumdepth...
428                         break;
429                 }
430
431                 counters.step(enumcounter);
432
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");
437                 if (par.bibitem()) {
438                         par.bibitem()->setCounter(number);
439                         par.params().labelString(layout->labelstring());
440                 }
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
444                 string type;
445                 size_t i = it.depth();
446                 while (i > 0) {
447                         --i;
448                         InsetBase * const in = &it[i].inset();
449                         if (in->lyxCode() == InsetBase::FLOAT_CODE
450                             || in->lyxCode() == InsetBase::WRAP_CODE) 
451                                 type = in->getInsetName();
452                                 break;
453                 }
454
455                 string s;
456                 if (!type.empty()) {
457                         Floating const & fl = textclass.floats().getType(type);
458
459                         counters.step(fl.type());
460
461                         // Doesn't work... yet.
462                         s = bformat(_("%1$s #:"), buf.B_(fl.name()));
463                 } else {
464                         // par->SetLayout(0);
465                         s = buf.B_(layout->labelstring());
466                 }
467
468                 par.params().labelString(s);
469         } else
470                 par.params().labelString(buf.B_(layout->labelstring()));
471 }
472
473 } // anon namespace
474
475
476 void updateCounters(Buffer const & buf)
477 {
478         // start over
479         buf.params().getLyXTextClass().counters().reset();
480
481         for (ParIterator it = par_iterator_begin(buf.inset()); it; ++it) {
482                 // reduce depth if necessary
483                 if (it.pit()) {
484                         Paragraph const & prevpar = it.plist()[it.pit() - 1];
485                         it->params().depth(min(it->params().depth(),
486                                                prevpar.getMaxDepthAfter()));
487                 } else
488                         it->params().depth(0);
489
490                 // set the counter for this paragraph
491                 setCounter(buf, it);
492         }
493 }
494
495
496 string expandLabel(LyXTextClass const & textclass,
497         LyXLayout_ptr const & layout, bool appendix)
498 {
499         string fmt = appendix ?
500                 layout->labelstring_appendix() : layout->labelstring();
501
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);
511                 }
512         }
513
514         return textclass.counters().counterLabel(fmt);
515 }
516
517