PyProTex.py 43.2 KB
Newer Older
1
#!/usr/bin/env python
2
#
3
# Copyright 2015 Momme Butenschoen, Plymouth Marine Laboratory
4
#
5
# This file is part of the PyProTex module.
6
#
7
# PyProTex is free software: you can redistribute it and/or modify it
8 9
# under the terms of the Lesser GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# PyProTex is distributed in the hope that it will be useful, but
13 14
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser
15
# NU General Public License for more details.
16 17
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser
18
# NU General Public License for more details.
19
# You should have received a copy of the Lesser GNU General Public License
20
# along with PyProTex. If not, see <http://www.gnu.org/licenses/>.
21
#
22 23 24 25
# Address:
# Plymouth Marine Laboratory
# Prospect Place, The Hoe
# Plymouth, PL1 3DH, UK
26
#
27
# Email:
28
# momm@pml.ac.uk
29
#
30
#  $Id: PyProTex,v15.04 $
31
#
32 33 34 35 36
#BOI
#
# !TITLE: PyProTex
# !AUTHOR: Momme Butensch\xf6n
# !AFFILIATION: Plymouth Marine Laboratory
37
# !DATE: 20 April 2015
38 39
#
#EOI
40 41 42 43 44
#BOP
#
# !ROUTINE: PyProTex - Translates DAO Prologues to LaTeX
#
# !INTERFACE:
45
#         PyProTex.py [-hbgACFS] ] [+-nlsxf] src_file[s]
46 47 48
#
# !DESCRIPTION:
#         This as a python version of the protex perl tool.
Momme Butenschoen's avatar
Momme Butenschoen committed
49
#         The perl tool was developed at the Goddard Space Flight Center
50 51 52 53 54
#         by Arlindo Da Silva, Will Sawyer, and others under no specific
#         license.
#         The python version was created by Momme Butenschoen at the
#         Plymouth Marine Laboratory
#         The adaptation is based on the version 2.0 as downloaded from
Momme Butenschoen's avatar
Momme Butenschoen committed
55
#         http://acmg.seas.harvard.edu/geos/wiki\_docs/protex/protex.tar.gz
56
#
57 58
#         Python class to produce a \LaTeX compatible document
#         from a DAO Fortran source code with standard Pro\TeX
59 60
#         prologues.
#         By default, output is directed to stdout.
61 62
#
# \noindent
63 64 65 66 67 68 69 70
# {\bf Command Line Switches:} \vspace{0.2cm}
#
# \begin{center}
# \begin{tabular}{|c|l|} \hline \hline
#   -h   & Human mode: descriptions only, no code information \\
#        & implies -l and -s \\ \hline
#   -b   & Bare mode, meaning no preamble, etc.  \\ \hline
#   -i   & internal mode: omit prologues marked !BOPI  \\ \hline
Momme Butenschoen's avatar
Momme Butenschoen committed
71
#   -g   & Use GEOS style. Implies -n unless overidden. \\ hline
72 73 74
#   +/-n & New Page for each subsection (wastes paper) \\ \hline
#   +/-l & Listing mode, default is prologues only \\ \hline
#   +/-s & Shut-up mode, i.e., ignore any code from BOC to EOC \\ \hline
75
#   +/-x & No LaTeX mode, i.e., put description tag in verbatim mode \\ \hline
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#   +/-f & No source file info \\ \hline
#   -A   & Ada code \\ \hline
#   -C   & C++ code \\ \hline
#   -F   & F90 code (default) \\ \hline
#   -S   & Shell script \\ \hline
#   none & Print help message \\ \hline \hline
# \end{tabular}
# \end{center}
#
# The options can appear in any order.  The options -g, -h and -b, affect
# the input from all files listed on command-line input.  Each of the
# remaining options affects only the input from the files listed after
# the option and prior to any overriding option.  The plus sign
# turns off the option.  For example, the command-line input,
# \bv
#      protex -bnS File1 -F File2.f +n File3.f
# \ev
# will cause the option, {\tt -n} to affect the input from the files,
# {\tt File} and {\tt File2.f}, but not from {\tt File3.f}.  The
# {\tt -S} option is implemented for {\tt File1} but is overridden by
# the {\tt -F} for files {\tt File2.f} and {\tt File3.f}.
#
#
# !SEE ALSO:
#         For a more detailed description of ProTeX functionality,
#         DAO Prologue and other conventions, consult:
#
103
#           Sawyer, W., and A. da Silva, 1997: ProTeX: A Sample
104 105
#           Fortran 90 Source Code Documentation System.
#           DAO Office Note 97-11
106
#
107
# !AUTHOR:
108
#        Momme Butensch\xf6n
109 110 111 112 113 114 115 116 117 118 119 120 121
#
# !REVISION HISTORY:
#
#  20Dec1995  da Silva  First experimental version
#  10Nov1996  da Silva  First internal release (v1.01)
#  28Jun1997  da Silva  Modified so that !DESCRIPTION can appear after
#             !INTERFACE, and !INPUT PARAMETERS etc. changed to italics.
#  02Jul1997  Sawyer    Added shut-up mode
#  20Oct1997  Sawyer    Added support for shell scripts
#  11Mar1998  Sawyer    Added: file name, date in header, C, script support
#  05Aug1998  Sawyer    Fixed LPChang-bug-support-for-files-with-underscores
#  10Oct1998  da Silva  Introduced -f option for removing source file info
#                       from subsection, etc.  Added help (WS).
122
#  06Dec1999  C. Redder Added LaTeX command "\label{sec:prologues}" just
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
#                       after the beginning of the proglogue section.
#  13Dec1999  C. Redder Increased flexbility in command-line
#                       interface.  The options can appear in any
#                       order which will allow the user to implement
#                       options for select files.
#  01Feb1999  C. Redder Added \usepackage commands to preamble of latex
#                       document to include the packages amsmath, epsfig
#                       and hangcaption.
#  10May2000  C. Redder Revised LaTeX command "\label{sec:prologues}"
#                       to "\label{app:ProLogues}"
#  10/10/2002 da Silva  Introduced ARGUMENTS keyword, touch ups.
#
#  15Jan2003  R. Staufer  Modified table of contents to print only section headers - no descriptions
#
#  25Feb2003  R. Staufer  Added BOPI/EOPI and -i (internal) switch to provide the option of omitting prologue information from output files.
#  31Mar2014  M. Butenschoen Changed heading style to use sections for modules.
#  22Oct2014  M. Butenschoen Conversion to python with consistent changes 
#                            to use part for top-level and section for 2nd
#                            level. Introduced -d option.
142
#  22Oct2014  M. Butenschoen -h option produces human-readable
143 144
#                            documentation with desciptions only omitting
#                            any iformation on the code.
145 146 147 148
#                            Help string is now obtained by calling without
#                            argument
#  20Apr2015 M. Butenschoen  Compability for python 2 and 3 in one file,
#                            python3 specific version therefore obsolete.
149 150 151
#
#EOP
#----------------------------------------------------------------------------
Momme Butenschoen's avatar
Momme Butenschoen committed
152
#BOC
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
from __future__ import print_function
from sys import argv,stderr,stdout
from time import localtime,strftime
from re import sub
from re import split as rsplit


