]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
68f80cc82eea33a491394aada325fec6e39692fa
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19 #include "support/SignalSlot.h"
20
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BufferParams;
28 class EmbeddedFileList;
29 class DocIterator;
30 class ErrorItem;
31 class ErrorList;
32 class FuncRequest;
33 class Inset;
34 class InsetRef;
35 class InsetLabel;
36 class Font;
37 class Format;
38 class Lexer;
39 class LyXRC;
40 class Text;
41 class LyXVC;
42 class LaTeXFeatures;
43 class Language;
44 class MacroData;
45 class MacroNameSet;
46 class MacroSet;
47 class OutputParams;
48 class Paragraph;
49 class ParConstIterator;
50 class ParIterator;
51 class ParagraphList;
52 class TeXErrors;
53 class TexRow;
54 class TocBackend;
55 class Undo;
56
57 namespace frontend {
58 class GuiBufferDelegate;
59 class WorkAreaManager;
60 }
61
62 namespace support {
63 class FileName;
64 }
65
66 /** The buffer object.
67  * This is the buffer object. It contains all the informations about
68  * a document loaded into LyX.
69  * The buffer object owns the Text (wrapped in an InsetText), which
70  * contains the individual paragraphs of the document.
71  *
72  *
73  * I am not sure if the class is complete or
74  * minimal, probably not.
75  * \author Lars Gullik Bjønnes
76  */
77 class Buffer {
78 public:
79         /// What type of log will \c getLogName() return?
80         enum LogType {
81                 latexlog, ///< LaTeX log
82                 buildlog  ///< Literate build log
83         };
84
85         /// Result of \c readFile()
86         enum ReadStatus {
87                 failure, ///< The file could not be read
88                 success, ///< The file could not be read
89                 wrongversion ///< The version of the file does not match ours
90         };
91
92
93         /// Method to check if a file is externally modified, used by 
94         /// isExternallyModified()
95         /**
96          * timestamp is fast but inaccurate. For example, the granularity
97          * of timestamp on a FAT filesystem is 2 second. Also, various operations
98          * may touch the timestamp of a file even when its content is unchanged.
99          *
100          * checksum is accurate but slow, which can be a problem when it is 
101          * frequently used, or used for a large file on a slow (network) file
102          * system.
103          *
104          * FIXME: replace this method with support/FileMonitor.
105          */
106         enum CheckMethod {
107                 checksum_method,  ///< Use file checksum
108                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
109         };
110         
111         /** Constructor
112             \param file
113             \param b  optional \c false by default
114         */
115         explicit Buffer(std::string const & file, bool b = false);
116
117         /// Destructor
118         ~Buffer();
119
120         /** High-level interface to buffer functionality.
121             This function parses a command string and executes it
122         */
123         bool dispatch(std::string const & command, bool * result = 0);
124
125         /// Maybe we know the function already by number...
126         bool dispatch(FuncRequest const & func, bool * result = 0);
127
128         /// Load the autosaved file.
129         void loadAutoSaveFile();
130
131         /// read a new document from a string
132         bool readString(std::string const &);
133         /// load a new file
134         bool readFile(support::FileName const & filename);
135
136         /// read the header, returns number of unknown tokens
137         int readHeader(Lexer & lex);
138
139         /** Reads a file without header.
140             \param par if != 0 insert the file.
141             \return \c false if file is not completely read.
142         */
143         bool readDocument(Lexer &);
144
145         ///
146         void insertStringAsLines(ParagraphList & plist,
147                 pit_type &, pos_type &,
148                 Font const &, docstring const &, bool);
149         ///
150         DocIterator getParFromID(int id) const;
151         /// do we have a paragraph with this id?
152         bool hasParWithID(int id) const;
153
154         ///
155         frontend::WorkAreaManager & workAreaManager() const;
156
157         /** Save file.
158             Takes care of auto-save files and backup file if requested.
159             Returns \c true if the save is successful, \c false otherwise.
160         */
161         bool save() const;
162
163         /// Write document to stream. Returns \c false if unsuccesful.
164         bool write(std::ostream &) const;
165         /// Write file. Returns \c false if unsuccesful.
166         bool writeFile(support::FileName const &) const;
167
168   /// Loads LyX file \c filename into buffer, *  and \return success 
169         bool loadLyXFile(support::FileName const & s);
170
171         /// Fill in the ErrorList with the TeXErrors
172         void bufferErrors(TeXErrors const &, ErrorList &) const;
173
174         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
175         bool makeLaTeXFile(support::FileName const & filename,
176                            std::string const & original_path,
177                            OutputParams const &,
178                            bool output_preamble = true,
179                            bool output_body = true) const;
180         /** Export the buffer to LaTeX.
181             If \p os is a file stream, and params().inputenc is "auto" or
182             "default", and the buffer contains text in different languages
183             with more than one encoding, then this method will change the
184             encoding associated to \p os. Therefore you must not call this
185             method with a string stream if the output is supposed to go to a
186             file. \code
187             odocfstream ofs;
188             ofs.open("test.tex");
189             writeLaTeXSource(ofs, ...);
190             ofs.close();
191             \endcode is NOT equivalent to \code
192             odocstringstream oss;
193             writeLaTeXSource(oss, ...);
194             odocfstream ofs;
195             ofs.open("test.tex");
196             ofs << oss.str();
197             ofs.close();
198             \endcode
199          */
200         void writeLaTeXSource(odocstream & os,
201                            std::string const & original_path,
202                            OutputParams const &,
203                            bool output_preamble = true,
204                            bool output_body = true) const;
205         ///
206         void makeDocBookFile(support::FileName const & filename,
207                              OutputParams const & runparams_in,
208                              bool only_body = false) const;
209         ///
210         void writeDocBookSource(odocstream & os, std::string const & filename,
211                              OutputParams const & runparams_in,
212                              bool only_body = false) const;
213         /// returns the main language for the buffer (document)
214         Language const * language() const;
215         /// get l10n translated to the buffers language
216         docstring const B_(std::string const & l10n) const;
217
218         ///
219         int runChktex();
220         /// return true if the main lyx file does not need saving
221         bool isClean() const;
222         ///
223         bool isBakClean() const;
224         ///
225         bool isDepClean(std::string const & name) const;
226
227         /// whether or not disk file has been externally modified
228         bool isExternallyModified(CheckMethod method) const;
229
230         /// save timestamp and checksum of the given file.
231         void saveCheckSum(support::FileName const & file) const;
232
233         /// mark the main lyx file as not needing saving
234         void markClean() const;
235
236         ///
237         void markBakClean() const;
238
239         ///
240         void markDepClean(std::string const & name);
241
242         ///
243         void setUnnamed(bool flag = true);
244
245         ///
246         bool isUnnamed() const;
247
248         /// Mark this buffer as dirty.
249         void markDirty();
250
251         /// Returns the buffer's filename. It is always an absolute path.
252         support::FileName fileName() const;
253
254         /// Returns the buffer's filename. It is always an absolute path.
255         std::string absFileName() const;
256
257         /// Returns the the path where the buffer lives.
258         /// It is always an absolute path.
259         std::string filePath() const;
260
261         /** A transformed version of the file name, adequate for LaTeX.
262             \param no_path optional if \c true then the path is stripped.
263         */
264         std::string latexName(bool no_path = true) const;
265
266         /// Get thee name and type of the log.
267         std::string logName(LogType * type = 0) const;
268
269         /// Change name of buffer. Updates "read-only" flag.
270         void setFileName(std::string const & newfile);
271
272         /// Set document's parent Buffer.
273         void setParent(Buffer const *);
274         Buffer const * parent();
275
276         /** Get the document's master (or \c this if this is not a
277             child document)
278          */
279         Buffer const * masterBuffer() const;
280
281         /// Is buffer read-only?
282         bool isReadonly() const;
283
284         /// Set buffer read-only flag
285         void setReadonly(bool flag = true);
286
287         /// returns \c true if the buffer contains a LaTeX document
288         bool isLatex() const;
289         /// returns \c true if the buffer contains a DocBook document
290         bool isDocBook() const;
291         /// returns \c true if the buffer contains a Wed document
292         bool isLiterate() const;
293
294         /** Validate a buffer for LaTeX.
295             This validates the buffer, and returns a struct for use by
296             #makeLaTeX# and others. Its main use is to figure out what
297             commands and packages need to be included in the LaTeX file.
298             It (should) also check that the needed constructs are there
299             (i.e. that the \refs points to coresponding \labels). It
300             should perhaps inset "error" insets to help the user correct
301             obvious mistakes.
302         */
303         void validate(LaTeXFeatures &) const;
304
305         /// Update the cache with all bibfiles in use (including bibfiles
306         /// of loaded child documents).
307         void updateBibfilesCache() const;
308         /// Return the cache with all bibfiles in use (including bibfiles
309         /// of loaded child documents).
310         EmbeddedFileList const & getBibfilesCache() const;
311         ///
312         void getLabelList(std::vector<docstring> &) const;
313
314         ///
315         void changeLanguage(Language const * from, Language const * to);
316
317         ///
318         bool isMultiLingual() const;
319
320         ///
321         BufferParams & params();
322         BufferParams const & params() const;
323
324         /** The list of paragraphs.
325             This is a linked list of paragraph, this list holds the
326             whole contents of the document.
327          */
328         ParagraphList & paragraphs();
329         ParagraphList const & paragraphs() const;
330
331         /// LyX version control object.
332         LyXVC & lyxvc();
333         LyXVC const & lyxvc() const;
334
335         /// Where to put temporary files.
336         std::string const temppath() const;
337
338         /// Used when typesetting to place errorboxes.
339         TexRow const & texrow() const;
340
341         ///
342         ParIterator par_iterator_begin();
343         ///
344         ParConstIterator par_iterator_begin() const;
345         ///
346         ParIterator par_iterator_end();
347         ///
348         ParConstIterator par_iterator_end() const;
349
350         /** \returns true only when the file is fully loaded.
351          *  Used to prevent the premature generation of previews
352          *  and by the citation inset.
353          */
354         bool isFullyLoaded() const;
355         /// Set by buffer_funcs' newFile.
356         void setFullyLoaded(bool);
357
358         /// Our main text (inside the top InsetText)
359         Text & text() const;
360
361         /// Our top InsetText
362         Inset & inset() const;
363
364         //
365         // Macro handling
366         //
367         /// Collect macro definitions in paragraphs
368         void updateMacros() const;
369         /// Iterate through the whole buffer and try to resolve macros
370         void updateMacroInstances() const;
371
372         /// List macro names of this buffer, the parent and the children
373         void listMacroNames(MacroNameSet & macros) const;
374         /// Collect macros of the parent and its children in front of this buffer.
375         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
376
377         /// Return macro defined before pos (or in the master buffer)
378         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
379         /// Return macro defined anywhere in the buffer (or in the master buffer)
380         MacroData const * getMacro(docstring const & name, bool global = true) const;
381         /// Return macro defined before the inclusion of the child
382         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
383
384         /// Replace the inset contents for insets which InsetCode is equal
385         /// to the passed \p inset_code.
386         void changeRefsIfUnique(docstring const & from, docstring const & to,
387                 InsetCode code);
388
389         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
390         /// including preamble
391         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
392                 bool full_source);
393
394         /// Access to error list.
395         /// This method is used only for GUI visualisation of Buffer related
396         /// errors (like parsing or LateX compilation). This method is const
397         /// because modifying the returned ErrorList does not touch the document
398         /// contents.
399         ErrorList & errorList(std::string const & type) const;
400
401         /// The Toc backend.
402         /// This is useful only for screen visualisation of the Buffer. This
403         /// method is const because modifying this backend does not touch
404         /// the document contents.
405         TocBackend & tocBackend() const;
406         
407         //@{
408         EmbeddedFileList & embeddedFiles();
409         EmbeddedFileList const & embeddedFiles() const;
410         bool embedded() const;
411         //@}
412
413         Undo & undo();
414        
415         /// This function is called when the buffer is changed.
416         void changed() const;
417         /// This function is called when the buffer structure is changed.
418         void structureChanged() const;
419         /// This function is called when some parsing error shows up.
420         void errors(std::string const & err) const;
421         /// This function is called when the buffer busy status change.
422         void setBusy(bool on) const;
423         /// This function is called when the buffer readonly status change.
424         void setReadOnly(bool on) const;
425         /// Update window titles of all users.
426         void updateTitles() const;
427         /// Reset autosave timers for all users.
428         void resetAutosaveTimers() const;
429         ///
430         void message(docstring const & msg) const;
431
432         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
433
434         ///
435         void autoSave() const;
436
437         /// return the format of the buffer on a string
438         std::string bufferFormat() const;
439
440         ///
441         bool doExport(std::string const & format, bool put_in_tempdir,
442                 std::string & result_file) const;
443         ///
444         bool doExport(std::string const & format, bool put_in_tempdir) const;
445         ///
446         bool preview(std::string const & format) const;
447         ///
448         bool isExportable(std::string const & format) const;
449         ///
450         std::vector<Format const *> exportableFormats(bool only_viewable) const;
451
452         ///
453         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
454         References & references(docstring const & label);
455         References const & references(docstring const & label) const;
456         void clearReferenceCache() const;
457         void setInsetLabel(docstring const & label, InsetLabel const * il);
458         InsetLabel const * insetLabel(docstring const & label) const;
459
460 private:
461         /// search for macro in local (buffer) table or in children
462         MacroData const * getBufferMacro(docstring const & name,
463                                          DocIterator const & pos) const;
464         /** Update macro table starting with position of it
465             \param it in some text inset
466         */
467         void updateMacros(DocIterator & it,
468                                      DocIterator & scope) const;
469
470         /// 
471         bool readFileHelper(support::FileName const & s);
472         ///
473         std::vector<std::string> backends() const;
474         /** Inserts a file into a document
475             \return \c false if method fails.
476         */
477         ReadStatus readFile(Lexer &, support::FileName const & filename,
478                             bool fromString = false);
479
480         /// Use the Pimpl idiom to hide the internals.
481         class Impl;
482         /// The pointer never changes although *pimpl_'s contents may.
483         Impl * const d;
484
485         frontend::GuiBufferDelegate * gui_;
486
487         /// This function is called when the buffer structure is changed.
488         Signal structureChanged_;
489         /// This function is called when some parsing error shows up.
490         //Signal errors(std::string const &) = 0;
491         /// This function is called when some message shows up.
492         //Signal message(docstring const &) = 0;
493         /// This function is called when the buffer busy status change.
494         //Signal setBusy(bool) = 0;
495         /// Reset autosave timers for all users.
496         Signal resetAutosaveTimers_;
497 };
498
499
500 } // namespace lyx
501
502 #endif