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