#----------------------------------------------------------------------

class PyProTex:

  def __init__(self,Choices):
    """Initiate class object with all options and settings.
           Choices: PyProTex options as list of input strings in."""
    
    #Option Classes
    self.GlobOptions=["h","b","g"]
    self.LangOptions=["A","C","F","S"]
    self.SwOptions=["f","l","i","n","s","x"]
    self.RegOptions=self.GlobOptions+self.LangOptions
    #Default Options
    self.opt={}
    self.opt["h"]=0
    self.opt["b"]=0
    self.opt["g"]=0
    self.opt["f"]=0
    self.opt["l"]=0
    self.opt["i"]=0
    self.opt["n"]=0
    self.opt["s"]=0
    self.opt["x"]=0
    self.opt["A"]=0
    self.opt["C"]=0
    self.opt["S"]=0
    self.opt["F"]=1 #Default file format is fortran

    # Optional Prologue Keywords
    # --------------------------
    self.keys =    [ "!INTERFACE:",
            "!USES:",
            "!PUBLIC TYPES:",
            "!PRIVATE TYPES:",
            "!PUBLIC MEMBER FUNCTIONS:",
            "!PRIVATE MEMBER FUNCTIONS:",
            "!PUBLIC DATA MEMBERS:",
            "!PARAMETERS:",
            "!ARGUMENTS:",
            "!IMPORT STATE:",
            "!EXPORT STATE:",
            "!INTERNAL STATE:",
            "!DEFINED PARAMETERS:",
            "!INPUT PARAMETERS:",
            "!INPUT/OUTPUT PARAMETERS:",
            "!OUTPUT PARAMETERS:",
            "!RETURN VALUE:",
            "!REVISION HISTORY:",
            "!BUGS:",
            "!SEE ALSO:",
            "!SYSTEM ROUTINES:",
            "!FILES USED:",
            "!REMARKS:",
            "!TO DO:",
            "!CALLING SEQUENCE:",
            "!AUTHOR:",
            "!CALLED FROM:",
            "!LOCAL VARIABLES:" ]

    # Initialize these for clarity
    # ----------------------------
    self.intro = 0             # doing introduction?
    self.prologue = 0          # doing prologue?
    self.first = 1             # first prologue?
    self.source = 0            # source code mode?
    self.verb = 0              # verbatim mode?
    self.tpage = 0             # title page?
    self.begdoc = 0            # has \begin{document} been written?
    self.descr_verb = 0        # descriptions in LaTeX mode
    self.inspec = 0            # are we processing state specs (GEOS)
    self.initem = 0            # are we processing state specs item (GEOS)
    self.skip = 0              # don't skip

    # Set for global options
    # -----------------------

    for choice in Choices:
      option = self.CheckOpts (choice,)
      if option:
        rc=self.GetOpts(choice,self.GlobOptions)
      else:
        print("Invalid option string: {}".format(choice),file=stderr)
        self.print_help(dest=stderr)

    # g option requires n option 
    # ---------------------

    if self.opt["g"]: self.opt["n"]=1

    # Set for non-global options
    # -----------------------
    for choice in Choices:
      option = self.CheckOpts(choice,quiet_mode=1)+1 
      if option:
        self.GetOpts(choice,self.SwOptions)
        self.SetLanguage(choice)

    # d option implies s option and no l option
    # ---------------------

    if self.opt["g"]:
        self.opt["s"]=1
        self.opt["l"]=0

265 266 267
    # Determine the type of code, set corresponding search strings
    # ------------------------------------------------------------
    # DEFAULT: FORTRAN
268 269 270 271 272 273 274 275 276 277 278 279
    if self.opt["A"]:            # ADA
        self.comment_string = '--'
        self.boi_string = '--BOI'
        self.eoi_string = '--EOI'
        self.bop_string = '--BOP'
        self.eop_string = '--EOP'
        self.bopi_string = '--BOPI'
        self.eopi_string = '--EOPI'
        self.boc_string = '--BOC'
        self.eoc_string = '--EOC'
        self.boe_string = '--BOE'
        self.eoe_string = '--EOE'
