]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
remove unused code
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
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 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
20 #include "Counters.h"
21 #include "ErrorList.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "InsetList.h"
25 #include "Language.h"
26 #include "LaTeX.h"
27 #include "Layout.h"
28 #include "LyX.h"
29 #include "TextClass.h"
30 #include "Paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "ParagraphList.h"
33 #include "ParagraphParameters.h"
34 #include "ParIterator.h"
35 #include "TexRow.h"
36 #include "Text.h"
37 #include "TocBackend.h"
38
39 #include "frontends/alert.h"
40
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetInclude.h"
43
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/filetools.h"
47 #include "support/gettext.h"
48 #include "support/lstrings.h"
49 #include "support/textutils.h"
50
51 using namespace std;
52 using namespace lyx::support;
53
54 namespace lyx {
55
56 namespace Alert = frontend::Alert;
57
58
59 Buffer * checkAndLoadLyXFile(FileName const & filename)
60 {
61         // File already open?
62         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
63         if (checkBuffer) {
64                 if (checkBuffer->isClean())
65                         return checkBuffer;
66                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
67                 docstring text = bformat(_(
68                                 "The document %1$s is already loaded and has unsaved changes.\n"
69                                 "Do you want to abandon your changes and reload the version on disk?"), file);
70                 if (Alert::prompt(_("Reload saved document?"),
71                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
72                         return checkBuffer;
73
74                 // FIXME: should be LFUN_REVERT
75                 theBufferList().release(checkBuffer);
76                 // Load it again.
77                 return checkAndLoadLyXFile(filename);
78         }
79
80         if (filename.exists()) {
81                 if (!filename.isReadableFile()) {
82                         docstring text = bformat(_("The file %1$s exists but is not "
83                                 "readable by the current user."),
84                                 from_utf8(filename.absFilename()));
85                         Alert::error(_("File not readable!"), text);
86                         return 0;
87                 }
88                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
89                 if (!b)
90                         // Buffer creation is not possible.
91                         return 0;
92                 if (!b->loadLyXFile(filename)) {
93                         theBufferList().release(b);
94                         return 0;
95                 }
96                 return b;
97         }
98
99         docstring text = bformat(_("The document %1$s does not yet "
100                 "exist.\n\nDo you want to create a new document?"),
101                 from_utf8(filename.absFilename()));
102         if (!Alert::prompt(_("Create new document?"),
103                         text, 0, 1, _("&Create"), _("Cancel")))
104                 return newFile(filename.absFilename(), string(), true);
105
106         return 0;
107 }
108
109
110 // FIXME newFile() should probably be a member method of Application...
111 Buffer * newFile(string const & filename, string const & templatename,
112                  bool const isNamed)
113 {
114         // get a free buffer
115         Buffer * b = theBufferList().newBuffer(filename);
116         if (!b)
117                 // Buffer creation is not possible.
118                 return 0;
119
120         FileName tname;
121         // use defaults.lyx as a default template if it exists.
122         if (templatename.empty())
123                 tname = libFileSearch("templates", "defaults.lyx");
124         else
125                 tname = makeAbsPath(templatename);
126
127         if (!tname.empty()) {
128                 if (!b->readFile(tname)) {
129                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
130                         docstring const text  = bformat(
131                                 _("The specified document template\n%1$s\ncould not be read."),
132                                 file);
133                         Alert::error(_("Could not read template"), text);
134                         theBufferList().release(b);
135                         return 0;
136                 }
137         }
138
139         if (!isNamed) {
140                 b->setUnnamed();
141                 b->setFileName(filename);
142         }
143
144         b->setReadonly(false);
145         b->setFullyLoaded(true);
146
147         return b;
148 }
149
150
151 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
152 {
153         static int newfile_number;
154
155         string document_path = path.absFilename();
156         string filename = addName(document_path,
157                 "newfile" + convert<string>(++newfile_number) + ".lyx");
158         while (theBufferList().exists(filename)
159                 || FileName(filename).isReadableFile()) {
160                 ++newfile_number;
161                 filename = addName(document_path,
162                         "newfile" +     convert<string>(newfile_number) + ".lyx");
163         }
164         return newFile(filename, templatename, false);
165 }
166
167
168 int countWords(DocIterator const & from, DocIterator const & to)
169 {
170         int count = 0;
171         bool inword = false;
172         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
173                 // Copied and adapted from isLetter() in ControlSpellChecker
174                 if (dit.inTexted()
175                     && dit.pos() != dit.lastpos()
176                     && dit.paragraph().isLetter(dit.pos())
177                     && !dit.paragraph().isDeleted(dit.pos())) {
178                         if (!inword) {
179                                 ++count;
180                                 inword = true;
181                         }
182                 } else if (inword)
183                         inword = false;
184         }
185
186         return count;
187 }
188
189
190 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
191 {
192         int chars = 0;
193         int blanks = 0;
194         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
195
196                 if (!dit.inTexted()) continue;
197                 Paragraph const & par = dit.paragraph();
198                 pos_type const pos = dit.pos();
199
200                 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
201                         if (Inset const * ins = par.getInset(pos)) {
202                                 if (ins->isLetter())
203                                         ++chars;
204                                 else if (with_blanks && ins->isSpace())
205                                         ++blanks;
206                         } else {
207                                 char_type const c = par.getChar(pos);
208                                 if (isPrintableNonspace(c))
209                                         ++chars;
210                                 else if (isSpace(c) && with_blanks)
211                                         ++blanks;
212                         }
213                 }
214         }
215
216         return chars + blanks;
217 }
218
219
220 namespace {
221
222 depth_type getDepth(DocIterator const & it)
223 {
224         depth_type depth = 0;
225         for (size_t i = 0 ; i < it.depth() ; ++i)
226                 if (!it[i].inset().inMathed())
227                         depth += it[i].paragraph().getDepth() + 1;
228         // remove 1 since the outer inset does not count
229         return depth - 1;
230 }
231
232 depth_type getItemDepth(ParIterator const & it)
233 {
234         Paragraph const & par = *it;
235         LabelType const labeltype = par.layout().labeltype;
236
237         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
238                 return 0;
239
240         // this will hold the lowest depth encountered up to now.
241         depth_type min_depth = getDepth(it);
242         ParIterator prev_it = it;
243         while (true) {
244                 if (prev_it.pit())
245                         --prev_it.top().pit();
246                 else {
247                         // start of nested inset: go to outer par
248                         prev_it.pop_back();
249                         if (prev_it.empty()) {
250                                 // start of document: nothing to do
251                                 return 0;
252                         }
253                 }
254
255                 // We search for the first paragraph with same label
256                 // that is not more deeply nested.
257                 Paragraph & prev_par = *prev_it;
258                 depth_type const prev_depth = getDepth(prev_it);
259                 if (labeltype == prev_par.layout().labeltype) {
260                         if (prev_depth < min_depth)
261                                 return prev_par.itemdepth + 1;
262                         if (prev_depth == min_depth)
263                                 return prev_par.itemdepth;
264                 }
265                 min_depth = min(min_depth, prev_depth);
266                 // small optimization: if we are at depth 0, we won't
267                 // find anything else
268                 if (prev_depth == 0)
269                         return 0;
270         }
271 }
272
273
274 bool needEnumCounterReset(ParIterator const & it)
275 {
276         Paragraph const & par = *it;
277         BOOST_ASSERT(par.layout().labeltype == LABEL_ENUMERATE);
278         depth_type const cur_depth = par.getDepth();
279         ParIterator prev_it = it;
280         while (prev_it.pit()) {
281                 --prev_it.top().pit();
282                 Paragraph const & prev_par = *prev_it;
283                 if (prev_par.getDepth() <= cur_depth)
284                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
285         }
286         // start of nested inset: reset
287         return true;
288 }
289
290
291 // set the label of a paragraph. This includes the counters.
292 void setLabel(Buffer const & buf, ParIterator & it)
293 {
294         DocumentClass const & textclass = buf.params().documentClass();
295         Paragraph & par = it.paragraph();
296         Layout const & layout = par.layout();
297         Counters & counters = textclass.counters();
298
299         if (par.params().startOfAppendix()) {
300                 // FIXME: only the counter corresponding to toplevel
301                 // sectionning should be reset
302                 counters.reset();
303                 counters.appendix(true);
304         }
305         par.params().appendix(counters.appendix());
306
307         // Compute the item depth of the paragraph
308         par.itemdepth = getItemDepth(it);
309
310         if (layout.margintype == MARGIN_MANUAL) {
311                 if (par.params().labelWidthString().empty())
312                         par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), buf.params()));
313         } else {
314                 par.params().labelWidthString(docstring());
315         }
316
317         switch(layout.labeltype) {
318         case LABEL_COUNTER:
319                 if (layout.toclevel <= buf.params().secnumdepth
320                     && (layout.latextype != LATEX_ENVIRONMENT
321                         || isFirstInSequence(it.pit(), it.plist()))) {
322                         counters.step(layout.counter);
323                         par.params().labelString(
324                                 par.expandLabel(layout, buf.params()));
325                 } else
326                         par.params().labelString(docstring());
327                 break;
328
329         case LABEL_ITEMIZE: {
330                 // At some point of time we should do something more
331                 // clever here, like:
332                 //   par.params().labelString(
333                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
334                 // for now, use a simple hardcoded label
335                 docstring itemlabel;
336                 switch (par.itemdepth) {
337                 case 0:
338                         itemlabel = char_type(0x2022);
339                         break;
340                 case 1:
341                         itemlabel = char_type(0x2013);
342                         break;
343                 case 2:
344                         itemlabel = char_type(0x2217);
345                         break;
346                 case 3:
347                         itemlabel = char_type(0x2219); // or 0x00b7
348                         break;
349                 }
350                 par.params().labelString(itemlabel);
351                 break;
352         }
353
354         case LABEL_ENUMERATE: {
355                 // FIXME: Yes I know this is a really, really! bad solution
356                 // (Lgb)
357                 docstring enumcounter = from_ascii("enum");
358
359                 switch (par.itemdepth) {
360                 case 2:
361                         enumcounter += 'i';
362                 case 1:
363                         enumcounter += 'i';
364                 case 0:
365                         enumcounter += 'i';
366                         break;
367                 case 3:
368                         enumcounter += "iv";
369                         break;
370                 default:
371                         // not a valid enumdepth...
372                         break;
373                 }
374
375                 // Maybe we have to reset the enumeration counter.
376                 if (needEnumCounterReset(it))
377                         counters.reset(enumcounter);
378
379                 counters.step(enumcounter);
380
381                 string format;
382
383                 switch (par.itemdepth) {
384                 case 0:
385                         format = N_("\\arabic{enumi}.");
386                         break;
387                 case 1:
388                         format = N_("(\\alph{enumii})");
389                         break;
390                 case 2:
391                         format = N_("\\roman{enumiii}.");
392                         break;
393                 case 3:
394                         format = N_("\\Alph{enumiv}.");
395                         break;
396                 default:
397                         // not a valid enumdepth...
398                         break;
399                 }
400
401                 par.params().labelString(counters.counterLabel(
402                         par.translateIfPossible(from_ascii(format), buf.params())));
403
404                 break;
405         }
406
407         case LABEL_SENSITIVE: {
408                 string const & type = counters.current_float();
409                 docstring full_label;
410                 if (type.empty())
411                         full_label = buf.B_("Senseless!!! ");
412                 else {
413                         docstring name = buf.B_(textclass.floats().getType(type).name());
414                         if (counters.hasCounter(from_utf8(type))) {
415                                 counters.step(from_utf8(type));
416                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
417                                                      name, 
418                                                      counters.theCounter(from_utf8(type)));
419                         } else
420                                 full_label = bformat(from_ascii("%1$s #:"), name);      
421                 }
422                 par.params().labelString(full_label);   
423                 break;
424         }
425
426         case LABEL_NO_LABEL:
427                 par.params().labelString(docstring());
428                 break;
429
430         case LABEL_MANUAL:
431         case LABEL_TOP_ENVIRONMENT:
432         case LABEL_CENTERED_TOP_ENVIRONMENT:
433         case LABEL_STATIC:      
434         case LABEL_BIBLIO:
435                 par.params().labelString(
436                         par.translateIfPossible(layout.labelstring(), 
437                                                 buf.params()));
438                 break;
439         }
440 }
441
442 } // anon namespace
443
444 void updateLabels(Buffer const & buf, ParIterator & parit)
445 {
446         BOOST_ASSERT(parit.pit() == 0);
447
448         // set the position of the text in the buffer to be able
449         // to resolve macros in it. This has nothing to do with
450         // labels, but by putting it here we avoid implementing
451         // a whole bunch of traversal routines just for this call.
452         parit.text()->setMacrocontextPosition(parit);
453
454         depth_type maxdepth = 0;
455         pit_type const lastpit = parit.lastpit();
456         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
457                 // reduce depth if necessary
458                 parit->params().depth(min(parit->params().depth(), maxdepth));
459                 maxdepth = parit->getMaxDepthAfter();
460
461                 // set the counter for this paragraph
462                 setLabel(buf, parit);
463
464                 // Now the insets
465                 InsetList::const_iterator iit = parit->insetList().begin();
466                 InsetList::const_iterator end = parit->insetList().end();
467                 for (; iit != end; ++iit) {
468                         parit.pos() = iit->pos;
469                         iit->inset->updateLabels(parit);
470                 }
471         }
472 }
473
474
475 // FIXME: buf should should be const because updateLabels() modifies
476 // the contents of the paragraphs.
477 void updateLabels(Buffer const & buf, bool childonly)
478 {
479         Buffer const * const master = buf.masterBuffer();
480         // Use the master text class also for child documents
481         DocumentClass const & textclass = master->params().documentClass();
482
483         if (!childonly) {
484                 // If this is a child document start with the master
485                 if (master != &buf) {
486                         updateLabels(*master);
487                         return;
488                 }
489
490                 // start over the counters
491                 textclass.counters().reset();
492                 buf.clearReferenceCache();
493                 buf.updateMacros();
494         }
495
496         Buffer & cbuf = const_cast<Buffer &>(buf);
497
498         if (buf.text().empty()) {
499                 // FIXME: we don't call continue with updateLabels()
500                 // here because it crashes on newly created documents.
501                 // But the TocBackend needs to be initialised
502                 // nonetheless so we update the tocBackend manually.
503                 cbuf.tocBackend().update();
504                 return;
505         }
506
507         // do the real work
508         ParIterator parit = par_iterator_begin(buf.inset());
509         updateLabels(buf, parit);
510
511         cbuf.tocBackend().update();
512         if (!childonly)
513                 cbuf.structureChanged();
514 }
515
516
517 } // namespace lyx