]> git.lyx.org Git - lyx.git/blob - src/buffer.C
d16d74ed22177300e34627147129d731f324a29a
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "exporter.h"
25 #include "format.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "insetiterator.h"
29 #include "language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
33 #include "lyxlex.h"
34 #include "lyxtext.h"
35 #include "lyxrc.h"
36 #include "lyxvc.h"
37 #include "lyx_main.h"
38 #include "messages.h"
39 #include "output.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_linuxdoc.h"
43 #include "paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "pariterator.h"
47 #include "sgml.h"
48 #include "texrow.h"
49 #include "undo.h"
50 #include "version.h"
51
52 #include "insets/insetbibitem.h"
53 #include "insets/insetbibtex.h"
54 #include "insets/insetinclude.h"
55 #include "insets/insettext.h"
56
57 #include "frontends/Alert.h"
58
59 #include "graphics/Previews.h"
60
61 #include "support/FileInfo.h"
62 #include "support/filetools.h"
63 #include "support/gzstream.h"
64 #include "support/lyxlib.h"
65 #include "support/os.h"
66 #include "support/path.h"
67 #include "support/textutils.h"
68 #include "support/tostr.h"
69 #include "support/std_sstream.h"
70
71 #include <boost/bind.hpp>
72
73 #include <iomanip>
74 #include <stack>
75
76 #include <utime.h>
77
78 using lyx::pos_type;
79 using lyx::par_type;
80
81 using lyx::support::AddName;
82 using lyx::support::atoi;
83 using lyx::support::bformat;
84 using lyx::support::ChangeExtension;
85 using lyx::support::cmd_ret;
86 using lyx::support::createBufferTmpDir;
87 using lyx::support::destroyDir;
88 using lyx::support::FileInfo;
89 using lyx::support::FileInfo;
90 using lyx::support::getExtFromContents;
91 using lyx::support::IsDirWriteable;
92 using lyx::support::IsFileWriteable;
93 using lyx::support::LibFileSearch;
94 using lyx::support::ltrim;
95 using lyx::support::MakeAbsPath;
96 using lyx::support::MakeDisplayPath;
97 using lyx::support::MakeLatexName;
98 using lyx::support::OnlyFilename;
99 using lyx::support::OnlyPath;
100 using lyx::support::Path;
101 using lyx::support::QuoteName;
102 using lyx::support::removeAutosaveFile;
103 using lyx::support::rename;
104 using lyx::support::RunCommand;
105 using lyx::support::split;
106 using lyx::support::strToInt;
107 using lyx::support::subst;
108 using lyx::support::tempName;
109 using lyx::support::trim;
110
111 namespace os = lyx::support::os;
112
113 using std::endl;
114 using std::for_each;
115 using std::make_pair;
116
117 using std::ifstream;
118 using std::ios;
119 using std::ostream;
120 using std::ostringstream;
121 using std::ofstream;
122 using std::pair;
123 using std::stack;
124 using std::vector;
125 using std::string;
126
127
128 // all these externs should eventually be removed.
129 extern BufferList bufferlist;
130
131 namespace {
132
133 const int LYX_FORMAT = 232;
134
135 } // namespace anon
136
137
138 typedef std::map<string, bool> DepClean;
139
140 struct Buffer::Impl
141 {
142         Impl(Buffer & parent, string const & file, bool readonly);
143
144         limited_stack<Undo> undostack;
145         limited_stack<Undo> redostack;
146         BufferParams params;
147         LyXVC lyxvc;
148         string temppath;
149         TexRow texrow;
150
151         /// need to regenerate .tex?
152         DepClean dep_clean;
153
154         /// is save needed?
155         mutable bool lyx_clean;
156
157         /// is autosave needed?
158         mutable bool bak_clean;
159
160         /// is this a unnamed file (New...)?
161         bool unnamed;
162
163         /// buffer is r/o
164         bool read_only;
165
166         /// name of the file the buffer is associated with.
167         string filename;
168
169         /// The path to the document file.
170         string filepath;
171
172         boost::scoped_ptr<Messages> messages;
173
174         /** Set to true only when the file is fully loaded.
175          *  Used to prevent the premature generation of previews
176          *  and by the citation inset.
177          */
178         bool file_fully_loaded;
179
180         /// our LyXText that should be wrapped in an InsetText
181         InsetText inset;
182 };
183
184
185 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
186         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
187           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
188                 inset(params)
189 {
190         lyxvc.buffer(&parent);
191         temppath = createBufferTmpDir();
192         // FIXME: And now do something if temppath == string(), because we
193         // assume from now on that temppath points to a valid temp dir.
194         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
195 }
196
197
198 Buffer::Buffer(string const & file, bool ronly)
199         : pimpl_(new Impl(*this, file, ronly))
200 {
201         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
202 }
203
204
205 Buffer::~Buffer()
206 {
207         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
208         // here the buffer should take care that it is
209         // saved properly, before it goes into the void.
210
211         closing();
212
213         if (!temppath().empty() && destroyDir(temppath()) != 0) {
214                 Alert::warning(_("Could not remove temporary directory"),
215                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
216         }
217
218         // Remove any previewed LaTeX snippets associated with this buffer.
219         lyx::graphics::Previews::get().removeLoader(*this);
220 }
221
222
223 LyXText & Buffer::text() const
224 {
225         return const_cast<LyXText &>(pimpl_->inset.text_);
226 }
227
228
229 InsetBase & Buffer::inset() const
230 {
231         return const_cast<InsetText &>(pimpl_->inset);
232 }
233
234
235 limited_stack<Undo> & Buffer::undostack()
236 {
237         return pimpl_->undostack;
238 }
239
240
241 limited_stack<Undo> const & Buffer::undostack() const
242 {
243         return pimpl_->undostack;
244 }
245
246
247 limited_stack<Undo> & Buffer::redostack()
248 {
249         return pimpl_->redostack;
250 }
251
252
253 limited_stack<Undo> const & Buffer::redostack() const
254 {
255         return pimpl_->redostack;
256 }
257
258
259 BufferParams & Buffer::params()
260 {
261         return pimpl_->params;
262 }
263
264
265 BufferParams const & Buffer::params() const
266 {
267         return pimpl_->params;
268 }
269
270
271 ParagraphList & Buffer::paragraphs()
272 {
273         return text().paragraphs();
274 }
275
276
277 ParagraphList const & Buffer::paragraphs() const
278 {
279         return text().paragraphs();
280 }
281
282
283 LyXVC & Buffer::lyxvc()
284 {
285         return pimpl_->lyxvc;
286 }
287
288
289 LyXVC const & Buffer::lyxvc() const
290 {
291         return pimpl_->lyxvc;
292 }
293
294
295 string const & Buffer::temppath() const
296 {
297         return pimpl_->temppath;
298 }
299
300
301 TexRow & Buffer::texrow()
302 {
303         return pimpl_->texrow;
304 }
305
306
307 TexRow const & Buffer::texrow() const
308 {
309         return pimpl_->texrow;
310 }
311
312
313 string const Buffer::getLatexName(bool no_path) const
314 {
315         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
316         return no_path ? OnlyFilename(name) : name;
317 }
318
319
320 pair<Buffer::LogType, string> const Buffer::getLogName() const
321 {
322         string const filename = getLatexName(false);
323
324         if (filename.empty())
325                 return make_pair(Buffer::latexlog, string());
326
327         string const path = temppath();
328
329         string const fname = AddName(path,
330                                      OnlyFilename(ChangeExtension(filename,
331                                                                   ".log")));
332         string const bname =
333                 AddName(path, OnlyFilename(
334                         ChangeExtension(filename,
335                                         formats.extension("literate") + ".out")));
336
337         // If no Latex log or Build log is newer, show Build log
338
339         FileInfo const f_fi(fname);
340         FileInfo const b_fi(bname);
341
342         if (b_fi.exist() &&
343             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
344                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
345                 return make_pair(Buffer::buildlog, bname);
346         }
347         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
348         return make_pair(Buffer::latexlog, fname);
349 }
350
351
352 void Buffer::setReadonly(bool flag)
353 {
354         if (pimpl_->read_only != flag) {
355                 pimpl_->read_only = flag;
356                 readonly(flag);
357         }
358 }
359
360
361 void Buffer::setFileName(string const & newfile)
362 {
363         pimpl_->filename = MakeAbsPath(newfile);
364         pimpl_->filepath = OnlyPath(pimpl_->filename);
365         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
366         updateTitles();
367 }
368
369
370 // We'll remove this later. (Lgb)
371 namespace {
372
373 void unknownClass(string const & unknown)
374 {
375         Alert::warning(_("Unknown document class"),
376                 bformat(_("Using the default document class, because the "
377                         "class %1$s is unknown."), unknown));
378 }
379
380 } // anon
381
382
383 int Buffer::readHeader(LyXLex & lex)
384 {
385         int unknown_tokens = 0;
386
387         while (lex.isOK()) {
388                 lex.nextToken();
389                 string const token = lex.getString();
390
391                 if (token.empty())
392                         continue;
393
394                 if (token == "\\end_header")
395                         break;
396
397                 lyxerr[Debug::PARSER] << "Handling header token: `"
398                                       << token << '\'' << endl;
399
400
401                 string unknown = params().readToken(lex, token);
402                 if (!unknown.empty()) {
403                         if (unknown[0] != '\\') {
404                                 unknownClass(unknown);
405                         } else {
406                                 ++unknown_tokens;
407                                 string const s = bformat(_("Unknown token: "
408                                                            "%1$s %2$s\n"),
409                                                          token,
410                                                          lex.getString());
411                                 error(ErrorItem(_("Header error"), s,
412                                                 -1, 0, 0));
413                         }
414                 }
415         }
416         return unknown_tokens;
417 }
418
419
420 // Uwe C. Schroeder
421 // changed to be public and have one parameter
422 // Returns false if "\end_document" is not read (Asger)
423 bool Buffer::readBody(LyXLex & lex)
424 {
425         if (paragraphs().empty()) {
426                 readHeader(lex);
427                 if (!params().getLyXTextClass().load()) {
428                         string theclass = params().getLyXTextClass().name();
429                         Alert::error(_("Can't load document class"), bformat(
430                                         "Using the default document class, because the "
431                                         " class %1$s could not be loaded.", theclass));
432                         params().textclass = 0;
433                 }
434         } else {
435                 // We don't want to adopt the parameters from the
436                 // document we insert, so read them into a temporary buffer
437                 // and then discard it
438
439                 Buffer tmpbuf("", false);
440                 tmpbuf.readHeader(lex);
441         }
442
443         return text().read(*this, lex);
444 }
445
446
447 // needed to insert the selection
448 void Buffer::insertStringAsLines(ParagraphList & pars,
449         par_type & par, pos_type & pos,
450         LyXFont const & fn, string const & str)
451 {
452         LyXLayout_ptr const & layout = pars[par].layout();
453
454         LyXFont font = fn;
455
456         pars[par].checkInsertChar(font);
457         // insert the string, don't insert doublespace
458         bool space_inserted = true;
459         bool autobreakrows = pars[par].autoBreakRows();
460         for (string::const_iterator cit = str.begin();
461             cit != str.end(); ++cit) {
462                 if (*cit == '\n') {
463                         if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
464                                 breakParagraph(params(), paragraphs(), par, pos,
465                                                layout->isEnvironment());
466                                 ++par;
467                                 pos = 0;
468                                 space_inserted = true;
469                         } else {
470                                 continue;
471                         }
472                         // do not insert consecutive spaces if !free_spacing
473                 } else if ((*cit == ' ' || *cit == '\t') &&
474                            space_inserted && !pars[par].isFreeSpacing()) {
475                         continue;
476                 } else if (*cit == '\t') {
477                         if (!pars[par].isFreeSpacing()) {
478                                 // tabs are like spaces here
479                                 pars[par].insertChar(pos, ' ', font);
480                                 ++pos;
481                                 space_inserted = true;
482                         } else {
483                                 const pos_type n = 8 - pos % 8;
484                                 for (pos_type i = 0; i < n; ++i) {
485                                         pars[par].insertChar(pos, ' ', font);
486                                         ++pos;
487                                 }
488                                 space_inserted = true;
489                         }
490                 } else if (!IsPrintable(*cit)) {
491                         // Ignore unprintables
492                         continue;
493                 } else {
494                         // just insert the character
495                         pars[par].insertChar(pos, *cit, font);
496                         ++pos;
497                         space_inserted = (*cit == ' ');
498                 }
499
500         }
501 }
502
503
504 bool Buffer::readFile(string const & filename)
505 {
506         // Check if the file is compressed.
507         string const format = getExtFromContents(filename);
508         if (format == "gzip" || format == "zip" || format == "compress") {
509                 params().compressed = true;
510         }
511
512         // remove dummy empty par
513         paragraphs().clear();
514         bool ret = readFile(filename, paragraphs().size());
515
516         // After we have read a file, we must ensure that the buffer
517         // language is set and used in the gui.
518         // If you know of a better place to put this, please tell me. (Lgb)
519         updateDocLang(params().language);
520
521         return ret;
522 }
523
524
525 bool Buffer::readFile(string const & filename, par_type pit)
526 {
527         LyXLex lex(0, 0);
528         lex.setFile(filename);
529         return readFile(lex, filename, pit);
530 }
531
532
533 bool Buffer::fully_loaded() const
534 {
535         return pimpl_->file_fully_loaded;
536 }
537
538
539 void Buffer::fully_loaded(bool value)
540 {
541         pimpl_->file_fully_loaded = value;
542 }
543
544
545 bool Buffer::readFile(LyXLex & lex, string const & filename, par_type pit)
546 {
547         BOOST_ASSERT(!filename.empty());
548
549         if (!lex.isOK()) {
550                 Alert::error(_("Document could not be read"),
551                              bformat(_("%1$s could not be read."), filename));
552                 return false;
553         }
554
555         lex.next();
556         string const token(lex.getString());
557
558         if (!lex.isOK()) {
559                 Alert::error(_("Document could not be read"),
560                              bformat(_("%1$s could not be read."), filename));
561                 return false;
562         }
563
564         // the first token _must_ be...
565         if (token != "\\lyxformat") {
566                 lyxerr << "Token: " << token << endl;
567
568                 Alert::error(_("Document format failure"),
569                              bformat(_("%1$s is not a LyX document."),
570                                        filename));
571                 return false;
572         }
573
574         lex.eatLine();
575         string tmp_format = lex.getString();
576         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
577         // if present remove ".," from string.
578         string::size_type dot = tmp_format.find_first_of(".,");
579         //lyxerr << "           dot found at " << dot << endl;
580         if (dot != string::npos)
581                         tmp_format.erase(dot, 1);
582         int file_format = strToInt(tmp_format);
583         //lyxerr << "format: " << file_format << endl;
584
585         if (file_format > LYX_FORMAT) {
586                 Alert::warning(_("Document format failure"),
587                                bformat(_("%1$s was created with a newer"
588                                          " version of LyX. This is likely to"
589                                          " cause problems."),
590                                          filename));
591         } else if (file_format < LYX_FORMAT) {
592                 string const tmpfile = tempName();
593                 if (tmpfile.empty()) {
594                         Alert::error(_("Conversion failed"),
595                                      bformat(_("%1$s is from an earlier"
596                                               " version of LyX, but a temporary"
597                                               " file for converting it could"
598                                               " not be created."),
599                                               filename));
600                         return false;
601                 }
602                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
603                 if (command.empty()) {
604                         Alert::error(_("Conversion script not found"),
605                                      bformat(_("%1$s is from an earlier"
606                                                " version of LyX, but the"
607                                                " conversion script lyx2lyx"
608                                                " could not be found."),
609                                                filename));
610                         return false;
611                 }
612                 command += " -t"
613                         + tostr(LYX_FORMAT)
614                         + " -o " + tmpfile + ' '
615                         + QuoteName(filename);
616                 lyxerr[Debug::INFO] << "Running '"
617                                     << command << '\''
618                                     << endl;
619                 cmd_ret const ret = RunCommand(command);
620                 if (ret.first != 0) {
621                         Alert::error(_("Conversion script failed"),
622                                      bformat(_("%1$s is from an earlier version"
623                                               " of LyX, but the lyx2lyx script"
624                                               " failed to convert it."),
625                                               filename));
626                         return false;
627                 } else {
628                         bool ret = readFile(tmpfile, pit);
629                         // Do stuff with tmpfile name and buffer name here.
630                         return ret;
631                 }
632
633         }
634
635         bool the_end = readBody(lex);
636         params().setPaperStuff();
637
638 #ifdef WITH_WARNINGS
639 #warning Look here!
640 #endif
641 #if 0
642         if (token == "\\end_document")
643                 the_end_read = true;
644
645         if (!the_end) {
646                 Alert::error(_("Document format failure"),
647                              bformat(_("%1$s ended unexpectedly, which means"
648                                        " that it is probably corrupted."),
649                                        filename));
650         }
651 #endif
652         pimpl_->file_fully_loaded = true;
653         return true;
654 }
655
656
657 // Should probably be moved to somewhere else: BufferView? LyXView?
658 bool Buffer::save() const
659 {
660         // We don't need autosaves in the immediate future. (Asger)
661         resetAutosaveTimers();
662
663         // make a backup
664         string s;
665         if (lyxrc.make_backup) {
666                 s = fileName() + '~';
667                 if (!lyxrc.backupdir_path.empty())
668                         s = AddName(lyxrc.backupdir_path,
669                                     subst(os::slashify_path(s),'/','!'));
670
671                 // Rename is the wrong way of making a backup,
672                 // this is the correct way.
673                 /* truss cp fil fil2:
674                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
675                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
676                    open("LyXVC.lyx", O_RDONLY)                     = 3
677                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
678                    fstat(4, 0xEFFFF508)                            = 0
679                    fstat(3, 0xEFFFF508)                            = 0
680                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
681                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
682                    read(3, 0xEFFFD4A0, 8192)                       = 0
683                    close(4)                                        = 0
684                    close(3)                                        = 0
685                    chmod("LyXVC3.lyx", 0100644)                    = 0
686                    lseek(0, 0, SEEK_CUR)                           = 46440
687                    _exit(0)
688                 */
689
690                 // Should probably have some more error checking here.
691                 // Doing it this way, also makes the inodes stay the same.
692                 // This is still not a very good solution, in particular we
693                 // might loose the owner of the backup.
694                 FileInfo finfo(fileName());
695                 if (finfo.exist()) {
696                         mode_t fmode = finfo.getMode();
697                         struct utimbuf times = {
698                                 finfo.getAccessTime(),
699                                 finfo.getModificationTime() };
700
701                         ifstream ifs(fileName().c_str());
702                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
703                         if (ifs && ofs) {
704                                 ofs << ifs.rdbuf();
705                                 ifs.close();
706                                 ofs.close();
707                                 ::chmod(s.c_str(), fmode);
708
709                                 if (::utime(s.c_str(), &times)) {
710                                         lyxerr << "utime error." << endl;
711                                 }
712                         } else {
713                                 lyxerr << "LyX was not able to make "
714                                         "backup copy. Beware." << endl;
715                         }
716                 }
717         }
718
719         if (writeFile(fileName())) {
720                 markClean();
721                 removeAutosaveFile(fileName());
722         } else {
723                 // Saving failed, so backup is not backup
724                 if (lyxrc.make_backup)
725                         rename(s, fileName());
726                 return false;
727         }
728         return true;
729 }
730
731
732 bool Buffer::writeFile(string const & fname) const
733 {
734         if (pimpl_->read_only && fname == fileName())
735                 return false;
736
737         FileInfo finfo(fname);
738         if (finfo.exist() && !finfo.writable())
739                 return false;
740
741         bool retval;
742
743         if (params().compressed) {
744                 gz::ogzstream ofs(fname.c_str());
745                 if (!ofs)
746                         return false;
747
748                 retval = do_writeFile(ofs);
749
750         } else {
751                 ofstream ofs(fname.c_str());
752                 if (!ofs)
753                         return false;
754
755                 retval = do_writeFile(ofs);
756         }
757
758         return retval;
759 }
760
761
762 bool Buffer::do_writeFile(ostream & ofs) const
763 {
764 #ifdef HAVE_LOCALE
765         // Use the standard "C" locale for file output.
766         ofs.imbue(std::locale::classic());
767 #endif
768
769         // The top of the file should not be written by params().
770
771         // write out a comment in the top of the file
772         ofs << "#LyX " << lyx_version
773             << " created this file. For more info see http://www.lyx.org/\n"
774             << "\\lyxformat " << LYX_FORMAT << "\n";
775
776         // now write out the buffer parameters.
777         params().writeFile(ofs);
778
779         ofs << "\\end_header\n";
780
781         // write the text
782         text().write(*this, ofs);
783
784         // Write marker that shows file is complete
785         ofs << "\n\\end_document" << endl;
786
787         // Shouldn't really be needed....
788         //ofs.close();
789
790         // how to check if close went ok?
791         // Following is an attempt... (BE 20001011)
792
793         // good() returns false if any error occured, including some
794         //        formatting error.
795         // bad()  returns true if something bad happened in the buffer,
796         //        which should include file system full errors.
797
798         bool status = true;
799         if (!ofs) {
800                 status = false;
801                 lyxerr << "File was not closed properly." << endl;
802         }
803
804         return status;
805 }
806
807
808 void Buffer::makeLaTeXFile(string const & fname,
809                            string const & original_path,
810                            OutputParams const & runparams,
811                            bool output_preamble, bool output_body)
812 {
813         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
814
815         ofstream ofs;
816         if (!openFileWrite(ofs, fname))
817                 return;
818
819         makeLaTeXFile(ofs, original_path,
820                       runparams, output_preamble, output_body);
821
822         ofs.close();
823         if (ofs.fail())
824                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
825 }
826
827
828 void Buffer::makeLaTeXFile(ostream & os,
829                            string const & original_path,
830                            OutputParams const & runparams_in,
831                            bool output_preamble, bool output_body)
832 {
833         OutputParams runparams = runparams_in;
834
835         // validate the buffer.
836         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
837         LaTeXFeatures features(*this, params(), runparams.nice);
838         validate(features);
839         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
840
841         texrow().reset();
842         // The starting paragraph of the coming rows is the
843         // first paragraph of the document. (Asger)
844         texrow().start(paragraphs().begin()->id(), 0);
845
846         if (output_preamble && runparams.nice) {
847                 os << "%% LyX " << lyx_version << " created this file.  "
848                         "For more info, see http://www.lyx.org/.\n"
849                         "%% Do not edit unless you really know what "
850                         "you are doing.\n";
851                 texrow().newline();
852                 texrow().newline();
853         }
854         lyxerr[Debug::INFO] << "lyx header finished" << endl;
855         // There are a few differences between nice LaTeX and usual files:
856         // usual is \batchmode and has a
857         // special input@path to allow the including of figures
858         // with either \input or \includegraphics (what figinsets do).
859         // input@path is set when the actual parameter
860         // original_path is set. This is done for usual tex-file, but not
861         // for nice-latex-file. (Matthias 250696)
862         // Note that input@path is only needed for something the user does
863         // in the preamble, included .tex files or ERT, files included by
864         // LyX work without it.
865         if (output_preamble) {
866                 if (!runparams.nice) {
867                         // code for usual, NOT nice-latex-file
868                         os << "\\batchmode\n"; // changed
869                         // from \nonstopmode
870                         texrow().newline();
871                 }
872                 if (!original_path.empty()) {
873                         string inputpath = os::external_path(original_path);
874                         subst(inputpath, "~", "\\string~");
875                         os << "\\makeatletter\n"
876                             << "\\def\\input@path{{"
877                             << inputpath << "/}}\n"
878                             << "\\makeatother\n";
879                         texrow().newline();
880                         texrow().newline();
881                         texrow().newline();
882                 }
883
884                 // Write the preamble
885                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
886
887                 if (!output_body)
888                         return;
889
890                 // make the body.
891                 os << "\\begin{document}\n";
892                 texrow().newline();
893         } // output_preamble
894         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
895
896         if (!lyxrc.language_auto_begin) {
897                 os << subst(lyxrc.language_command_begin, "$$lang",
898                              params().language->babel())
899                     << endl;
900                 texrow().newline();
901         }
902
903         // if we are doing a real file with body, even if this is the
904         // child of some other buffer, let's cut the link here.
905         // This happens for example if only a child document is printed.
906         string save_parentname;
907         if (output_preamble) {
908                 save_parentname = params().parentname;
909                 params().parentname.erase();
910         }
911
912         // the real stuff
913         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
914
915         // Restore the parenthood if needed
916         if (output_preamble)
917                 params().parentname = save_parentname;
918
919         // add this just in case after all the paragraphs
920         os << endl;
921         texrow().newline();
922
923         if (!lyxrc.language_auto_end) {
924                 os << subst(lyxrc.language_command_end, "$$lang",
925                              params().language->babel())
926                     << endl;
927                 texrow().newline();
928         }
929
930         if (output_preamble) {
931                 os << "\\end{document}\n";
932                 texrow().newline();
933
934                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
935         } else {
936                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
937                                      << endl;
938         }
939
940         // Just to be sure. (Asger)
941         texrow().newline();
942
943         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
944         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
945                             << '.' << endl;
946 }
947
948
949 bool Buffer::isLatex() const
950 {
951         return params().getLyXTextClass().outputType() == LATEX;
952 }
953
954
955 bool Buffer::isLinuxDoc() const
956 {
957         return params().getLyXTextClass().outputType() == LINUXDOC;
958 }
959
960
961 bool Buffer::isLiterate() const
962 {
963         return params().getLyXTextClass().outputType() == LITERATE;
964 }
965
966
967 bool Buffer::isDocBook() const
968 {
969         return params().getLyXTextClass().outputType() == DOCBOOK;
970 }
971
972
973 bool Buffer::isSGML() const
974 {
975         LyXTextClass const & tclass = params().getLyXTextClass();
976
977         return tclass.outputType() == LINUXDOC ||
978                tclass.outputType() == DOCBOOK;
979 }
980
981
982 void Buffer::makeLinuxDocFile(string const & fname,
983                               OutputParams const & runparams,
984                               bool body_only)
985 {
986         ofstream ofs;
987         if (!openFileWrite(ofs, fname))
988                 return;
989
990         LaTeXFeatures features(*this, params(), runparams.nice);
991         validate(features);
992
993         texrow().reset();
994
995         LyXTextClass const & tclass = params().getLyXTextClass();
996
997         string top_element = tclass.latexname();
998
999         if (!body_only) {
1000                 ofs << tclass.class_header();
1001
1002                 string preamble = params().preamble;
1003                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1004                          : fname;
1005                 preamble += features.getIncludedFiles(name);
1006                 preamble += features.getLyXSGMLEntities();
1007
1008                 if (!preamble.empty()) {
1009                         ofs << " [ " << preamble << " ]";
1010                 }
1011                 ofs << ">\n\n";
1012
1013                 if (params().options.empty())
1014                         sgml::openTag(ofs, 0, false, top_element);
1015                 else {
1016                         string top = top_element;
1017                         top += ' ';
1018                         top += params().options;
1019                         sgml::openTag(ofs, 0, false, top);
1020                 }
1021         }
1022
1023         ofs << "<!-- LyX "  << lyx_version
1024             << " created this file. For more info see http://www.lyx.org/"
1025             << " -->\n";
1026
1027         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1028
1029         if (!body_only) {
1030                 ofs << "\n\n";
1031                 sgml::closeTag(ofs, 0, false, top_element);
1032         }
1033
1034         ofs.close();
1035         if (ofs.fail())
1036                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1037 }
1038
1039
1040 void Buffer::makeDocBookFile(string const & fname,
1041                              OutputParams const & runparams,
1042                              bool only_body)
1043 {
1044         ofstream ofs;
1045         if (!openFileWrite(ofs, fname))
1046                 return;
1047
1048         LaTeXFeatures features(*this, params(), runparams.nice);
1049         validate(features);
1050
1051         texrow().reset();
1052
1053         LyXTextClass const & tclass = params().getLyXTextClass();
1054         string top_element = tclass.latexname();
1055
1056         if (!only_body) {
1057                 ofs << subst(tclass.class_header(), "#", top_element);
1058
1059                 string preamble = params().preamble;
1060                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1061                          : fname;
1062                 preamble += features.getIncludedFiles(name);
1063                 preamble += features.getLyXSGMLEntities();
1064
1065                 if (!preamble.empty()) {
1066                         ofs << "\n [ " << preamble << " ]";
1067                 }
1068                 ofs << ">\n\n";
1069         }
1070
1071         string top = top_element;
1072         top += " lang=\"";
1073         top += params().language->code();
1074         top += '"';
1075
1076         if (!params().options.empty()) {
1077                 top += ' ';
1078                 top += params().options;
1079         }
1080         sgml::openTag(ofs, 0, false, top);
1081
1082         ofs << "<!-- SGML/XML file was created by LyX " << lyx_version
1083             << "\n  See http://www.lyx.org/ for more information -->\n";
1084
1085         params().getLyXTextClass().counters().reset();
1086         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1087
1088         ofs << "\n\n";
1089         sgml::closeTag(ofs, 0, false, top_element);
1090
1091         ofs.close();
1092         if (ofs.fail())
1093                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1094 }
1095
1096
1097 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1098 // Other flags: -wall -v0 -x
1099 int Buffer::runChktex()
1100 {
1101         busy(true);
1102
1103         // get LaTeX-Filename
1104         string const name = getLatexName();
1105         string const path = temppath();
1106         string const org_path = filePath();
1107
1108         Path p(path); // path to LaTeX file
1109         message(_("Running chktex..."));
1110
1111         // Generate the LaTeX file if neccessary
1112         OutputParams runparams;
1113         runparams.flavor = OutputParams::LATEX;
1114         runparams.nice = false;
1115         makeLaTeXFile(name, org_path, runparams);
1116
1117         TeXErrors terr;
1118         Chktex chktex(lyxrc.chktex_command, name, filePath());
1119         int res = chktex.run(terr); // run chktex
1120
1121         if (res == -1) {
1122                 Alert::error(_("chktex failure"),
1123                              _("Could not run chktex successfully."));
1124         } else if (res > 0) {
1125                 // Insert all errors as errors boxes
1126                 bufferErrors(*this, terr);
1127         }
1128
1129         busy(false);
1130
1131         return res;
1132 }
1133
1134
1135 void Buffer::validate(LaTeXFeatures & features) const
1136 {
1137         LyXTextClass const & tclass = params().getLyXTextClass();
1138
1139         if (params().tracking_changes) {
1140                 features.require("dvipost");
1141                 features.require("color");
1142         }
1143
1144         // AMS Style is at document level
1145         if (params().use_amsmath == BufferParams::AMS_ON
1146             || tclass.provides(LyXTextClass::amsmath))
1147                 features.require("amsmath");
1148
1149         for_each(paragraphs().begin(), paragraphs().end(),
1150                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1151
1152         // the bullet shapes are buffer level not paragraph level
1153         // so they are tested here
1154         for (int i = 0; i < 4; ++i) {
1155                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1156                         int const font = params().user_defined_bullet(i).getFont();
1157                         if (font == 0) {
1158                                 int const c = params()
1159                                         .user_defined_bullet(i)
1160                                         .getCharacter();
1161                                 if (c == 16
1162                                    || c == 17
1163                                    || c == 25
1164                                    || c == 26
1165                                    || c == 31) {
1166                                         features.require("latexsym");
1167                                 }
1168                         } else if (font == 1) {
1169                                 features.require("amssymb");
1170                         } else if ((font >= 2 && font <= 5)) {
1171                                 features.require("pifont");
1172                         }
1173                 }
1174         }
1175
1176         if (lyxerr.debugging(Debug::LATEX)) {
1177                 features.showStruct();
1178         }
1179 }
1180
1181
1182 void Buffer::getLabelList(std::vector<string> & list) const
1183 {
1184         /// if this is a child document and the parent is already loaded
1185         /// Use the parent's list instead  [ale990407]
1186         Buffer const * tmp = getMasterBuffer();
1187         if (!tmp) {
1188                 lyxerr << "getMasterBuffer() failed!" << endl;
1189                 BOOST_ASSERT(tmp);
1190         }
1191         if (tmp != this) {
1192                 tmp->getLabelList(list);
1193                 return;
1194         }
1195
1196         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1197                 it.nextInset()->getLabelList(*this, list);
1198 }
1199
1200
1201 // This is also a buffer property (ale)
1202 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1203         const
1204 {
1205         /// if this is a child document and the parent is already loaded
1206         /// use the parent's list instead  [ale990412]
1207         Buffer const * tmp = getMasterBuffer();
1208         BOOST_ASSERT(tmp);
1209         if (tmp != this) {
1210                 tmp->fillWithBibKeys(keys);
1211                 return;
1212         }
1213
1214         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1215                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1216                         InsetBibtex const & inset =
1217                                 dynamic_cast<InsetBibtex const &>(*it);
1218                         inset.fillWithBibKeys(*this, keys);
1219                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1220                         InsetInclude const & inset =
1221                                 dynamic_cast<InsetInclude const &>(*it);
1222                         inset.fillWithBibKeys(*this, keys);
1223                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1224                         InsetBibitem const & inset =
1225                                 dynamic_cast<InsetBibitem const &>(*it);
1226                         string const key = inset.getContents();
1227                         string const opt = inset.getOptions();
1228                         string const ref; // = pit->asString(this, false);
1229                         string const info = opt + "TheBibliographyRef" + ref;
1230                         keys.push_back(pair<string, string>(key, info));
1231                 }
1232         }
1233 }
1234
1235
1236 bool Buffer::isDepClean(string const & name) const
1237 {
1238         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1239         if (it == pimpl_->dep_clean.end())
1240                 return true;
1241         return it->second;
1242 }
1243
1244
1245 void Buffer::markDepClean(string const & name)
1246 {
1247         pimpl_->dep_clean[name] = true;
1248 }
1249
1250
1251 bool Buffer::dispatch(string const & command, bool * result)
1252 {
1253         return dispatch(lyxaction.lookupFunc(command), result);
1254 }
1255
1256
1257 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1258 {
1259         bool dispatched = true;
1260
1261         switch (func.action) {
1262                 case LFUN_EXPORT: {
1263                         bool const tmp = Exporter::Export(this, func.argument, false);
1264                         if (result)
1265                                 *result = tmp;
1266                         break;
1267                 }
1268
1269                 default:
1270                         dispatched = false;
1271         }
1272         return dispatched;
1273 }
1274
1275
1276 void Buffer::changeLanguage(Language const * from, Language const * to)
1277 {
1278         lyxerr << "Changing Language!" << endl;
1279
1280         // Take care of l10n/i18n
1281         updateDocLang(to);
1282
1283         ParIterator end = par_iterator_end();
1284         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1285                 it->changeLanguage(params(), from, to);
1286 }
1287
1288
1289 void Buffer::updateDocLang(Language const * nlang)
1290 {
1291         pimpl_->messages.reset(new Messages(nlang->code()));
1292 }
1293
1294
1295 bool Buffer::isMultiLingual() const
1296 {
1297         ParConstIterator end = par_iterator_end();
1298         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1299                 if (it->isMultiLingual(params()))
1300                         return true;
1301
1302         return false;
1303 }
1304
1305
1306 ParIterator Buffer::getParFromID(int id) const
1307 {
1308         ParConstIterator it = par_iterator_begin();
1309         ParConstIterator end = par_iterator_end();
1310
1311         if (id < 0) {
1312                 // John says this is called with id == -1 from undo
1313                 lyxerr << "getParFromID(), id: " << id << endl;
1314                 return end;
1315         }
1316
1317         for (; it != end; ++it)
1318                 if (it->id() == id)
1319                         return it;
1320
1321         return end;
1322 }
1323
1324
1325 bool Buffer::hasParWithID(int id) const
1326 {
1327         ParConstIterator it = par_iterator_begin();
1328         ParConstIterator end = par_iterator_end();
1329
1330         if (id < 0) {
1331                 // John says this is called with id == -1 from undo
1332                 lyxerr << "hasParWithID(), id: " << id << endl;
1333                 return 0;
1334         }
1335
1336         for (; it != end; ++it)
1337                 if (it->id() == id)
1338                         return true;
1339
1340         return false;
1341 }
1342
1343
1344 ParIterator Buffer::par_iterator_begin()
1345 {
1346         return ::par_iterator_begin(inset());
1347 }
1348
1349
1350 ParIterator Buffer::par_iterator_end()
1351 {
1352         return ::par_iterator_end(inset());
1353 }
1354
1355
1356 ParConstIterator Buffer::par_iterator_begin() const
1357 {
1358         return ::par_const_iterator_begin(inset());
1359 }
1360
1361
1362 ParConstIterator Buffer::par_iterator_end() const
1363 {
1364         return ::par_const_iterator_end(inset());
1365 }
1366
1367
1368 Language const * Buffer::getLanguage() const
1369 {
1370         return params().language;
1371 }
1372
1373
1374 string const Buffer::B_(string const & l10n) const
1375 {
1376         if (pimpl_->messages.get()) {
1377                 return pimpl_->messages->get(l10n);
1378         }
1379
1380         return _(l10n);
1381 }
1382
1383
1384 bool Buffer::isClean() const
1385 {
1386         return pimpl_->lyx_clean;
1387 }
1388
1389
1390 bool Buffer::isBakClean() const
1391 {
1392         return pimpl_->bak_clean;
1393 }
1394
1395
1396 void Buffer::markClean() const
1397 {
1398         if (!pimpl_->lyx_clean) {
1399                 pimpl_->lyx_clean = true;
1400                 updateTitles();
1401         }
1402         // if the .lyx file has been saved, we don't need an
1403         // autosave
1404         pimpl_->bak_clean = true;
1405 }
1406
1407
1408 void Buffer::markBakClean()
1409 {
1410         pimpl_->bak_clean = true;
1411 }
1412
1413
1414 void Buffer::setUnnamed(bool flag)
1415 {
1416         pimpl_->unnamed = flag;
1417 }
1418
1419
1420 bool Buffer::isUnnamed() const
1421 {
1422         return pimpl_->unnamed;
1423 }
1424
1425
1426 void Buffer::markDirty()
1427 {
1428         if (pimpl_->lyx_clean) {
1429                 pimpl_->lyx_clean = false;
1430                 updateTitles();
1431         }
1432         pimpl_->bak_clean = false;
1433
1434         DepClean::iterator it = pimpl_->dep_clean.begin();
1435         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1436
1437         for (; it != end; ++it) {
1438                 it->second = false;
1439         }
1440 }
1441
1442
1443 string const & Buffer::fileName() const
1444 {
1445         return pimpl_->filename;
1446 }
1447
1448
1449 string const & Buffer::filePath() const
1450 {
1451         return pimpl_->filepath;
1452 }
1453
1454
1455 bool Buffer::isReadonly() const
1456 {
1457         return pimpl_->read_only;
1458 }
1459
1460
1461 void Buffer::setParentName(string const & name)
1462 {
1463         params().parentname = name;
1464 }
1465
1466
1467 Buffer const * Buffer::getMasterBuffer() const
1468 {
1469         if (!params().parentname.empty()
1470             && bufferlist.exists(params().parentname)) {
1471                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1472                 if (buf)
1473                         return buf->getMasterBuffer();
1474         }
1475
1476         return this;
1477 }