280
    elif self.opt["C"]: # C
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        self.comment_string = '//'
        self.boi_string = '//BOI'
        self.eoi_string = '//EOI'
        self.bop_string = '//BOP'
        self.eop_string = '//EOP'
        self.bopi_string = '//BOPI'
        self.eopi_string = '//EOPI'
        self.boc_string = '//BOC'
        self.eoc_string = '//EOC'
        self.boe_string = '//BOE'
        self.eoe_string = '//EOE'
    elif self.opt["S"]:            # Script
        self.comment_string = '#'
        self.boi_string = '#BOI'
        self.eoi_string = '#EOI'
        self.bop_string = '#BOP'
        self.eop_string = '#EOP'
298 299
        self.bopi_string = '#BOPI'
        self.eopi_string = '#EOPI'
300 301 302 303
        self.boc_string = '#BOC'
        self.eoc_string = '#EOC'
        self.boe_string = '#BOE'
        self.eoe_string = '#EOE'
304
    else:
305 306 307 308 309 310 311 312 313 314 315 316
        self.comment_string = '!'
        self.boi_string = '!BOI'
        self.eoi_string = '!EOI'
        self.bop_string = '!BOP'
        self.eop_string = '!EOP'
        self.bopi_string = '!BOPI'
        self.eopi_string = '!EOPI'
        self.boc_string = '!BOC'
        self.eoc_string = '!EOC'
        self.boe_string = '!BOE'
        self.eoe_string = '!EOE'

317 318
    # Set date
    # --------
319
    self.Date = strftime("%a %b %d %T %Z",localtime())
320

321 322 323 324 325 326 327 328 329
    # Initial LaTeX stuff
    # -------------------
    self.Str=""
    self.Str+=self.print_notice()        # auto-generation warning
    self.Str+=self.print_preamble()      # \documentclass, text dimensions, etc.
    self.Str+=self.print_macros()        # short-hand LaTeX macros

  def __call__(self,files):
    """Process all files in argument list, line by line, 
Momme Butenschoen's avatar
Momme Butenschoen committed
330 331
    compiling the documentation Tex source into the self.Str string
    attribute.
332
            files: list of input files"""
333 334 335 336 337
    # If no file arguments are present print help string and exit
    # ---------------------

    if not files: self.print_help()
    
338
    for f in files:  
339 340
       # Set file name parameters
       # ------------------------
341 342 343
       self.InputFile           = f
       self.all_path_components = self.InputFile.split("/")
       self.FileBaseName        = self.all_path_components[-1].replace("_","\_")
344 345
       # Open current file
       # -----------------
346 347 348
       try:
          fid=open(self.InputFile,'r')
       except:
349
          raise RunTimeError("Unable to open {}".format(self.InputFile))
350

351 352
       # Print page header
       # -----------------
353 354

       if self.opt["g"]:
355 356 357 358 359
          self.shname =  " "
          self.lnname =  " "
          self.units  =  " "
          self.dims   =  " "
          self.locs   =  " "
360
       else:
361
          self.Str+="\n\markboth{{Left}}{{Source File: {},  Date: {}}}\n\n".format(self.FileBaseName,self.Date)
362

363 364
       # Process input file line by line:
       # ---------------------------------------------------------
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

       Lines=fid.readlines()
       for line in Lines:
          Record=line.rstrip("\n") #strip record separator
          self._processRecord(Record)

    #close document
    self.Str+="\n"
    if self.source: self.do_eoc()
    self.Str+="\n%...............................................................\n"

    # see comment above where these are originally set.
    #print "\\setlength{\\parskip}{\\oldparskip}";
    #print "\\setlength{\\parindent}{\\oldparindent}";
    #print "\\setlength{\\baselineskip}{\\oldbaselineskip}";

    if not self.opt["b"]:
      self.Str+="\n\\end{document}"

  def _processRecord(self,Rec): 
     """Process a record according to its context."""

     Fld=Rec.split(None,9999) #split line by whitespace
     if len(Fld)==0: return #skip empty lines
     if Fld[0] == "!QUOTE:" or (self.opt["g"] and len(Fld)>1 and Fld[1] == "!!GEOS!!"):
        self.Str+="\n"
        for f in Fld[1:]:
           self.Str+="{} ".format(f)
        return

395 396
     # Start the intro at new line and switch intro on
     # -------------------------------------------
397 398 399 400 401
     if Fld[0] == self.boi_string:
        self.Str+="\n"
        self.intro = 1
        return

402 403
     # If within intro and title is given print title and switch title page on
     # -------------------------------------------
404 405
     if len(Fld)>1 and Fld[1] == '!TITLE:':
        if self.intro:
406
           self.title = "{}".format(" ".join(*Fld[2]))
407 408 409
           self.tpage = 1
           return

410 411
     # If within intro and author is given print title and switch title page on
     # -------------------------------------------
412 413
     if len(Fld)>1 and Fld[1] == '!AUTHOR:':
        if self.intro:
414
           self.author = "{}".format(" ".join(*Fld[2:]))
415 416 417
           self.tpage = 1
           return

418
     # If within intro and affiliation is given print title and set title page
419 420 421
     #       -------------------------------------------
     if len(Fld)>1 and Fld[1] == '!AFFILIATION:':
        if self.intro:
422
           self.affiliation = "{}".format(" ".join(*Fld[2:]))
423 424 425
           self.tpage = 1
           return

426 427
     # If within intro and date is given print date and switch title page on
     # -------------------------------------------
428 429
     if len(Fld)>1 and Fld[1] == '!DATE:':
        if self.intro:
