]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Strip old tabular code. More Alert fixes
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "bufferlist.h"
15 #include "LyXAction.h"
16 #include "lyxrc.h"
17 #include "lyxlex.h"
18 #include "tex-strings.h"
19 #include "layout.h"
20 #include "bufferview_funcs.h"
21 #include "lyxfont.h"
22 #include "version.h"
23 #include "LaTeX.h"
24 #include "Chktex.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "lyxtext.h"
28 #include "gettext.h"
29 #include "language.h"
30 #include "exporter.h"
31 #include "Lsstream.h"
32 #include "format.h"
33 #include "BufferView.h"
34 #include "ParagraphParameters.h"
35 #include "iterators.h"
36 #include "lyxtextclasslist.h"
37 #include "sgml.h"
38 #include "paragraph_funcs.h"
39 #include "author.h"
40
41 #include "frontends/LyXView.h"
42
43 #include "mathed/formulamacro.h"
44 #include "mathed/formula.h"
45
46 #include "insets/inseterror.h"
47 #include "insets/insetbibitem.h"
48 #include "insets/insetbibtex.h"
49 #include "insets/insetinclude.h"
50 #include "insets/insettext.h"
51
52 #include "frontends/Dialogs.h"
53 #include "frontends/Alert.h"
54
55 #include "graphics/Previews.h"
56
57 #include "support/textutils.h"
58 #include "support/filetools.h"
59 #include "support/path.h"
60 #include "support/os.h"
61 #include "support/lyxlib.h"
62 #include "support/FileInfo.h"
63 #include "support/lyxmanip.h"
64 #include "support/lyxtime.h"
65
66 #include <boost/bind.hpp>
67 #include <boost/tuple/tuple.hpp>
68 #include "BoostFormat.h"
69
70 #include <fstream>
71 #include <iomanip>
72 #include <map>
73 #include <stack>
74 #include <list>
75 #include <algorithm>
76
77 #include <cstdlib>
78 #include <cmath>
79 #include <unistd.h>
80 #include <sys/types.h>
81 #include <utime.h>
82
83 #ifdef HAVE_LOCALE
84 #include <locale>
85 #endif
86
87 #ifndef CXX_GLOBAL_CSTD
88 using std::pow;
89 #endif
90
91 using std::ostream;
92 using std::ofstream;
93 using std::ifstream;
94 using std::fstream;
95 using std::ios;
96 using std::setw;
97 using std::endl;
98 using std::pair;
99 using std::make_pair;
100 using std::vector;
101 using std::map;
102 using std::stack;
103 using std::list;
104 using std::for_each;
105
106 using lyx::pos_type;
107 using lyx::textclass_type;
108
109 // all these externs should eventually be removed.
110 extern BufferList bufferlist;
111
112 namespace {
113
114 const int LYX_FORMAT = 223;
115
116 } // namespace anon
117
118 Buffer::Buffer(string const & file, bool ronly)
119         : niceFile(true), lyx_clean(true), bak_clean(true),
120           unnamed(false), read_only(ronly),
121           filename_(file), users(0)
122 {
123         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
124         filepath_ = OnlyPath(file);
125         lyxvc.buffer(this);
126         if (read_only || lyxrc.use_tempdir) {
127                 tmppath = CreateBufferTmpDir();
128         } else {
129                 tmppath.erase();
130         }
131
132         // set initial author
133         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
134 }
135
136
137 Buffer::~Buffer()
138 {
139         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
140         // here the buffer should take care that it is
141         // saved properly, before it goes into the void.
142
143         // make sure that views using this buffer
144         // forgets it.
145         if (users)
146                 users->buffer(0);
147
148         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
149 #if USE_BOOST_FORMAT
150                 boost::format fmt = _("Could not remove the temporary directory %1$s");
151                 fmt % tmppath;
152                 string msg = fmt.str();
153 #else
154                 string msg = _("Could not remove the temporary directory ") + tmppath;
155 #endif
156                 Alert::warning(_("Could not remove temporary directory"), msg);
157         }
158
159         paragraphs.clear();
160
161         // Remove any previewed LaTeX snippets assocoated with this buffer.
162         grfx::Previews::get().removeLoader(this);
163 }
164
165
166 string const Buffer::getLatexName(bool no_path) const
167 {
168         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
169         if (no_path)
170                 return OnlyFilename(name);
171         else
172                 return name;
173 }
174
175
176 pair<Buffer::LogType, string> const Buffer::getLogName() const
177 {
178         string const filename = getLatexName(false);
179
180         if (filename.empty())
181                 return make_pair(Buffer::latexlog, string());
182
183         string path = OnlyPath(filename);
184
185         if (lyxrc.use_tempdir || !IsDirWriteable(path))
186                 path = tmppath;
187
188         string const fname = AddName(path,
189                                      OnlyFilename(ChangeExtension(filename,
190                                                                   ".log")));
191         string const bname =
192                 AddName(path, OnlyFilename(
193                         ChangeExtension(filename,
194                                         formats.extension("literate") + ".out")));
195
196         // If no Latex log or Build log is newer, show Build log
197
198         FileInfo const f_fi(fname);
199         FileInfo const b_fi(bname);
200
201         if (b_fi.exist() &&
202             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
203                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
204                 return make_pair(Buffer::buildlog, bname);
205         }
206         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
207         return make_pair(Buffer::latexlog, fname);
208 }
209
210
211 void Buffer::setReadonly(bool flag)
212 {
213         if (read_only != flag) {
214                 read_only = flag;
215                 updateTitles();
216                 users->owner()->getDialogs().updateBufferDependent(false);
217         }
218 }
219
220
221 AuthorList & Buffer::authors()
222 {
223         return params.authorlist;
224 }
225
226
227 /// Update window titles of all users
228 // Should work on a list
229 void Buffer::updateTitles() const
230 {
231         if (users)
232                 users->owner()->updateWindowTitle();
233 }
234
235
236 /// Reset autosave timer of all users
237 // Should work on a list
238 void Buffer::resetAutosaveTimers() const
239 {
240         if (users)
241                 users->owner()->resetAutosaveTimer();
242 }
243
244
245 void Buffer::setFileName(string const & newfile)
246 {
247         filename_ = MakeAbsPath(newfile);
248         filepath_ = OnlyPath(filename_);
249         setReadonly(IsFileWriteable(filename_) == 0);
250         updateTitles();
251 }
252
253
254 // We'll remove this later. (Lgb)
255 namespace {
256
257 void unknownClass(string const & unknown)
258 {
259         string msg =
260 #if USE_BOOST_FORMAT
261                 boost::io::str(boost::format(
262                         _("Using the default document class, because the "
263                         " class %1$s is unknown.")) % unknown);
264 #else
265                 _("Using the default document class, because the "
266                 " class ") + unknown + (" is unknown."); 
267 #endif
268         Alert::warning(_("Unknown document class"), msg);
269 }
270
271 } // anon
272
273 int Buffer::readHeader(LyXLex & lex)
274 {
275         int unknown_tokens = 0;
276
277         while (lex.isOK()) {
278                 lex.nextToken();
279                 string const token = lex.getString();
280
281                 if (token.empty())
282                         continue;
283
284                 if (token == "\\end_header")
285                         break;
286
287                 lyxerr[Debug::PARSER] << "Handling header token: `"
288                                       << token << '\'' << endl;
289
290                 string unknown = params.readToken(lex, token);
291                 if (!unknown.empty()) {
292                         if (unknown[0] != '\\') {
293                                 unknownClass(unknown);
294                         } else {
295                                 ++unknown_tokens;
296                         }
297                 }
298         }
299         return unknown_tokens;
300 }
301
302
303 // candidate for move to BufferView
304 // (at least some parts in the beginning of the func)
305 //
306 // Uwe C. Schroeder
307 // changed to be public and have one parameter
308 // if par = 0 normal behavior
309 // else insert behavior
310 // Returns false if "\the_end" is not read (Asger)
311 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
312 {
313         int unknown_tokens = 0;
314
315         Paragraph::depth_type depth = 0;
316         bool the_end_read = false;
317
318         if (paragraphs.empty()) {
319                 unknown_tokens += readHeader(lex);
320
321                 if (!params.getLyXTextClass().load()) {
322                         string theclass = params.getLyXTextClass().name();
323                         string msg =
324 #if USE_BOOST_FORMAT
325                                 boost::io::str(boost::format(
326                                         _("Using the default document class, because the "
327                                         " class %1$s could not be loaded.")) % theclass);
328 #else
329                                 _("Using the default document class, because the "
330                                 " class ") + theclass + (" could not be loaded.");
331 #endif
332                         Alert::error(_("Can't load document class"), msg);
333                         params.textclass = 0;
334                 }
335         } else {
336                 // We are inserting into an existing document
337                 users->text->breakParagraph(paragraphs);
338
339                 // We don't want to adopt the parameters from the
340                 // document we insert, so read them into a temporary buffer
341                 // and then discard it
342
343                 Buffer tmpbuf("", false);
344                 tmpbuf.readHeader(lex);
345         }
346
347         while (lex.isOK()) {
348                 lex.nextToken();
349                 string const token = lex.getString();
350
351                 if (token.empty())
352                         continue;
353
354                 lyxerr[Debug::PARSER] << "Handling token: `"
355                                       << token << '\'' << endl;
356
357                 if (token == "\\the_end") {
358                         the_end_read = true;
359                         continue;
360                 }
361
362                 unknown_tokens += readParagraph(lex, token, paragraphs, pit, depth);
363         }
364
365
366         if (unknown_tokens > 0) {
367 #if USE_BOOST_FORMAT
368                 string s;
369                 if (unknown_tokens == 1) {
370                         boost::format fmt(_("Encountered one unknown token when reading the document %1$s."));
371                         fmt % fileName();
372                         s = fmt.str();
373                 } else {
374                         boost::format fmt(_("Encountered %1$s unknown tokens when reading the document %2$s."));
375                         fmt % tostr(unknown_tokens);
376                         fmt % fileName();
377                         s = fmt.str();
378                 }
379 #else
380                 string s = _("Encountered ");
381                 if (unknown_tokens == 1) {
382                         s += _("one unknown token");
383                 } else {
384                         s += tostr(unknown_tokens);
385                         s += _(" unknown tokens");
386                 }
387                 Alert::warning(_("Document format failure"), s);
388 #endif
389         }
390
391         return the_end_read;
392 }
393
394
395 int
396 Buffer::readParagraph(LyXLex & lex, string const & token,
397                       ParagraphList & pars, ParagraphList::iterator & pit,
398                       Paragraph::depth_type & depth)
399 {
400         static Change current_change;
401         int unknown = 0;
402
403         if (token == "\\layout") {
404                 lex.pushToken(token);
405
406                 Paragraph * par = new Paragraph();
407                 par->params().depth(depth);
408                 if (params.tracking_changes)
409                         par->trackChanges();
410                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
411                 par->setFont(0, f);
412
413                 // FIXME: goddamn InsetTabular makes us pass a Buffer
414                 // not BufferParams
415                 unknown += ::readParagraph(*this, *par, lex);
416
417                 // insert after
418                 if (pit != pars.end())
419                         ++pit;
420                 pit = pars.insert(pit, par);
421         } else if (token == "\\begin_deeper") {
422                 ++depth;
423         } else if (token == "\\end_deeper") {
424                 if (!depth) {
425                         lex.printError("\\end_deeper: " "depth is already null");
426                 } else {
427                         --depth;
428                 }
429         } else {
430                 ++unknown;
431         }
432         return unknown;
433 }
434
435
436 // needed to insert the selection
437 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
438                                  LyXFont const & fn,string const & str)
439 {
440         LyXLayout_ptr const & layout = par->layout();
441
442         LyXFont font = fn;
443
444         par->checkInsertChar(font);
445         // insert the string, don't insert doublespace
446         bool space_inserted = true;
447         bool autobreakrows = !par->inInset() ||
448                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
449         for(string::const_iterator cit = str.begin();
450             cit != str.end(); ++cit) {
451                 if (*cit == '\n') {
452                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
453                                 breakParagraph(params, paragraphs, par, pos,
454                                                layout->isEnvironment());
455                                 par = par->next();
456                                 pos = 0;
457                                 space_inserted = true;
458                         } else {
459                                 continue;
460                         }
461                         // do not insert consecutive spaces if !free_spacing
462                 } else if ((*cit == ' ' || *cit == '\t') &&
463                            space_inserted && !layout->free_spacing &&
464                                    !par->isFreeSpacing())
465                 {
466                         continue;
467                 } else if (*cit == '\t') {
468                         if (!layout->free_spacing && !par->isFreeSpacing()) {
469                                 // tabs are like spaces here
470                                 par->insertChar(pos, ' ', font);
471                                 ++pos;
472                                 space_inserted = true;
473                         } else {
474                                 const pos_type nb = 8 - pos % 8;
475                                 for (pos_type a = 0; a < nb ; ++a) {
476                                         par->insertChar(pos, ' ', font);
477                                         ++pos;
478                                 }
479                                 space_inserted = true;
480                         }
481                 } else if (!IsPrintable(*cit)) {
482                         // Ignore unprintables
483                         continue;
484                 } else {
485                         // just insert the character
486                         par->insertChar(pos, *cit, font);
487                         ++pos;
488                         space_inserted = (*cit == ' ');
489                 }
490
491         }
492 }
493
494
495 bool Buffer::readFile(LyXLex & lex, string const & filename)
496 {
497         return readFile(lex, filename, paragraphs.begin());
498 }
499
500
501 // FIXME: all the below Alerts should give the filename..
502 bool Buffer::readFile(LyXLex & lex, string const & filename, ParagraphList::iterator pit)
503 {
504         if (lex.isOK()) {
505                 lex.next();
506                 string const token(lex.getString());
507                 if (token == "\\lyxformat") { // the first token _must_ be...
508                         lex.eatLine();
509                         string tmp_format = lex.getString();
510                         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
511                         // if present remove ".," from string.
512                         string::size_type dot = tmp_format.find_first_of(".,");
513                         //lyxerr << "           dot found at " << dot << endl;
514                         if (dot != string::npos)
515                                 tmp_format.erase(dot, 1);
516                         file_format = strToInt(tmp_format);
517                         //lyxerr << "format: " << file_format << endl;
518                         if (file_format == LYX_FORMAT) {
519                                 // current format
520                         } else if (file_format > LYX_FORMAT) {
521                                 Alert::warning(_("Document format failure"),
522                                         _("This document was created with a newer version of "
523                                         "LyX. This is likely to cause problems."));
524                         } else if (file_format < LYX_FORMAT) {
525                                 // old formats
526                                 if (file_format < 200) {
527                                         Alert::error(_("Document format failure"),
528                                                 _("This LyX document is too old to be read "
529                                                 "by this version of LyX. Try LyX 0.10."));
530                                         return false;
531                                 } else if (!filename.empty()) {
532                                         string command =
533                                                 LibFileSearch("lyx2lyx", "lyx2lyx");
534                                         if (command.empty()) {
535                                                 Alert::error(_("Conversion script not found"),
536                                                         _("The document is from an earlier version "
537                                                           "of LyX, but the conversion script lyx2lyx "
538                                                           "could not be found."));
539                                                 return false;
540                                         }
541                                         command += " -t"
542                                                 +tostr(LYX_FORMAT) + ' '
543                                                 + QuoteName(filename);
544                                         lyxerr[Debug::INFO] << "Running '"
545                                                             << command << '\''
546                                                             << endl;
547                                         cmd_ret const ret = RunCommand(command);
548                                         if (ret.first) {
549                                                 Alert::error(_("Conversion script failed"),
550                                                         _("The document is from an earlier version "
551                                                           "of LyX, but the lyx2lyx script failed "
552                                                           "to convert it."));
553                                                 return false;
554                                         }
555                                         istringstream is(STRCONV(ret.second));
556                                         LyXLex tmplex(0, 0);
557                                         tmplex.setStream(is);
558                                         return readFile(tmplex, string(), pit);
559                                 } else {
560                                         // This code is reached if lyx2lyx failed (for
561                                         // some reason) to change the file format of
562                                         // the file.
563                                         lyx::Assert(false);
564                                         return false;
565                                 }
566                         }
567                         bool the_end = readBody(lex, pit);
568                         params.setPaperStuff();
569
570                         if (!the_end) {
571                                 Alert::error(_("Document format failure"),
572                                         _("The document ended unexpectedly, which means "
573                                           "that it is probably corrupted."));
574                         }
575                         return true;
576                 } else {
577                         Alert::error(_("Document format failure"),
578                                 _("The specified document is not a LyX document."));
579                 }
580         } else {
581                 Alert::error(_("Document could not be read"),
582                         _("The specified document could not be read."));
583         }
584         return false;
585 }
586
587
588 // Should probably be moved to somewhere else: BufferView? LyXView?
589 bool Buffer::save() const
590 {
591         // We don't need autosaves in the immediate future. (Asger)
592         resetAutosaveTimers();
593
594         // make a backup
595         string s;
596         if (lyxrc.make_backup) {
597                 s = fileName() + '~';
598                 if (!lyxrc.backupdir_path.empty())
599                         s = AddName(lyxrc.backupdir_path,
600                                     subst(os::slashify_path(s),'/','!'));
601
602                 // Rename is the wrong way of making a backup,
603                 // this is the correct way.
604                 /* truss cp fil fil2:
605                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
606                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
607                    open("LyXVC.lyx", O_RDONLY)                     = 3
608                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
609                    fstat(4, 0xEFFFF508)                            = 0
610                    fstat(3, 0xEFFFF508)                            = 0
611                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
612                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
613                    read(3, 0xEFFFD4A0, 8192)                       = 0
614                    close(4)                                        = 0
615                    close(3)                                        = 0
616                    chmod("LyXVC3.lyx", 0100644)                    = 0
617                    lseek(0, 0, SEEK_CUR)                           = 46440
618                    _exit(0)
619                 */
620
621                 // Should probably have some more error checking here.
622                 // Doing it this way, also makes the inodes stay the same.
623                 // This is still not a very good solution, in particular we
624                 // might loose the owner of the backup.
625                 FileInfo finfo(fileName());
626                 if (finfo.exist()) {
627                         mode_t fmode = finfo.getMode();
628                         struct utimbuf times = {
629                                 finfo.getAccessTime(),
630                                 finfo.getModificationTime() };
631
632                         ifstream ifs(fileName().c_str());
633                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
634                         if (ifs && ofs) {
635                                 ofs << ifs.rdbuf();
636                                 ifs.close();
637                                 ofs.close();
638                                 ::chmod(s.c_str(), fmode);
639
640                                 if (::utime(s.c_str(), &times)) {
641                                         lyxerr << "utime error." << endl;
642                                 }
643                         } else {
644                                 lyxerr << "LyX was not able to make "
645                                         "backup copy. Beware." << endl;
646                         }
647                 }
648         }
649
650         if (writeFile(fileName())) {
651                 markClean();
652                 removeAutosaveFile(fileName());
653         } else {
654                 // Saving failed, so backup is not backup
655                 if (lyxrc.make_backup) {
656                         lyx::rename(s, fileName());
657                 }
658                 return false;
659         }
660         return true;
661 }
662
663
664 bool Buffer::writeFile(string const & fname) const
665 {
666         if (read_only && (fname == fileName())) {
667                 return false;
668         }
669
670         FileInfo finfo(fname);
671         if (finfo.exist() && !finfo.writable()) {
672                 return false;
673         }
674
675         ofstream ofs(fname.c_str());
676         if (!ofs) {
677                 return false;
678         }
679
680 #ifdef HAVE_LOCALE
681         // Use the standard "C" locale for file output.
682         ofs.imbue(std::locale::classic());
683 #endif
684
685         // The top of the file should not be written by params.
686
687         // write out a comment in the top of the file
688         ofs << '#' << lyx_docversion
689             << " created this file. For more info see http://www.lyx.org/\n"
690             << "\\lyxformat " << LYX_FORMAT << "\n";
691
692         // now write out the buffer paramters.
693         params.writeFile(ofs);
694
695         ofs << "\\end_header\n";
696
697         Paragraph::depth_type depth = 0;
698
699         // this will write out all the paragraphs
700         // using recursive descent.
701         ParagraphList::iterator pit = paragraphs.begin();
702         ParagraphList::iterator pend = paragraphs.end();
703         for (; pit != pend; ++pit)
704                 pit->write(this, ofs, params, depth);
705
706         // Write marker that shows file is complete
707         ofs << "\n\\the_end" << endl;
708
709         ofs.close();
710
711         // how to check if close went ok?
712         // Following is an attempt... (BE 20001011)
713
714         // good() returns false if any error occured, including some
715         //        formatting error.
716         // bad()  returns true if something bad happened in the buffer,
717         //        which should include file system full errors.
718
719         bool status = true;
720         if (!ofs.good()) {
721                 status = false;
722 #if 0
723                 if (ofs.bad()) {
724                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
725                 } else {
726                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
727                                << endl;
728                 }
729 #endif
730         }
731
732         return status;
733 }
734
735
736 namespace {
737
738 pair<int, string> const addDepth(int depth, int ldepth)
739 {
740         int d = depth * 2;
741         if (ldepth > depth)
742                 d += (ldepth - depth) * 2;
743         return make_pair(d, string(d, ' '));
744 }
745
746 }
747
748
749 string const Buffer::asciiParagraph(Paragraph const & par,
750                                     unsigned int linelen,
751                                     bool noparbreak) const
752 {
753         ostringstream buffer;
754         Paragraph::depth_type depth = 0;
755         int ltype = 0;
756         Paragraph::depth_type ltype_depth = 0;
757         bool ref_printed = false;
758 //      if (!par->previous()) {
759 #if 0
760         // begins or ends a deeper area ?
761         if (depth != par->params().depth()) {
762                 if (par->params().depth() > depth) {
763                         while (par->params().depth() > depth) {
764                                 ++depth;
765                         }
766                 } else {
767                         while (par->params().depth() < depth) {
768                                 --depth;
769                         }
770                 }
771         }
772 #else
773         depth = par.params().depth();
774 #endif
775
776         // First write the layout
777         string const & tmp = par.layout()->name();
778         if (compare_no_case(tmp, "itemize") == 0) {
779                 ltype = 1;
780                 ltype_depth = depth + 1;
781         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
782                 ltype = 2;
783                 ltype_depth = depth + 1;
784         } else if (contains(ascii_lowercase(tmp), "ection")) {
785                 ltype = 3;
786                 ltype_depth = depth + 1;
787         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
788                 ltype = 4;
789                 ltype_depth = depth + 1;
790         } else if (compare_ascii_no_case(tmp, "description") == 0) {
791                 ltype = 5;
792                 ltype_depth = depth + 1;
793         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
794                 ltype = 6;
795                 ltype_depth = 0;
796         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
797                 ltype = 7;
798                 ltype_depth = 0;
799         } else {
800                 ltype = 0;
801                 ltype_depth = 0;
802         }
803
804         /* maybe some vertical spaces */
805
806         /* the labelwidthstring used in lists */
807
808         /* some lines? */
809
810         /* some pagebreaks? */
811
812         /* noindent ? */
813
814         /* what about the alignment */
815
816         // linelen <= 0 is special and means we don't have paragraph breaks
817
818         string::size_type currlinelen = 0;
819
820         if (!noparbreak) {
821                 if (linelen > 0)
822                         buffer << "\n\n";
823
824                 buffer << string(depth * 2, ' ');
825                 currlinelen += depth * 2;
826
827                 //--
828                 // we should probably change to the paragraph language in the
829                 // gettext here (if possible) so that strings are outputted in
830                 // the correct language! (20012712 Jug)
831                 //--
832                 switch (ltype) {
833                 case 0: // Standard
834                 case 4: // (Sub)Paragraph
835                 case 5: // Description
836                         break;
837                 case 6: // Abstract
838                         if (linelen > 0) {
839                                 buffer << _("Abstract") << "\n\n";
840                                 currlinelen = 0;
841                         } else {
842                                 string const abst = _("Abstract: ");
843                                 buffer << abst;
844                                 currlinelen += abst.length();
845                         }
846                         break;
847                 case 7: // Bibliography
848                         if (!ref_printed) {
849                                 if (linelen > 0) {
850                                         buffer << _("References") << "\n\n";
851                                         currlinelen = 0;
852                                 } else {
853                                         string const refs = _("References: ");
854                                         buffer << refs;
855                                         currlinelen += refs.length();
856                                 }
857
858                                 ref_printed = true;
859                         }
860                         break;
861                 default:
862                 {
863                         string const parlab = par.params().labelString();
864                         buffer << parlab << ' ';
865                         currlinelen += parlab.length() + 1;
866                 }
867                 break;
868
869                 }
870         }
871
872         if (!currlinelen) {
873                 pair<int, string> p = addDepth(depth, ltype_depth);
874                 buffer << p.second;
875                 currlinelen += p.first;
876         }
877
878         // this is to change the linebreak to do it by word a bit more
879         // intelligent hopefully! (only in the case where we have a
880         // max linelength!) (Jug)
881
882         string word;
883
884         for (pos_type i = 0; i < par.size(); ++i) {
885                 char c = par.getUChar(params, i);
886                 switch (c) {
887                 case Paragraph::META_INSET:
888                 {
889                         Inset const * inset = par.getInset(i);
890                         if (inset) {
891                                 if (linelen > 0) {
892                                         buffer << word;
893                                         currlinelen += word.length();
894                                         word.erase();
895                                 }
896                                 if (inset->ascii(this, buffer, linelen)) {
897                                         // to be sure it breaks paragraph
898                                         currlinelen += linelen;
899                                 }
900                         }
901                 }
902                 break;
903
904                 default:
905                         if (c == ' ') {
906                                 if (linelen > 0 &&
907                                     currlinelen + word.length() > linelen - 10) {
908                                         buffer << "\n";
909                                         pair<int, string> p = addDepth(depth, ltype_depth);
910                                         buffer << p.second;
911                                         currlinelen = p.first;
912                                 }
913
914                                 buffer << word << ' ';
915                                 currlinelen += word.length() + 1;
916                                 word.erase();
917
918                         } else {
919                                 if (c != '\0') {
920                                         word += c;
921                                 } else {
922                                         lyxerr[Debug::INFO] <<
923                                                 "writeAsciiFile: NULL char in structure." << endl;
924                                 }
925                                 if ((linelen > 0) &&
926                                         (currlinelen + word.length()) > linelen)
927                                 {
928                                         buffer << "\n";
929
930                                         pair<int, string> p =
931                                                 addDepth(depth, ltype_depth);
932                                         buffer << p.second;
933                                         currlinelen = p.first;
934                                 }
935                         }
936                         break;
937                 }
938         }
939         buffer << word;
940         return STRCONV(buffer.str());
941 }
942
943
944 void Buffer::writeFileAscii(string const & fname, int linelen)
945 {
946         ofstream ofs(fname.c_str());
947         if (!ofs) {
948                 string const error = strerror(errno);
949                 string const file = MakeDisplayPath(fname, 50);
950 #if USE_BOOST_FORMAT
951                 boost::format fmt(_("Could not save the document\n%1$s\ndue to the error: %2$s"));
952                 fmt % file;
953                 fmt % error;
954                 string text = fmt.str();
955 #else
956                 string text = _("Could not save the document\n");
957                 text += file + _(" due to the error: ");
958                 text += error;
959 #endif
960                 Alert::error(_("Could not save document"), text);
961                 return;
962         }
963         writeFileAscii(ofs, linelen);
964 }
965
966
967 void Buffer::writeFileAscii(ostream & os, int linelen)
968 {
969         ParagraphList::iterator beg = paragraphs.begin();
970         ParagraphList::iterator end = paragraphs.end();
971         ParagraphList::iterator it = beg;
972         for (; it != end; ++it) {
973                 os << asciiParagraph(*it, linelen, it == beg);
974         }
975         os << "\n";
976 }
977
978
979
980 void Buffer::makeLaTeXFile(string const & fname,
981                            string const & original_path,
982                            bool nice, bool only_body, bool only_preamble)
983 {
984         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
985
986         ofstream ofs(fname.c_str());
987         if (!ofs) {
988                 string const error = strerror(errno);
989                 string const file = MakeDisplayPath(fname, 50);
990 #if USE_BOOST_FORMAT
991                 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
992                 fmt % file;
993                 fmt % error;
994                 string text = fmt.str();
995 #else
996                 string text = _("Could not open the specified document\n");
997                 text += file + _(" due to the error: ");
998                 text += error;
999 #endif
1000                 Alert::error(_("Could not open file"), text);
1001                 return;
1002         }
1003
1004         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1005
1006         ofs.close();
1007         if (ofs.fail()) {
1008                 lyxerr << "File was not closed properly." << endl;
1009         }
1010 }
1011
1012
1013 void Buffer::makeLaTeXFile(ostream & os,
1014                            string const & original_path,
1015                            bool nice, bool only_body, bool only_preamble)
1016 {
1017         niceFile = nice; // this will be used by Insetincludes.
1018
1019         // validate the buffer.
1020         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1021         LaTeXFeatures features(params);
1022         validate(features);
1023         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1024
1025         texrow.reset();
1026         // The starting paragraph of the coming rows is the
1027         // first paragraph of the document. (Asger)
1028         texrow.start(&*(paragraphs.begin()), 0);
1029
1030         if (!only_body && nice) {
1031                 os << "%% " << lyx_docversion << " created this file.  "
1032                         "For more info, see http://www.lyx.org/.\n"
1033                         "%% Do not edit unless you really know what "
1034                         "you are doing.\n";
1035                 texrow.newline();
1036                 texrow.newline();
1037         }
1038         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1039         // There are a few differences between nice LaTeX and usual files:
1040         // usual is \batchmode and has a
1041         // special input@path to allow the including of figures
1042         // with either \input or \includegraphics (what figinsets do).
1043         // input@path is set when the actual parameter
1044         // original_path is set. This is done for usual tex-file, but not
1045         // for nice-latex-file. (Matthias 250696)
1046         if (!only_body) {
1047                 if (!nice) {
1048                         // code for usual, NOT nice-latex-file
1049                         os << "\\batchmode\n"; // changed
1050                         // from \nonstopmode
1051                         texrow.newline();
1052                 }
1053                 if (!original_path.empty()) {
1054                         string inputpath = os::external_path(original_path);
1055                         subst(inputpath, "~", "\\string~");
1056                         os << "\\makeatletter\n"
1057                             << "\\def\\input@path{{"
1058                             << inputpath << "/}}\n"
1059                             << "\\makeatother\n";
1060                         texrow.newline();
1061                         texrow.newline();
1062                         texrow.newline();
1063                 }
1064
1065                 // Write the preamble
1066                 params.writeLaTeX(os, features, texrow);
1067
1068                 if (only_preamble)
1069                         return;
1070
1071                 // make the body.
1072                 os << "\\begin{document}\n";
1073                 texrow.newline();
1074         } // only_body
1075         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1076
1077         if (!lyxrc.language_auto_begin) {
1078                 os << subst(lyxrc.language_command_begin, "$$lang",
1079                              params.language->babel())
1080                     << endl;
1081                 texrow.newline();
1082         }
1083
1084         latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1085
1086         // add this just in case after all the paragraphs
1087         os << endl;
1088         texrow.newline();
1089
1090         if (!lyxrc.language_auto_end) {
1091                 os << subst(lyxrc.language_command_end, "$$lang",
1092                              params.language->babel())
1093                     << endl;
1094                 texrow.newline();
1095         }
1096
1097         if (!only_body) {
1098                 os << "\\end{document}\n";
1099                 texrow.newline();
1100
1101                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1102         } else {
1103                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1104                                      << endl;
1105         }
1106
1107         // Just to be sure. (Asger)
1108         texrow.newline();
1109
1110         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1111         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1112                             << '.' << endl;
1113
1114         // we want this to be true outside previews (for insetexternal)
1115         niceFile = true;
1116 }
1117
1118
1119 bool Buffer::isLatex() const
1120 {
1121         return params.getLyXTextClass().outputType() == LATEX;
1122 }
1123
1124
1125 bool Buffer::isLinuxDoc() const
1126 {
1127         return params.getLyXTextClass().outputType() == LINUXDOC;
1128 }
1129
1130
1131 bool Buffer::isLiterate() const
1132 {
1133         return params.getLyXTextClass().outputType() == LITERATE;
1134 }
1135
1136
1137 bool Buffer::isDocBook() const
1138 {
1139         return params.getLyXTextClass().outputType() == DOCBOOK;
1140 }
1141
1142
1143 bool Buffer::isSGML() const
1144 {
1145         LyXTextClass const & tclass = params.getLyXTextClass();
1146
1147         return tclass.outputType() == LINUXDOC ||
1148                tclass.outputType() == DOCBOOK;
1149 }
1150
1151
1152 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1153 {
1154         ofstream ofs(fname.c_str());
1155
1156         if (!ofs) {
1157                 string const file = MakeDisplayPath(fname, 50);
1158 #if USE_BOOST_FORMAT
1159                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1160                 fmt % file;
1161                 string text = fmt.str();
1162 #else
1163                 string text = _("Could not save the specified document\n");
1164                 text += file + _(".\n");
1165 #endif
1166                 Alert::error(_("Could not save document"), text);
1167                 return;
1168         }
1169
1170         niceFile = nice; // this will be used by included files.
1171
1172         LaTeXFeatures features(params);
1173
1174         validate(features);
1175
1176         texrow.reset();
1177
1178         LyXTextClass const & tclass = params.getLyXTextClass();
1179
1180         string top_element = tclass.latexname();
1181
1182         if (!body_only) {
1183                 ofs << "<!doctype linuxdoc system";
1184
1185                 string preamble = params.preamble;
1186                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1187                          : fname;
1188                 preamble += features.getIncludedFiles(name);
1189                 preamble += features.getLyXSGMLEntities();
1190
1191                 if (!preamble.empty()) {
1192                         ofs << " [ " << preamble << " ]";
1193                 }
1194                 ofs << ">\n\n";
1195
1196                 if (params.options.empty())
1197                         sgml::openTag(ofs, 0, false, top_element);
1198                 else {
1199                         string top = top_element;
1200                         top += ' ';
1201                         top += params.options;
1202                         sgml::openTag(ofs, 0, false, top);
1203                 }
1204         }
1205
1206         ofs << "<!-- "  << lyx_docversion
1207             << " created this file. For more info see http://www.lyx.org/"
1208             << " -->\n";
1209
1210         Paragraph::depth_type depth = 0; // paragraph depth
1211         Paragraph * par = &*(paragraphs.begin());
1212         string item_name;
1213         vector<string> environment_stack(5);
1214
1215         while (par) {
1216                 LyXLayout_ptr const & style = par->layout();
1217                 // treat <toc> as a special case for compatibility with old code
1218                 if (par->isInset(0)) {
1219                         Inset * inset = par->getInset(0);
1220                         Inset::Code lyx_code = inset->lyxCode();
1221                         if (lyx_code == Inset::TOC_CODE) {
1222                                 string const temp = "toc";
1223                                 sgml::openTag(ofs, depth, false, temp);
1224
1225                                 par = par->next();
1226                                 continue;
1227                         }
1228                 }
1229
1230                 // environment tag closing
1231                 for (; depth > par->params().depth(); --depth) {
1232                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1233                         environment_stack[depth].erase();
1234                 }
1235
1236                 // write opening SGML tags
1237                 switch (style->latextype) {
1238                 case LATEX_PARAGRAPH:
1239                         if (depth == par->params().depth()
1240                            && !environment_stack[depth].empty()) {
1241                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1242                                 environment_stack[depth].erase();
1243                                 if (depth)
1244                                         --depth;
1245                                 else
1246                                         ofs << "</p>";
1247                         }
1248                         sgml::openTag(ofs, depth, false, style->latexname());
1249                         break;
1250
1251                 case LATEX_COMMAND:
1252                         if (depth!= 0)
1253                                 sgmlError(par, 0,
1254                                           _("Error: Wrong depth for LatexType Command.\n"));
1255
1256                         if (!environment_stack[depth].empty()) {
1257                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1258                                 ofs << "</p>";
1259                         }
1260
1261                         environment_stack[depth].erase();
1262                         sgml::openTag(ofs, depth, false, style->latexname());
1263                         break;
1264
1265                 case LATEX_ENVIRONMENT:
1266                 case LATEX_ITEM_ENVIRONMENT:
1267                 case LATEX_BIB_ENVIRONMENT:
1268                 {
1269                         string const & latexname = style->latexname();
1270
1271                         if (depth == par->params().depth()
1272                             && environment_stack[depth] != latexname) {
1273                                 sgml::closeTag(ofs, depth, false,
1274                                              environment_stack[depth]);
1275                                 environment_stack[depth].erase();
1276                         }
1277                         if (depth < par->params().depth()) {
1278                                depth = par->params().depth();
1279                                environment_stack[depth].erase();
1280                         }
1281                         if (environment_stack[depth] != latexname) {
1282                                 if (depth == 0) {
1283                                         sgml::openTag(ofs, depth, false, "p");
1284                                 }
1285                                 sgml::openTag(ofs, depth, false, latexname);
1286
1287                                 if (environment_stack.size() == depth + 1)
1288                                         environment_stack.push_back("!-- --");
1289                                 environment_stack[depth] = latexname;
1290                         }
1291
1292                         if (style->latexparam() == "CDATA")
1293                                 ofs << "<![CDATA[";
1294
1295                         if (style->latextype == LATEX_ENVIRONMENT) break;
1296
1297                         if (style->labeltype == LABEL_MANUAL)
1298                                 item_name = "tag";
1299                         else
1300                                 item_name = "item";
1301
1302                         sgml::openTag(ofs, depth + 1, false, item_name);
1303                 }
1304                 break;
1305
1306                 default:
1307                         sgml::openTag(ofs, depth, false, style->latexname());
1308                         break;
1309                 }
1310
1311                 simpleLinuxDocOnePar(ofs, par, depth);
1312
1313                 par = par->next();
1314
1315                 ofs << "\n";
1316                 // write closing SGML tags
1317                 switch (style->latextype) {
1318                 case LATEX_COMMAND:
1319                         break;
1320                 case LATEX_ENVIRONMENT:
1321                 case LATEX_ITEM_ENVIRONMENT:
1322                 case LATEX_BIB_ENVIRONMENT:
1323                         if (style->latexparam() == "CDATA")
1324                                 ofs << "]]>";
1325                         break;
1326                 default:
1327                         sgml::closeTag(ofs, depth, false, style->latexname());
1328                         break;
1329                 }
1330         }
1331
1332         // Close open tags
1333         for (int i = depth; i >= 0; --i)
1334                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1335
1336         if (!body_only) {
1337                 ofs << "\n\n";
1338                 sgml::closeTag(ofs, 0, false, top_element);
1339         }
1340
1341         ofs.close();
1342         // How to check for successful close
1343
1344         // we want this to be true outside previews (for insetexternal)
1345         niceFile = true;
1346 }
1347
1348
1349 // checks, if newcol chars should be put into this line
1350 // writes newline, if necessary.
1351 namespace {
1352
1353 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1354                           string::size_type newcol)
1355 {
1356         colcount += newcol;
1357         if (colcount > lyxrc.ascii_linelen) {
1358                 os << "\n";
1359                 colcount = newcol; // assume write after this call
1360         }
1361 }
1362
1363 enum PAR_TAG {
1364         NONE=0,
1365         TT = 1,
1366         SF = 2,
1367         BF = 4,
1368         IT = 8,
1369         SL = 16,
1370         EM = 32
1371 };
1372
1373
1374 string tag_name(PAR_TAG const & pt) {
1375         switch (pt) {
1376         case NONE: return "!-- --";
1377         case TT: return "tt";
1378         case SF: return "sf";
1379         case BF: return "bf";
1380         case IT: return "it";
1381         case SL: return "sl";
1382         case EM: return "em";
1383         }
1384         return "";
1385 }
1386
1387
1388 inline
1389 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1390 {
1391         p1 = static_cast<PAR_TAG>(p1 | p2);
1392 }
1393
1394
1395 inline
1396 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1397 {
1398         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1399 }
1400
1401 } // anon
1402
1403
1404 // Handle internal paragraph parsing -- layout already processed.
1405 void Buffer::simpleLinuxDocOnePar(ostream & os,
1406         Paragraph * par,
1407         Paragraph::depth_type /*depth*/)
1408 {
1409         LyXLayout_ptr const & style = par->layout();
1410
1411         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1412
1413         // gets paragraph main font
1414         LyXFont font_old;
1415         bool desc_on;
1416         if (style->labeltype == LABEL_MANUAL) {
1417                 font_old = style->labelfont;
1418                 desc_on = true;
1419         } else {
1420                 font_old = style->font;
1421                 desc_on = false;
1422         }
1423
1424         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1425         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1426         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1427         bool is_em = false;
1428
1429         stack<PAR_TAG> tag_state;
1430         // parsing main loop
1431         for (pos_type i = 0; i < par->size(); ++i) {
1432
1433                 PAR_TAG tag_close = NONE;
1434                 list < PAR_TAG > tag_open;
1435
1436                 LyXFont const font = par->getFont(params, i);
1437
1438                 if (font_old.family() != font.family()) {
1439                         switch (family_type) {
1440                         case LyXFont::SANS_FAMILY:
1441                                 tag_close |= SF;
1442                                 break;
1443                         case LyXFont::TYPEWRITER_FAMILY:
1444                                 tag_close |= TT;
1445                                 break;
1446                         default:
1447                                 break;
1448                         }
1449
1450                         family_type = font.family();
1451
1452                         switch (family_type) {
1453                         case LyXFont::SANS_FAMILY:
1454                                 tag_open.push_back(SF);
1455                                 break;
1456                         case LyXFont::TYPEWRITER_FAMILY:
1457                                 tag_open.push_back(TT);
1458                                 break;
1459                         default:
1460                                 break;
1461                         }
1462                 }
1463
1464                 if (font_old.series() != font.series()) {
1465                         switch (series_type) {
1466                         case LyXFont::BOLD_SERIES:
1467                                 tag_close |= BF;
1468                                 break;
1469                         default:
1470                                 break;
1471                         }
1472
1473                         series_type = font.series();
1474
1475                         switch (series_type) {
1476                         case LyXFont::BOLD_SERIES:
1477                                 tag_open.push_back(BF);
1478                                 break;
1479                         default:
1480                                 break;
1481                         }
1482
1483                 }
1484
1485                 if (font_old.shape() != font.shape()) {
1486                         switch (shape_type) {
1487                         case LyXFont::ITALIC_SHAPE:
1488                                 tag_close |= IT;
1489                                 break;
1490                         case LyXFont::SLANTED_SHAPE:
1491                                 tag_close |= SL;
1492                                 break;
1493                         default:
1494                                 break;
1495                         }
1496
1497                         shape_type = font.shape();
1498
1499                         switch (shape_type) {
1500                         case LyXFont::ITALIC_SHAPE:
1501                                 tag_open.push_back(IT);
1502                                 break;
1503                         case LyXFont::SLANTED_SHAPE:
1504                                 tag_open.push_back(SL);
1505                                 break;
1506                         default:
1507                                 break;
1508                         }
1509                 }
1510                 // handle <em> tag
1511                 if (font_old.emph() != font.emph()) {
1512                         if (font.emph() == LyXFont::ON) {
1513                                 tag_open.push_back(EM);
1514                                 is_em = true;
1515                         }
1516                         else if (is_em) {
1517                                 tag_close |= EM;
1518                                 is_em = false;
1519                         }
1520                 }
1521
1522                 list < PAR_TAG > temp;
1523                 while (!tag_state.empty() && tag_close) {
1524                         PAR_TAG k =  tag_state.top();
1525                         tag_state.pop();
1526                         os << "</" << tag_name(k) << '>';
1527                         if (tag_close & k)
1528                                 reset(tag_close,k);
1529                         else
1530                                 temp.push_back(k);
1531                 }
1532
1533                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1534                     j != temp.end(); ++j) {
1535                         tag_state.push(*j);
1536                         os << '<' << tag_name(*j) << '>';
1537                 }
1538
1539                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1540                     j != tag_open.end(); ++j) {
1541                         tag_state.push(*j);
1542                         os << '<' << tag_name(*j) << '>';
1543                 }
1544
1545                 char c = par->getChar(i);
1546
1547                 if (c == Paragraph::META_INSET) {
1548                         Inset * inset = par->getInset(i);
1549                         inset->linuxdoc(this, os);
1550                         font_old = font;
1551                         continue;
1552                 }
1553
1554                 if (style->latexparam() == "CDATA") {
1555                         // "TeX"-Mode on == > SGML-Mode on.
1556                         if (c != '\0')
1557                                 os << c;
1558                         ++char_line_count;
1559                 } else {
1560                         bool ws;
1561                         string str;
1562                         boost::tie(ws, str) = sgml::escapeChar(c);
1563                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
1564                                 // in freespacing mode, spaces are
1565                                 // non-breaking characters
1566                                 if (desc_on) {// if char is ' ' then...
1567
1568                                         ++char_line_count;
1569                                         sgmlLineBreak(os, char_line_count, 6);
1570                                         os << "</tag>";
1571                                         desc_on = false;
1572                                 } else  {
1573                                         sgmlLineBreak(os, char_line_count, 1);
1574                                         os << c;
1575                                 }
1576                         } else {
1577                                 os << str;
1578                                 char_line_count += str.length();
1579                         }
1580                 }
1581                 font_old = font;
1582         }
1583
1584         while (!tag_state.empty()) {
1585                 os << "</" << tag_name(tag_state.top()) << '>';
1586                 tag_state.pop();
1587         }
1588
1589         // resets description flag correctly
1590         if (desc_on) {
1591                 // <tag> not closed...
1592                 sgmlLineBreak(os, char_line_count, 6);
1593                 os << "</tag>";
1594         }
1595 }
1596
1597
1598 // Print an error message.
1599 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
1600         string const & /*message*/) const
1601 {
1602 #ifdef WITH_WARNINGS
1603 #warning This is wrong we cannot insert an inset like this!!!
1604         // I guess this was Jose' so I explain you more or less why this
1605         // is wrong. This way you insert something in the paragraph and
1606         // don't tell it to LyXText (row rebreaking and undo handling!!!)
1607         // I deactivate this code, have a look at BufferView::insertErrors
1608         // how you should do this correctly! (Jug 20020315)
1609 #endif
1610 #if 0
1611         // insert an error marker in text
1612         InsetError * new_inset = new InsetError(message);
1613         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1614                          params.language));
1615 #endif
1616 }
1617
1618
1619 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1620 {
1621         ofstream ofs(fname.c_str());
1622         if (!ofs) {
1623                 string const file = MakeDisplayPath(fname, 50);
1624 #if USE_BOOST_FORMAT
1625                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1626                 fmt % file;
1627                 string text = fmt.str();
1628 #else
1629                 string text = _("Could not save the specified document\n");
1630                 text += file + _(".\n");
1631 #endif
1632                 Alert::error(_("Could not save document"), text);
1633                 return;
1634                 return;
1635         }
1636
1637         Paragraph * par = &*(paragraphs.begin());
1638
1639         niceFile = nice; // this will be used by Insetincludes.
1640
1641         LaTeXFeatures features(params);
1642         validate(features);
1643
1644         texrow.reset();
1645
1646         LyXTextClass const & tclass = params.getLyXTextClass();
1647         string top_element = tclass.latexname();
1648
1649         if (!only_body) {
1650                 ofs << "<!DOCTYPE " << top_element
1651                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1652
1653                 string preamble = params.preamble;
1654                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1655                          : fname;
1656                 preamble += features.getIncludedFiles(name);
1657                 preamble += features.getLyXSGMLEntities();
1658
1659                 if (!preamble.empty()) {
1660                         ofs << "\n [ " << preamble << " ]";
1661                 }
1662                 ofs << ">\n\n";
1663         }
1664
1665         string top = top_element;
1666         top += " lang=\"";
1667         top += params.language->code();
1668         top += '"';
1669
1670         if (!params.options.empty()) {
1671                 top += ' ';
1672                 top += params.options;
1673         }
1674         sgml::openTag(ofs, 0, false, top);
1675
1676         ofs << "<!-- DocBook file was created by " << lyx_docversion
1677             << "\n  See http://www.lyx.org/ for more information -->\n";
1678
1679         vector<string> environment_stack(10);
1680         vector<string> environment_inner(10);
1681         vector<string> command_stack(10);
1682
1683         bool command_flag = false;
1684         Paragraph::depth_type command_depth = 0;
1685         Paragraph::depth_type command_base = 0;
1686         Paragraph::depth_type cmd_depth = 0;
1687         Paragraph::depth_type depth = 0; // paragraph depth
1688
1689         string item_name;
1690         string command_name;
1691
1692         while (par) {
1693                 string sgmlparam;
1694                 string c_depth;
1695                 string c_params;
1696                 int desc_on = 0; // description mode
1697
1698                 LyXLayout_ptr const & style = par->layout();
1699
1700                 // environment tag closing
1701                 for (; depth > par->params().depth(); --depth) {
1702                         if (environment_inner[depth] != "!-- --") {
1703                                 item_name = "listitem";
1704                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1705                                 if (environment_inner[depth] == "varlistentry")
1706                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1707                         }
1708                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1709                         environment_stack[depth].erase();
1710                         environment_inner[depth].erase();
1711                 }
1712
1713                 if (depth == par->params().depth()
1714                    && environment_stack[depth] != style->latexname()
1715                    && !environment_stack[depth].empty()) {
1716                         if (environment_inner[depth] != "!-- --") {
1717                                 item_name= "listitem";
1718                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1719                                 if (environment_inner[depth] == "varlistentry")
1720                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1721                         }
1722
1723                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1724
1725                         environment_stack[depth].erase();
1726                         environment_inner[depth].erase();
1727                 }
1728
1729                 // Write opening SGML tags.
1730                 switch (style->latextype) {
1731                 case LATEX_PARAGRAPH:
1732                         sgml::openTag(ofs, depth + command_depth,
1733                                     false, style->latexname());
1734                         break;
1735
1736                 case LATEX_COMMAND:
1737                         if (depth != 0)
1738                                 sgmlError(par, 0,
1739                                           _("Error: Wrong depth for LatexType Command.\n"));
1740
1741                         command_name = style->latexname();
1742
1743                         sgmlparam = style->latexparam();
1744                         c_params = split(sgmlparam, c_depth,'|');
1745
1746                         cmd_depth = lyx::atoi(c_depth);
1747
1748                         if (command_flag) {
1749                                 if (cmd_depth < command_base) {
1750                                         for (Paragraph::depth_type j = command_depth;
1751                                              j >= command_base; --j) {
1752                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1753                                                 ofs << endl;
1754                                         }
1755                                         command_depth = command_base = cmd_depth;
1756                                 } else if (cmd_depth <= command_depth) {
1757                                         for (int j = command_depth;
1758                                              j >= int(cmd_depth); --j) {
1759                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1760                                                 ofs << endl;
1761                                         }
1762                                         command_depth = cmd_depth;
1763                                 } else
1764                                         command_depth = cmd_depth;
1765                         } else {
1766                                 command_depth = command_base = cmd_depth;
1767                                 command_flag = true;
1768                         }
1769                         if (command_stack.size() == command_depth + 1)
1770                                 command_stack.push_back(string());
1771                         command_stack[command_depth] = command_name;
1772
1773                         // treat label as a special case for
1774                         // more WYSIWYM handling.
1775                         // This is a hack while paragraphs can't have
1776                         // attributes, like id in this case.
1777                         if (par->isInset(0)) {
1778                                 Inset * inset = par->getInset(0);
1779                                 Inset::Code lyx_code = inset->lyxCode();
1780                                 if (lyx_code == Inset::LABEL_CODE) {
1781                                         command_name += " id=\"";
1782                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1783                                         command_name += '"';
1784                                         desc_on = 3;
1785                                 }
1786                         }
1787
1788                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1789
1790                         item_name = c_params.empty() ? "title" : c_params;
1791                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1792                         break;
1793
1794                 case LATEX_ENVIRONMENT:
1795                 case LATEX_ITEM_ENVIRONMENT:
1796                         if (depth < par->params().depth()) {
1797                                 depth = par->params().depth();
1798                                 environment_stack[depth].erase();
1799                         }
1800
1801                         if (environment_stack[depth] != style->latexname()) {
1802                                 if (environment_stack.size() == depth + 1) {
1803                                         environment_stack.push_back("!-- --");
1804                                         environment_inner.push_back("!-- --");
1805                                 }
1806                                 environment_stack[depth] = style->latexname();
1807                                 environment_inner[depth] = "!-- --";
1808                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1809                         } else {
1810                                 if (environment_inner[depth] != "!-- --") {
1811                                         item_name= "listitem";
1812                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1813                                         if (environment_inner[depth] == "varlistentry")
1814                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1815                                 }
1816                         }
1817
1818                         if (style->latextype == LATEX_ENVIRONMENT) {
1819                                 if (!style->latexparam().empty()) {
1820                                         if (style->latexparam() == "CDATA")
1821                                                 ofs << "<![CDATA[";
1822                                         else
1823                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1824                                 }
1825                                 break;
1826                         }
1827
1828                         desc_on = (style->labeltype == LABEL_MANUAL);
1829
1830                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1831                         sgml::openTag(ofs, depth + 1 + command_depth,
1832                                     false, environment_inner[depth]);
1833
1834                         item_name = desc_on ? "term" : "para";
1835                         sgml::openTag(ofs, depth + 1 + command_depth,
1836                                     false, item_name);
1837                         break;
1838                 default:
1839                         sgml::openTag(ofs, depth + command_depth,
1840                                     false, style->latexname());
1841                         break;
1842                 }
1843
1844                 simpleDocBookOnePar(ofs, par, desc_on,
1845                                     depth + 1 + command_depth);
1846                 par = par->next();
1847
1848                 string end_tag;
1849                 // write closing SGML tags
1850                 switch (style->latextype) {
1851                 case LATEX_COMMAND:
1852                         end_tag = c_params.empty() ? "title" : c_params;
1853                         sgml::closeTag(ofs, depth + command_depth,
1854                                      false, end_tag);
1855                         break;
1856                 case LATEX_ENVIRONMENT:
1857                         if (!style->latexparam().empty()) {
1858                                 if (style->latexparam() == "CDATA")
1859                                         ofs << "]]>";
1860                                 else
1861                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1862                         }
1863                         break;
1864                 case LATEX_ITEM_ENVIRONMENT:
1865                         if (desc_on == 1) break;
1866                         end_tag = "para";
1867                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1868                         break;
1869                 case LATEX_PARAGRAPH:
1870                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1871                         break;
1872                 default:
1873                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1874                         break;
1875                 }
1876         }
1877
1878         // Close open tags
1879         for (int d = depth; d >= 0; --d) {
1880                 if (!environment_stack[depth].empty()) {
1881                         if (environment_inner[depth] != "!-- --") {
1882                                 item_name = "listitem";
1883                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1884                                if (environment_inner[depth] == "varlistentry")
1885                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1886                         }
1887
1888                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1889                 }
1890         }
1891
1892         for (int j = command_depth; j >= 0 ; --j)
1893                 if (!command_stack[j].empty()) {
1894                         sgml::closeTag(ofs, j, false, command_stack[j]);
1895                         ofs << endl;
1896                 }
1897
1898         ofs << "\n\n";
1899         sgml::closeTag(ofs, 0, false, top_element);
1900
1901         ofs.close();
1902         // How to check for successful close
1903
1904         // we want this to be true outside previews (for insetexternal)
1905         niceFile = true;
1906 }
1907
1908
1909 void Buffer::simpleDocBookOnePar(ostream & os,
1910                                  Paragraph * par, int & desc_on,
1911                                  Paragraph::depth_type depth) const
1912 {
1913         bool emph_flag = false;
1914
1915         LyXLayout_ptr const & style = par->layout();
1916
1917         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1918
1919         int char_line_count = depth;
1920         //if (!style.free_spacing)
1921         //      os << string(depth,' ');
1922
1923         // parsing main loop
1924         for (pos_type i = 0; i < par->size(); ++i) {
1925                 LyXFont font = par->getFont(params, i);
1926
1927                 // handle <emphasis> tag
1928                 if (font_old.emph() != font.emph()) {
1929                         if (font.emph() == LyXFont::ON) {
1930                                 if (style->latexparam() == "CDATA")
1931                                         os << "]]>";
1932                                 os << "<emphasis>";
1933                                 if (style->latexparam() == "CDATA")
1934                                         os << "<![CDATA[";
1935                                 emph_flag = true;
1936                         } else if (i) {
1937                                 if (style->latexparam() == "CDATA")
1938                                         os << "]]>";
1939                                 os << "</emphasis>";
1940                                 if (style->latexparam() == "CDATA")
1941                                         os << "<![CDATA[";
1942                                 emph_flag = false;
1943                         }
1944                 }
1945
1946
1947                 if (par->isInset(i)) {
1948                         Inset * inset = par->getInset(i);
1949                         // don't print the inset in position 0 if desc_on == 3 (label)
1950                         if (i || desc_on != 3) {
1951                                 if (style->latexparam() == "CDATA")
1952                                         os << "]]>";
1953                                 inset->docbook(this, os, false);
1954                                 if (style->latexparam() == "CDATA")
1955                                         os << "<![CDATA[";
1956                         }
1957                 } else {
1958                         char c = par->getChar(i);
1959                         bool ws;
1960                         string str;
1961                         boost::tie(ws, str) = sgml::escapeChar(c);
1962
1963                         if (style->pass_thru) {
1964                                 os << c;
1965                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
1966                                         os << str;
1967                         } else if (desc_on ==1) {
1968                                 ++char_line_count;
1969                                 os << "\n</term><listitem><para>";
1970                                 desc_on = 2;
1971                         } else {
1972                                 os << ' ';
1973                         }
1974                 }
1975                 font_old = font;
1976         }
1977
1978         if (emph_flag) {
1979                 if (style->latexparam() == "CDATA")
1980                         os << "]]>";
1981                 os << "</emphasis>";
1982                 if (style->latexparam() == "CDATA")
1983                         os << "<![CDATA[";
1984         }
1985
1986         // resets description flag correctly
1987         if (desc_on == 1) {
1988                 // <term> not closed...
1989                 os << "</term>\n<listitem><para>&nbsp;</para>";
1990         }
1991         if (style->free_spacing)
1992                 os << '\n';
1993 }
1994
1995
1996 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1997 // Other flags: -wall -v0 -x
1998 int Buffer::runChktex()
1999 {
2000         if (!users->text) return 0;
2001
2002         users->owner()->busy(true);
2003
2004         // get LaTeX-Filename
2005         string const name = getLatexName();
2006         string path = filePath();
2007
2008         string const org_path = path;
2009         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2010                 path = tmppath;
2011         }
2012
2013         Path p(path); // path to LaTeX file
2014         users->owner()->message(_("Running chktex..."));
2015
2016         // Remove all error insets
2017         bool const removedErrorInsets = users->removeAutoInsets();
2018
2019         // Generate the LaTeX file if neccessary
2020         makeLaTeXFile(name, org_path, false);
2021
2022         TeXErrors terr;
2023         Chktex chktex(lyxrc.chktex_command, name, filePath());
2024         int res = chktex.run(terr); // run chktex
2025
2026         if (res == -1) {
2027                 Alert::error(_("chktex failure"),
2028                         _("Could not run chktex successfully."));
2029         } else if (res > 0) {
2030                 // Insert all errors as errors boxes
2031                 users->insertErrors(terr);
2032         }
2033
2034         // if we removed error insets before we ran chktex or if we inserted
2035         // error insets after we ran chktex, this must be run:
2036         if (removedErrorInsets || res) {
2037 #warning repaint needed here, or do you mean update() ?
2038                 users->repaint();
2039                 users->fitCursor();
2040         }
2041         users->owner()->busy(false);
2042
2043         return res;
2044 }
2045
2046
2047 void Buffer::validate(LaTeXFeatures & features) const
2048 {
2049         LyXTextClass const & tclass = params.getLyXTextClass();
2050
2051         if (params.tracking_changes) {
2052                 features.require("dvipost");
2053                 features.require("color");
2054         }
2055
2056         // AMS Style is at document level
2057         if (params.use_amsmath == BufferParams::AMS_ON
2058             || tclass.provides(LyXTextClass::amsmath))
2059                 features.require("amsmath");
2060
2061         for_each(paragraphs.begin(), paragraphs.end(),
2062                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2063
2064         // the bullet shapes are buffer level not paragraph level
2065         // so they are tested here
2066         for (int i = 0; i < 4; ++i) {
2067                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2068                         int const font = params.user_defined_bullets[i].getFont();
2069                         if (font == 0) {
2070                                 int const c = params
2071                                         .user_defined_bullets[i]
2072                                         .getCharacter();
2073                                 if (c == 16
2074                                    || c == 17
2075                                    || c == 25
2076                                    || c == 26
2077                                    || c == 31) {
2078                                         features.require("latexsym");
2079                                 }
2080                         } else if (font == 1) {
2081                                 features.require("amssymb");
2082                         } else if ((font >= 2 && font <= 5)) {
2083                                 features.require("pifont");
2084                         }
2085                 }
2086         }
2087
2088         if (lyxerr.debugging(Debug::LATEX)) {
2089                 features.showStruct();
2090         }
2091 }
2092
2093
2094 vector<string> const Buffer::getLabelList() const
2095 {
2096         /// if this is a child document and the parent is already loaded
2097         /// Use the parent's list instead  [ale990407]
2098         if (!params.parentname.empty()
2099             && bufferlist.exists(params.parentname)) {
2100                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2101                 if (tmp)
2102                         return tmp->getLabelList();
2103         }
2104
2105         vector<string> label_list;
2106         for (inset_iterator it = inset_const_iterator_begin();
2107              it != inset_const_iterator_end(); ++it) {
2108                 vector<string> const l = it->getLabelList();
2109                 label_list.insert(label_list.end(), l.begin(), l.end());
2110         }
2111         return label_list;
2112 }
2113
2114
2115 // This is also a buffer property (ale)
2116 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2117 {
2118         /// if this is a child document and the parent is already loaded
2119         /// use the parent's list instead  [ale990412]
2120         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2121                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2122                 if (tmp) {
2123                         tmp->fillWithBibKeys(keys);
2124                         return;
2125                 }
2126         }
2127
2128         for (inset_iterator it = inset_const_iterator_begin();
2129                 it != inset_const_iterator_end(); ++it) {
2130                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2131                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2132                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2133                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2134                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2135                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2136                         string const key = bib.getContents();
2137                         string const opt = bib.getOptions();
2138                         string const ref; // = pit->asString(this, false);
2139                         string const info = opt + "TheBibliographyRef" + ref;
2140                         keys.push_back(pair<string, string>(key, info));
2141                 }
2142         }
2143 }
2144
2145
2146 bool Buffer::isDepClean(string const & name) const
2147 {
2148         DepClean::const_iterator it = dep_clean_.find(name);
2149         if (it == dep_clean_.end())
2150                 return true;
2151         return it->second;
2152 }
2153
2154
2155 void Buffer::markDepClean(string const & name)
2156 {
2157         dep_clean_[name] = true;
2158 }
2159
2160
2161 bool Buffer::dispatch(string const & command, bool * result)
2162 {
2163         // Split command string into command and argument
2164         string cmd;
2165         string line = ltrim(command);
2166         string const arg = trim(split(line, cmd, ' '));
2167
2168         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2169 }
2170
2171
2172 bool Buffer::dispatch(int action, string const & argument, bool * result)
2173 {
2174         bool dispatched = true;
2175
2176         switch (action) {
2177                 case LFUN_EXPORT: {
2178                         bool const tmp = Exporter::Export(this, argument, false);
2179                         if (result)
2180                                 *result = tmp;
2181                         break;
2182                 }
2183
2184                 default:
2185                         dispatched = false;
2186         }
2187         return dispatched;
2188 }
2189
2190
2191 void Buffer::resizeInsets(BufferView * bv)
2192 {
2193         /// then remove all LyXText in text-insets
2194         for_each(paragraphs.begin(), paragraphs.end(),
2195                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2196 }
2197
2198
2199 void Buffer::redraw()
2200 {
2201 #warning repaint needed here, or do you mean update() ?
2202         users->repaint();
2203         users->fitCursor();
2204 }
2205
2206
2207 void Buffer::changeLanguage(Language const * from, Language const * to)
2208 {
2209
2210         ParIterator end = par_iterator_end();
2211         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2212                 (*it)->changeLanguage(params, from, to);
2213 }
2214
2215
2216 bool Buffer::isMultiLingual()
2217 {
2218         ParIterator end = par_iterator_end();
2219         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2220                 if ((*it)->isMultiLingual(params))
2221                         return true;
2222
2223         return false;
2224 }
2225
2226
2227 void Buffer::inset_iterator::setParagraph()
2228 {
2229         while (pit != pend) {
2230                 it = pit->insetlist.begin();
2231                 if (it != pit->insetlist.end())
2232                         return;
2233                 ++pit;
2234         }
2235 }
2236
2237
2238 Inset * Buffer::getInsetFromID(int id_arg) const
2239 {
2240         for (inset_iterator it = inset_const_iterator_begin();
2241                  it != inset_const_iterator_end(); ++it)
2242         {
2243                 if (it->id() == id_arg)
2244                         return &(*it);
2245                 Inset * in = it->getInsetFromID(id_arg);
2246                 if (in)
2247                         return in;
2248         }
2249         return 0;
2250 }
2251
2252
2253 Paragraph * Buffer::getParFromID(int id) const
2254 {
2255         if (id < 0)
2256                 return 0;
2257
2258         // why should we allow < 0 ??
2259         //lyx::Assert(id >= 0);
2260
2261         ParConstIterator it(par_iterator_begin());
2262         ParConstIterator end(par_iterator_end());
2263
2264         for (; it != end; ++it) {
2265                 // go on then, show me how to remove
2266                 // the cast
2267                 if ((*it)->id() == id) {
2268                         return const_cast<Paragraph*>(*it);
2269                 }
2270         }
2271
2272         return 0;
2273 }
2274
2275
2276 ParIterator Buffer::par_iterator_begin()
2277 {
2278         return ParIterator(&*(paragraphs.begin()));
2279 }
2280
2281
2282 ParIterator Buffer::par_iterator_end()
2283 {
2284         return ParIterator();
2285 }
2286
2287 ParConstIterator Buffer::par_iterator_begin() const
2288 {
2289         return ParConstIterator(&*(paragraphs.begin()));
2290 }
2291
2292
2293 ParConstIterator Buffer::par_iterator_end() const
2294 {
2295         return ParConstIterator();
2296 }
2297
2298
2299
2300 void Buffer::addUser(BufferView * u)
2301 {
2302         users = u;
2303 }
2304
2305
2306 void Buffer::delUser(BufferView *)
2307 {
2308         users = 0;
2309 }
2310
2311
2312 Language const * Buffer::getLanguage() const
2313 {
2314         return params.language;
2315 }
2316
2317
2318 bool Buffer::isClean() const
2319 {
2320         return lyx_clean;
2321 }
2322
2323
2324 bool Buffer::isBakClean() const
2325 {
2326         return bak_clean;
2327 }
2328
2329
2330 void Buffer::markClean() const
2331 {
2332         if (!lyx_clean) {
2333                 lyx_clean = true;
2334                 updateTitles();
2335         }
2336         // if the .lyx file has been saved, we don't need an
2337         // autosave
2338         bak_clean = true;
2339 }
2340
2341
2342 void Buffer::markBakClean()
2343 {
2344         bak_clean = true;
2345 }
2346
2347
2348 void Buffer::setUnnamed(bool flag)
2349 {
2350         unnamed = flag;
2351 }
2352
2353
2354 bool Buffer::isUnnamed()
2355 {
2356         return unnamed;
2357 }
2358
2359
2360 void Buffer::markDirty()
2361 {
2362         if (lyx_clean) {
2363                 lyx_clean = false;
2364                 updateTitles();
2365         }
2366         bak_clean = false;
2367
2368         DepClean::iterator it = dep_clean_.begin();
2369         DepClean::const_iterator const end = dep_clean_.end();
2370
2371         for (; it != end; ++it) {
2372                 it->second = false;
2373         }
2374 }
2375
2376
2377 string const & Buffer::fileName() const
2378 {
2379         return filename_;
2380 }
2381
2382
2383 string const & Buffer::filePath() const
2384 {
2385         return filepath_;
2386 }
2387
2388
2389 bool Buffer::isReadonly() const
2390 {
2391         return read_only;
2392 }
2393
2394
2395 BufferView * Buffer::getUser() const
2396 {
2397         return users;
2398 }
2399
2400
2401 void Buffer::setParentName(string const & name)
2402 {
2403         params.parentname = name;
2404 }
2405
2406
2407 Buffer::inset_iterator::inset_iterator()
2408         : pit(0), pend(0)
2409 {}
2410
2411
2412 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2413         : pit(p), pend(e)
2414 {
2415         setParagraph();
2416 }
2417
2418
2419 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2420 {
2421         if (pit != pend) {
2422                 ++it;
2423                 if (it == pit->insetlist.end()) {
2424                         ++pit;
2425                         setParagraph();
2426                 }
2427         }
2428         return *this;
2429 }
2430
2431
2432 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2433 {
2434         inset_iterator tmp = *this;
2435         ++*this;
2436         return tmp;
2437 }
2438
2439
2440 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2441 {
2442         return *it.getInset();
2443 }
2444
2445
2446 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2447 {
2448         return it.getInset();
2449 }
2450
2451
2452 Paragraph * Buffer::inset_iterator::getPar()
2453 {
2454         return &(*pit);
2455 }
2456
2457
2458 lyx::pos_type Buffer::inset_iterator::getPos() const
2459 {
2460         return it.getPos();
2461 }
2462
2463
2464 bool operator==(Buffer::inset_iterator const & iter1,
2465                 Buffer::inset_iterator const & iter2)
2466 {
2467         return iter1.pit == iter2.pit
2468                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2469 }
2470
2471
2472 bool operator!=(Buffer::inset_iterator const & iter1,
2473                 Buffer::inset_iterator const & iter2)
2474 {
2475         return !(iter1 == iter2);
2476 }