430
           self.date="{}".format(" ".join(Fld[2]))
431 432 433
           self.tpage = 1
           return

434 435
     # If within intro and introduction is given print introduction header and switch title page on 
     # -------------------------------------------
436 437 438 439 440 441 442 443 444 445 446
     if len(Fld)>1 and Fld[1] == '!INTRODUCTION:':
        if self.intro:
           self.self,do_beg()
           self.Str+=" \n"
           self.Str+="%..............................................\n"
           if self.opt["g"]:
             self.Str+="\part{{\Large {} }}\n".format(" ".join(*Fld[2:]))
           else:
             self.Str+="\part{{ {} }}\n".format(" ".join(*Fld[2:]))
           return

447 448
     # close introduction and switch off intro
     # -------------------
449 450 451 452 453 454 455 456

     if Fld[0] == self.eoi_string:
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.Str+="\\newpage\n"
           self.intro = 0
           return

457 458 459 460
     # Beginning of prologue : print header and
     # switch on prologue
     # switch off verb, source and inspec
     # ---------------------
461
     if Fld[0] == self.bop_string:
Momme Butenschoen's avatar
Momme Butenschoen committed
462
        self.skip=0
463 464 465 466 467 468
        if self.source: self.do_eoc()
        self.Str+=" \n"
        self.Str+="%/////////////////////////////////////////////////////////////\n"
        self.do_beg()
        if self.first or self.opt["n"]:
           if not (self.opt["b"] or self.opt["g"]):
469
              self.Str+="\part{Routine/Function Prologues} \label{app:ProLogues}\n"
470 471 472 473 474 475 476 477 478 479 480 481
        else:
           self.Str+=" \n"
           self.Str+="\mbox{}\hrulefill\\ \n"
           self.Str+=" \n"
        self.first = 0
        self.prologue = 1
        self.verb = 0
        self.source = 0
        self.inspec = 0
        self.set_missing()   # initialise keyword check
        return

482 483
     # Beginning of internal prologue (switchable)
     # ------------------------------
484 485 486 487 488 489 490 491 492
     if Fld[0] == self.bopi_string:
        if self.opt["i"]:
           self.prologue = 0 #No internal prologue with i option
        else:
           if self.source: self.do_eoc() #if source is still active close it and close verbatim
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.do_beg()
           if self.first or self.opt["n"]:
493
              if not (self.opt["b"] or self.opt["g"]):
494 495 496 497 498 499 500 501 502 503 504 505 506
                 self.Str+="\part{Routine/Function Prologues} \label{{app:ProLogues}}\n"
           else:
              self.Str+=" \n"
              self.Str+="\mbox{}\hrulefill\\\ \n"
              self.Str+=" \n"
           self.first = 0
           self.prologue = 1
           self.verb = 0
           self.source = 0
           self.inspec = 0
           self.set_missing()    # initialise keyword check
           return

507 508
     # A new subroutine/function
     # -------------------------
509 510 511 512 513 514
     if len(Fld)>1 and Fld[1] == '!ROUTINE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["f"]:
515
              self.Str+="\n\\section{{{} }}\n\n".format(name)
516
           else:
517
              self.Str+="\n\section{{{} (Source: {})}}\n\n".format(name, self.FileBaseName)
518 519 520 521
           self.have_name = 1
           self.first = 0
           return

522 523
     # A new Module
     # ------------
524 525 526 527 528 529 530 531 532 533
     if len(Fld)>1 and Fld[1] == '!MODULE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["g"]:
              self.Str+="\n\section [{0}] {{Module {0} }}\n\n".format(name)
           else:
              if self.opt["f"]:
                 self.Str+="\n\section{{Module: {} }}\n\n".format(name)
534
              else:
535 536 537 538 539 540
                 self.Str+="\n\section{{Module: {} (Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.have_intf = 1  # fake, does not need one.
           self.first = 0
           return

541 542
     # A new include file
     # ------------------
543 544 545 546 547
     if len(Fld)>1 and Fld[1] == '!INCLUDE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
548
           if self.opt["f"]:
549 550 551 552 553 554 555 556
              self.Str+="\n\subsection{{Include File {} }}\n\n".format(name)
           else:
              self.Str+="\n\subsection{{Include File {} (Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.have_intf = 1  # fake, does not need one.
           self.first = 0
           return

557 558
     # A new INTERNAL subroutine/function
     # ----------------------------------
559 560 561 562 563 564 565 566 567 568 569 570 571
     if len(Fld)>1 and Fld[1] == '!IROUTINE:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           words = name.split()
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["g"]:
              self.Str+="\n\subsection {{{}}}\n\n".format(name)
           else:
              self.Str+="\n\subsection {{{}}}\n\n".format(name)
           self.have_name = 1
           return

572 573
     # A new CONTAINED subroutine/function
     # ----------------------------------
574 575 576 577
     if len(Fld)>1 and Fld[1] == '!CROUTINE:':          # Contained routine
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
578
           words = name.split()
579 580 581 582
           self.Str+="\n\subsection{{{}}}\n\n".format(name)
           self.have_name = 1
           return

583 584
     # A new CLASS
     # ------------
585 586 587 588 589 590 591 592 593 594 595 596 597 598
     if len(Fld)>1 and Fld[1] == '!CLASS:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not first: self.Str+="\n\\newpage\n"
           if self.opt["f"]:
              self.Str+="\n\section{{C++:  Class Interface {} }}\n\n".format( self.name_is)
           else:
              self.Str+="\n\section{{C++:  Class Interface {} (Source: {})}}\n\n".format(self.name_is,self.FileBaseName)
           self.have_name = 1
           self.have_intf = 1  # fake, does not need one.
           self.first = 0
           return

599 600
     # A new Method
     # -------------------------
601 602 603 604 605 606 607 608 609 610 611 612 613 614
     if len(Fld)>1 and Fld[1] == '!METHOD:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first:
              self.Str+="\n\\newpage\n"
           if self.opt["f"]: 
              self.Str+="\n\subsection{{{}}}\n\n".format(name)
           else:
              self.Str+="\n\subsection{{{} (Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.first = 0
           return

615 616
     # A new function
     # -------------------------
617 618 619 620 621 622 623 624 625 626 627 628 629
     if len(Fld)>1 and Fld[1] == '!FUNCTION:':
        if self.prologue:
           self.name_is = " ".join(Fld[2:])
           name=self.name_is.replace("_","\_")# Replace "_" with "\_"
           if self.opt["n"] and not self.first: self.Str+="\n\\newpage\n"
           if self.opt["f"]:
              self.Str+="\n\subsection{{{}}}\n\n".format(names)
           else:
              self.Str+="\n\subsection{{{}(Source: {})}}\n\n".format(name,self.FileBaseName)
           self.have_name = 1
           self.first = 0
           return

630 631
     # Description: what follows will be regular LaTeX (no verbatim)
     # -------------------------------------------------------------
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
     if "!DESCRIPTION:" in Rec:
        if self.prologue:
           self.skip=0 
           # if still active close verbatim and switch off 
           if self.verb:
              self.Str+="\n\end{verbatim}"
              self.Str+="\n{{\sf \\bf DESCRIPTION:\\\ }}\n\n"
              self.verb = 0
           if self.opt["x"]: #description not latex
              self.Str+="\n\\begin{verbatim} "
              self.verb = 1
              self.descr_verb = 1
           else:
              for f in Fld[2:]:
                 self.Str+="\n{} ".format(f)
           # self.Str+=" "
           self.have_desc = 1
           return

651 652
     # Handle optional keywords (these will appear as verbatim)
     # --------------------------------------------------------
653 654 655
     if self.prologue:
        for key in self.keys:
           if key in Rec:
656
             if self.opt['h']:  
657 658 659 660 661 662 663 664 665 666 667 668
                self.skip=1
                return
             else:
               if self.verb: #switch off verbatim to create heading
                 self.Str+="\n\end{verbatim}\n"
                 self.verb = 0
               k = "{}".format(key)
               ln = len(k)
               Rec=key
               if self.opt["g"]:
                 if ("/IMPORT STATE/" in key) or ("/EXPORT STATE/" in key) or ("/INTERNAL STATE/" in key):
                    if self.inspec:
669
                       self.beg_item()
670
                    self.Str+="\n \\bigskip \n {{\\bf  {} }} \n\n".format(k[1:ln])
671 672 673 674
                    self.hed_item()
                    self.inspec = 1
                    self.initem = 0
                    return
675
                 else:
676
                    self.Str+="\n{{\\bf {}}}".format(k[1:ln]) # italics
677 678
               else:
                 if ("/USES/" in key) or ("/INPUT/" in key) or ("/OUTPUT/" in key) or ("/PARAMETERS/" in key) or ("/VALUE/" in key) or  ("/ARGUMENTS/" in key):
679
                    self.Str+="\n{{\em {}}}".format(k[1:ln]) # italics
680
                 else:
681
                    self.Str+="\n{{\\sf {}}}".format(k[1:ln]) # san serif
682 683 684 685 686 687 688 689 690
               #switch verbatim back on:      
               self.Str+="\n\\begin{verbatim}"
               self.verb = 1
               self.descr_verb = 1
               if key == "!INTERFACE:":         self.have_intf = 1
               if key == "!CALLING SEQUENCE:":  self.have_intf = 1
               if key == "!REVISION HISTORY:":  self.have_hist = 1
               return

691 692
     # End of prologue
     # ---------------
693 694 695 696 697
     if Fld[0] == self.eop_string:
        if self.verb: #close and switch off verbatim
           self.Str+="\n\end{verbatim}\n"
           self.verb = 0
        if self.opt["g"] and self.inspec:
698
           self.beg_item()
699 700 701 702 703 704 705 706 707
           self.inspec = 0
        self.prologue = 0 #switch off prologue
        if self.opt["l"]:
           Fld[0] = self.boc_string
        else:
           return

     if not self.opt["s"]:

708 709
        # End of Internal Prologue
        # ------------------------
710 711 712 713 714
        if Fld[0] == self.eopi_string:
           if self.verb: #close and switch off verbatim
              self.Str+="\n\end{verbatim}\n"
              self.verb = 0
           if self.opt["g"] and self.inspec:
715
              self.beg_item()
716 717 718 719 720 721 722 723
              self.inspec = 0
           self.prologue = 0
           if self.opt["l"]:
              Fld[0] = self.boc_string
           else:
              return

        #
724 725
        # Beginning of source code section
        # --------------------------------
726 727 728 729 730 731 732 733 734 735
        if Fld[0] == self.boc_string:
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.first = 0
           self.prologue = 0
           self.source = 1
           self.Str+="\n\\begin{verbatim}"
           self.verb = 1
           return

736 737
        # End of source code
        # ------------------
738 739
        if Fld[0] == self.eoc_string:
           self.do_eoc() #if source is still active close it and close verbatim
740

741 742 743
           self.prologue = 0
           return

744 745
        # Beginning of example prologue
        # (separated in latex source but not in output)
746 747 748 749 750 751 752 753 754 755 756
        #          -----------------------------
        if Fld[0] == self.boe_string:
           if self.source: self.do_eoc() #if source is still active close it and close verbatim
           self.Str+=" \n"
           self.Str+="%/////////////////////////////////////////////////////////////\n"
           self.first = 0
           self.prologue = 1
           self.verb = 0
           self.source = 0
           return

757 758
        # End of example prologue
        # -----------------------
759 760 761 762 763 764 765 766 767 768
        if Fld[0] == self.eoe_string:
           if self.verb:
              self.Str+="\n\end{verbatim}\n"
              self.verb = 0
           self.prologue = 0
           if self.opt["l"]:
              Fld[0] = self.boc_string
           else:
              return

769 770
     # Prologue or Introduction, print regular line (except for !)
     # -----------------------------------------------------------
Momme Butenschoen's avatar
Momme Butenschoen committed
771
     if not self.skip and (self.prologue or self.intro):
772 773 774 775
        if self.verb and len(Fld)==1 and Fld[0]==self.comment_string: 
           return
        elif(self.opt["g"]):
           if self.verb and len(Fld)==2 and Fld[0]=='implicit':
776
              return
777
           elif self.verb and len(Fld)==1 and Fld[0] == 'private':
778
              return
779 780 781 782 783
        elif len(Fld)>1 and Fld[1] == "\\ev":  # special handling
           Rec = self.comment_string+" \end{verbatim}"
        Rec=Rec.replace(self.comment_string," ")       # replace comment string with blank
        if self.opt["g"] and self.inspec:
           if Fld[0] == "call":
784
              self.beg_item()
785 786 787 788
              return
           elif len(Fld)>1 and Fld[1] == "=":
              self.prc_item(Fld)
        else:
789
           self.Str+="\n{}".format(Rec)
790 791
        self.descr_verb = 0

792 793
     # Source code: print the full line
     # --------------------------------
794 795 796 797 798 799 800 801 802 803
     if self.source and not self.skip:
        self.Str+="\n"+Rec
        return

  def __str__(self,):
      return self.Str

  def CheckOpts(self,optStr,quiet_mode=0):
      """Checks options against a given list.  Outputs error message
       for any invalid option.
804

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
          string: optStr - options to be checked. (e.g. -df+x)  The
                               string must begin with a positive or
                               negative sign.  If no sign appears at the
                               beginning or by itself, then the argument
                               is not recognized as a list of options.
          string: valid_reg_options - string of valid regular options.
                               (i.e. options that are associated only
                               eith negative sign.)
          string: valid_sw_options - string of valid switch options.
                               (i.e. options that can be associated with
                               either a positive or negative sign.
          logical:   quiet mode (optional) If True then print no error
                               messages.
       Returns:         integer return code
                               = 0 if the arguement, options, is
                                  not recognized as a list of options
                               =  1 if all options are valid.
                               >  1 for the number of invalid options.
823
      """
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857

      if ( optStr=="+" or optStr=="-" ): return -1
      Options = [c for c in optStr] #split up string in single characters
      if Options[0]!="-" and Options[0]!="+": return -1
      flag = 1
      for option in Options:
        if option == "-" or option == "+": 
           option_sign = option
        else:
           if option_sign == "-":
              valid_options = self.RegOptions+self.SwOptions
           else:
              valid_options = self.SwOptions
           if option not in valid_options and quiet_mode:
              flag+=1
              print("Invalid option: {}{}\n".format(option_sign,option),file=stderr) 
              self.print_help(dest=stderr)
      return flag

  def GetOpts(self,optStr,valid_options):
      """Gets options.  If an option is valid, then self.opt[option] is
      set to 0 or 1 in relation to if the option is preceeded 
      by a positive or negative sign.
 
        string: optStr - options to be checked. (e.g. -df+x)  The
                             list must begin with a positive or
                             negative sign.  If no sign appears at the
                             beginning or by itself, then the argument
                             is not recognized as a list of options.
        string: valid_options - list of valid options (e.g. dfhx)
      Returns:         integer return code
                             = -1 if the arguement, options, is
                                not recognized as a list of options.
                             =  0 otherwise
858
      """
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

      if optStr == "+" or optStr == "-": return -1
      Options = [c for c in optStr] #split up string in single characters
      if Options[0]!="-" and Options[0]!="+": return -1
      for option in Options:
        if option == "-" or option == "+": 
           option_sign = option
        else:
           if option in valid_options:
             if option_sign == "-":
               self.opt[option] = 1
             elif option_sign == "+":
               self.opt[option] = 0
      return 0

  def SetLanguage(self,optStr):
875 876 877
      """Sets the language option.
      The last input option that is a LanguageOption will overrule
      all others,  i.e. for all other language options in the list,
878
      opt_[option] is set to 0. Other options are ignored.
879

880 881 882 883 884 885 886 887 888
        string: optStr - options to be checked. (e.g. -df+x)  The
                             list must begin with a positive or
                             negative sign.  If no sign appears at the
                             beginning or by itself, then the argument
                             is not recognized as a list of options.
      Returns:           integer return code
                             = -1 if the arguement, options, is
                                not recognized as a list of options.
                             =  0 otherwise
889
      """
890 891 892 893 894 895 896 897 898 899 900 901 902 903

      if optStr == "+" or optStr == "-": return -1
      Options = [c for c in optStr] #split up string in single characters
      ValidOptions = [c for c in self.LangOptions] #split up string in single characters
      for option in Options:
        if option != "-" and option != "+": 
           if option in self.LangOptions:
              for valid_option in self.LangOptions:
                 self.opt[valid_option]=0
              self.opt[option]=1
      return 0

  def print_help(self,dest=stdout):
      """Print help string, by default to standard output."""
904
      print("Usage:     PyProTex.py [-hbACFS] [+-nlsxf] src_file[s]",file=dest)
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
      print(" ",file=dest)
      print(" Options:",file=dest)
      print("     -h   Human mode: descriptions only, no code information",file=dest)
      print("                      implies -l and -s",file=dest)
      print("     -b   Bare mode, meaning no preamble, etc.",file=dest)
      print("     -d   descriptions only, implies +s and -l",file=dest)
      print("     +-n  New Page for each subsection (wastes paper)",file=dest)
      print("     +-l  Listing mode, default is prologues only",file=dest)
      print("     +-i  drop internal prologues",file=dest)
      print("     +-s  Shut-up mode, i.e., ignore any code from BOC to EOC",file=dest)
      print("     +-x  No LaTeX mode, i.e., put !DESCRIPTION: in verbatim mode",file=dest)
      print("     +-f  No source file info",file=dest)
      print("     -A   Ada code",file=dest)
      print("     -C   C++ code",file=dest)
      print("     -F   F90 code",file=dest)
      print("     -S   Shell script",file=dest)
      print(" ",file=dest)
      print("  The options can appear in any order.  The options, -h and -b,",file=dest)
923 924 925 926
      print("  affect the input from all files listed on command-line input.",file=dest)
      print("  Each of the remaining options effects only the input from the",file=dest)
      print("  files listed after the option and prior to any overriding",file=dest)
      print("  option.  The plus sign turns off the option.",file=dest)
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
      raise SystemExit()

  def print_notice(self,):
      """Add auto generation disclaimer to output string."""
      Str="%                **** IMPORTANT NOTICE *****" 
      Str+="% This LaTeX file has been automatically produced by PyProTex"
      Str+="% Any changes made to this file will likely be lost next time"
      Str+="% this file is regenerated from its source."
      Str+=" "
      return Str

  def print_preamble(self,):
      """Add Latex Preamble to output string."""
      Str=""
      if not self.opt["b"]:
        Str+="%------------------------ PREAMBLE --------------------------\n"
        Str+="\\documentclass[11pt]{article}\n"
        Str+="\\usepackage{amsmath,amsfonts,mathrsfs}\n"
        Str+="\\usepackage{epsfig}\n"
        Str+="\\usepackage{hangcaption}\n"
        Str+="\\textheight     9in\n"
        Str+="\\topmargin      0pt\n"
        Str+="\\headsep        1cm\n"
        Str+="\\headheight     0pt\n"
        Str+="\\textwidth      6in\n"
        Str+="\\oddsidemargin  0in\n"
        Str+="\\evensidemargin 0in\n"
        Str+="\\marginparpush  0pt\n"
        Str+="\\pagestyle{myheadings}\n"
        Str+="\\markboth{}{}\n"
        Str+="%-------------------------------------------------------------\n"

959 960
        # in your main document before you include any protex-generated files
        # for the first time, if you define these three variables as length
961 962 963 964 965
        # settings (like this:)
        #   \newlength{\oldparskip}
        #   \newlength{\oldparindent}
        #   \newlength{\oldbaselineskip}
        # then 1) comment in all the lines below, and 2) find the 3 reset lines
966 967 968
        # further down and comment in them as well.
        # then protex will override the paragraph and skip settings during
        # the source sections, but will restore the original document settings
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        # at the end.   if someone can figure out how to check to see if a
        # latex variable exists, and do a conditional section, we could make
        # this fully self-contained.
        # nsc feb 2003

        #.Str+="\\setlength{\\oldparskip}{\\parskip}\n"
        Str+="\\setlength{\\parskip}{0pt}\n"
        #Str+="\\setlength{\\oldparindent}{\\parindent}\n"
        Str+="\\setlength{\\parindent}{0pt}\n"
        #Str+="\\setlength{\\oldbaselineskip}{\\baselineskip}\n"
        Str+="\\setlength{\\baselineskip}{11pt}\n"
      return Str

  def print_macros(self,):
     """Add macro definitions to output string."""
     Str=" \n"
     Str+="%--------------------- SHORT-HAND MACROS ----------------------\n"
     Str+="\\def\\bv{\\begin{verbatim}}\n"
     Str+="\\def\\ev{\\end{verbatim}}\n"
     Str+="\\def\\be{\\begin{equation}}\n"
     Str+="\\def\\ee{\\end{equation}}\n"
     Str+="\\def\\bea{\\begin{eqnarray}}\n"
     Str+="\\def\\eea{\\end{eqnarray}}\n"
     Str+="\\def\\bi{\\begin{itemize}}\n"
     Str+="\\def\\ei{\\end{itemize}}\n"
     Str+="\\def\\bn{\\begin{enumerate}}\n"
     Str+="\\def\\en{\\end{enumerate}}\n"
     Str+="\\def\\bd{\\begin{description}}\n"
     Str+="\\def\\ed{\\end{description}}\n"
     Str+="\\def\\({\\left (}\n"
     Str+="\\def\\){\\right )}\n"
     Str+="\\def\\[{\\left [}\n"
     Str+="\\def\\]{\\right ]}\n"
     Str+="\\def\\<{\\left  \\langle}\n"
     Str+="\\def\\>{\\right \\rangle}\n"
     Str+="\\def\\cI{{\\cal I}}\n"
     Str+="\\def\\diag{\\mathop{\\rm diag}}\n"
     Str+="\\def\\tr{\\mathop{\\rm tr}}\n"
     Str+="%-------------------------------------------------------------\n"
     return Str

  def do_beg(self,):
1011
     """Add title page to output string."""
1012 1013 1014 1015
     if not self.opt["b"]:
       if self.begdoc == 0:
         if self.tpage:
            self.Str+="\n\\title{@title}\n"
1016
            self.Str+="\\author{{\sc {}}}\\\\ {{\\em {}}}\n".format(self.author,self.affiliation)
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
            self.Str+="\\date{{{}}}\n".format(self.date)
         self.Str+="\\begin{document}\n"
         if self.tpage:
            self.Str+="\\maketitle\n"
         self.Str+="\\tableofcontents\n"
         self.Str+="\\newpage\n"
         self.begdoc = 1

  def do_eoc(self,):
      """At eoc close verbatim and set source to false."""
      self.Str+="\n"
      if self.verb:
         self.Str+="\end{verbatim}"
         self.verb = 0
      self.source = 0

  def set_missing(self,):
      """Reset section attributes for later checking."""
      self.have_name = 0;      # have routine name?
      self.have_desc = 0;      # have description?
      self.have_intf = 0;      # have interface?
      self.have_hist = 0;      # have revision history?
      self.name_is = "UNKNOWN";
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049
  def check_if_all_there(self,):
       """Checking for section attributes."""
       self.check_error(self.have_name,"!(I)ROUTINE:")
       self.check_error(self.have_desc,"!DESCRIPTION:")
       self.check_error(self.have_intf,"!INTERFACE:")
       self.check_error(self.have_hist,"!REVISION HISTORY:")

  def check_error(self,flag,tag):
      """Raise prologue status error flag is False."""
1050
      if not flag:
1051
         raise RunTimeError("ProTeX: invalid prologue, missing {}: in {}".format(tag,self.name_is))
1052 1053

  def hed_item(self,):
1054 1055 1056 1057 1058 1059 1060
      self.Str+="\\bigskip\n{{ \\bf \sf \n"
      self.Str+="\makebox[.9 in][l]{{Short Name }} \n"
      self.Str+="\makebox[.9 in][l]{{Units      }} \n"
      self.Str+="\makebox[.7 in][l]{{Dims       }} \n"
      self.Str+="\makebox[.7 in][l]{{Vert Loc   }} \n"
      self.Str+="\makebox[4. in][l]{{Long Name  }} \n"
      self.Str+="}} \n \n"
1061 1062 1063 1064 1065 1066

  def beg_item(self,):
      if self.initem:
         if self.intv:
            self.Str+="\makebox[1.05 in][l]{{\$\overline{{\\rm \\bf {} }}\$}} \n".format(self.shname)
         else:
1067 1068
            self.Str+="\makebox[1.05 in][l]{{\\bf            {} }} \n".format(self.shname)
            self.Str+="\makebox[.9 in][l]{{ {} }} \n".format(units)
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
         if self.dims != " ":
            if self.dims != 'GEOS\_DIMSHORZONLY': 
               self.Str+="\makebox[.7 in][l]{{HorzOnly}}\n"
            elif self.dims == 'GEOS\_DIMSHORZVERT': 
               self.Str+="\makebox[.7 in][l]{{HorzVert}}\n"
            elif self.dims == 'GEOS\_DIMSVERTONLY': 
               self.Str+="\makebox[.7 in][l]{{VertOnly}}\n"
            elif self.dims == 'GEOS\_DIMSTILEONLY': 
               self.Str+="\makebox[.7 in][l]{{TileOnly}}\n"
            elif self.dims == 'GEOS\_DIMSTILETILE': 
               self.Str+="\makebox[.7 in][l]{{TileTile}}\n"
         if self.locs != " ":
            if(self.locs == 'GEOS\_VLOCATIONCENTER'):
                self.Str+="\makebox[.7 in][l]{{Center}}\n"
            elif(self.locs == 'GEOS\_VLOCATIONEDGE'):
                self.Str+="\makebox[.7 in][l]{{Edge  }}\n"
            elif(self.locs == 'GEOS\_VLOCATIONNONE'):
                self.Str+="\makebox[.7 in][l]{{None  }}\n"
         self.Str+="\makebox[4 in][l]{{\\small {} }}\\newline\n".format(self.lnname)
      self.initem=1
      self.dims=' '
      self.locs=' '
      self.intv=0

  def prc_units(self,Str):
      #outStr=Str.replace("+1","").replace(
      #s/\+1//g;
      #s/([a-zA-Z])\+([1-9][0-9]*)/{\1}\$^{\2}\$/g;
      #s/\-([1-9][0-9]*)/\$^{-\1}\$/g;
      pass

  def prc_item(self,fld):
      # Attribute name is the first field
      self.name = fld[0].upper()
      # Attribute value begins at the third field
      value=fld
      valStr = " ".join(value[2:])
      # Clean the value
      valStr=valStr.replace("_","\_").replace("\'","").replace("\"","").replace(",","").replace("&","")
      if self.name == "UNITS":
         self.prc_units()
      else:
         valStr=valStr.replace(" ","")
         if self.name == "SHORT_NAME":
            self.shname =  valStr
         elif self.name == "LONG_NAME":
            self.lnname =  valStr
         elif self.name == "UNITS":
            self.units  =  valStr
         elif self.name == "DIMS":
            self.dims   =  valStr.upper()
         elif self.name == "VLOCATION":
            self.locs   =  valStr.upper()
         elif self.name == "AVERAGING_INTERVAL":
            self.intv = 1
1124

1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
if __name__=="__main__":
    files=[]
    opts=[]
    for arg in argv[1:]:
        if arg[0] not in ("+","-",):
            files.append(arg)
        else:
            opts.append(arg)
    PPTex=PyProTex(opts) #set-up with all options
    PPTex(files) #translate all files
    print(PPTex)
Momme Butenschoen's avatar
Momme Butenschoen committed
1136
#EOC