~ubuntu-branches/ubuntu/natty/moin/natty-updates

« back to all changes in this revision

Viewing changes to MoinMoin/formatter/text_html.py

  • Committer: Bazaar Package Importer
  • Author(s): Jonas Smedegaard
  • Date: 2008-06-22 21:17:13 UTC
  • mto: This revision was merged to the branch mainline in revision 18.
  • Revision ID: james.westby@ubuntu.com-20080622211713-inlv5k4eifxckelr
ImportĀ upstreamĀ versionĀ 1.7.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
from MoinMoin import wikiutil, i18n
15
15
from MoinMoin.Page import Page
16
16
from MoinMoin.action import AttachFile
17
 
from MoinMoin.support.python_compatibility import set
 
17
from MoinMoin.support.python_compatibility import set, rsplit
18
18
 
19
19
# insert IDs into output wherever they occur
20
20
# warning: breaks toggle line numbers javascript
189
189
        self._in_code_line = 0
190
190
        self._code_area_js = 0
191
191
        self._code_area_state = ['', 0, -1, -1, 0]
192
 
 
193
 
        # code format string. id - code block id, num - line number.
194
 
        # Caution: upon changing, also check line numbers hide/show js.
195
 
        self._code_id_format = "%(id)s_%(num)d"
196
 
 
197
192
        self._show_section_numbers = None
198
193
        self.pagelink_preclosed = False
199
194
        self._is_included = kw.get('is_included', False)
415
410
        """
416
411
 
417
412
        if hasattr(self, 'page'):
418
 
            self.request.uid_generator.begin(self.page.page_name)
 
413
            self.request.begin_include(self.page.page_name)
419
414
 
420
415
        result = []
421
416
        # Use the content language
439
434
        result.append(self.anchordef('bottom'))
440
435
        result.append(self._close('div', newline=newline))
441
436
        if hasattr(self, 'page'):
442
 
            self.request.uid_generator.end()
 
437
            self.request.end_include()
443
438
        return ''.join(result)
444
439
 
445
440
    def lang(self, on, lang_name):
493
488
        wikitag, wikiurl, wikitail, wikitag_bad = wikiutil.resolve_interwiki(self.request, interwiki, pagename)
494
489
        wikiurl = wikiutil.mapURL(self.request, wikiurl)
495
490
        if wikitag == 'Self': # for own wiki, do simple links
 
491
            if '#' in wikitail:
 
492
                wikitail, kw['anchor'] = rsplit(wikitail, '#', 1)
496
493
            wikitail = wikiutil.url_unquote(wikitail)
497
494
            try: # XXX this is the only place where we access self.page - do we need it? Crashes silently on actions!
498
495
                pagename = wikiutil.AbsPageName(self.page.page_name, wikitail)
505
502
                if querystr:
506
503
                    separator = ('?', '&')['?' in href]
507
504
                    href = '%s%s%s' % (href, separator, wikiutil.makeQueryString(querystr))
508
 
                anchor = kw.get('anchor')
509
 
                if anchor:
510
 
                    href = '%s#%s' % (href, self.sanitize_to_id(anchor))
511
505
                if wikitag_bad:
512
506
                    html_class = 'badinterwiki'
513
507
                else:
607
601
 
608
602
    # Attachments ######################################################
609
603
 
610
 
    def attachment_link(self, on, url=None, querystr=None, **kw):
 
604
    def attachment_link(self, on, url=None, **kw):
611
605
        """ Link to an attachment.
612
606
 
613
607
            @param on: 1/True=start link, 0/False=end link
615
609
        """
616
610
        assert on in (0, 1, False, True) # make sure we get called the new way, not like the 1.5 api was
617
611
        _ = self.request.getText
618
 
        if querystr is None:
619
 
            querystr = {}
 
612
        querystr = kw.get('querystr', {})
620
613
        assert isinstance(querystr, dict) # new in 1.6, only support dicts
621
614
        if 'do' not in querystr:
622
615
            querystr['do'] = 'view'
626
619
            fname = wikiutil.taintfilename(filename)
627
620
            if AttachFile.exists(self.request, pagename, fname):
628
621
                target = AttachFile.getAttachUrl(pagename, fname, self.request, do=querystr['do'])
629
 
                if not 'title' in kw:
630
 
                    kw['title'] = "attachment:%s" % url
631
 
                kw['css'] = 'attachment'
 
622
                title = "attachment:%s" % url
 
623
                css = 'attachment'
632
624
            else:
633
 
                target = AttachFile.getAttachUrl(pagename, fname, self.request, do='upload_form')
634
 
                kw['title'] = _('Upload new attachment "%(filename)s"') % {'filename': fname}
635
 
                kw['css'] = 'attachment nonexistent'
636
 
            return self.url(on, target, **kw)
 
625
                target = AttachFile.getAttachUrl(pagename, fname, self.request, upload=True)
 
626
                title = _('Upload new attachment "%(filename)s"') % {'filename': fname}
 
627
                css = 'attachment nonexistent'
 
628
            return self.url(on, target, css=css, title=title)
637
629
        else:
638
630
            return self.url(on)
639
631
 
644
636
        exists = AttachFile.exists(self.request, pagename, fname)
645
637
        if exists:
646
638
            kw['css'] = 'attachment'
647
 
            kw['src'] = AttachFile.getAttachUrl(pagename, fname, self.request, addts=1)
 
639
            kw['src'] = AttachFile.getAttachUrl(pagename, filename, self.request, addts=1)
648
640
            title = _('Inlined image: %(url)s') % {'url': self.text(url)}
649
641
            if not 'title' in kw:
650
642
                kw['title'] = title
656
648
            title = _('Upload new attachment "%(filename)s"') % {'filename': fname}
657
649
            img = self.icon('attachimg')
658
650
            css = 'nonexistent'
659
 
            target = AttachFile.getAttachUrl(pagename, fname, self.request, do='upload_form')
 
651
            target = AttachFile.getAttachUrl(pagename, fname, self.request, upload=True)
660
652
            return self.url(1, target, css=css, title=title) + img + self.url(0)
661
653
 
662
654
    def attachment_drawing(self, url, text, **kw):
663
 
        # ToDo try to move this to a better place e.g. __init__
664
 
        try:
665
 
            drawing_action = AttachFile.get_action(self.request, url, do='modify')
666
 
            assert drawing_action is not None
667
 
            attachment_drawing = wikiutil.importPlugin(self.request.cfg, 'action',
668
 
                                              drawing_action, 'attachment_drawing')
669
 
            return attachment_drawing(self, url, text, **kw)
670
 
        except (wikiutil.PluginMissingError, wikiutil.PluginAttributeError, AssertionError):
671
 
            return url
 
655
        _ = self.request.getText
 
656
        pagename, filename = AttachFile.absoluteName(url, self.page.page_name)
 
657
        fname = wikiutil.taintfilename(filename)
 
658
        drawing = fname
 
659
        fname = fname + u".png"
 
660
        filename = filename + u".png"
 
661
        # fallback for old gif drawings (1.1 -> 1.2)
 
662
        exists = AttachFile.exists(self.request, pagename, fname)
 
663
        if not exists:
 
664
            gfname = fname[:-4] + u".gif"
 
665
            gfilename = filename[:-4] + u".gif"
 
666
            exists = AttachFile.exists(self.request, pagename, gfname)
 
667
            if exists:
 
668
                fname, filename = gfname, gfilename
 
669
 
 
670
        # check whether attachment exists, possibly point to upload form
 
671
        drawing_url = AttachFile.getAttachUrl(pagename, fname, self.request, drawing=drawing, upload=True)
 
672
        if not exists:
 
673
            linktext = _('Create new drawing "%(filename)s (opens in new window)"')
 
674
            return (self.url(1, drawing_url) +
 
675
                    self.text(linktext % {'filename': fname}) +
 
676
                    self.url(0))
 
677
 
 
678
        mappath = AttachFile.getFilename(self.request, pagename, drawing + u'.map')
 
679
 
 
680
        # check for map file
 
681
        if os.path.exists(mappath):
 
682
            # we have a image map. inline it and add a map ref to the img tag
 
683
            try:
 
684
                map = file(mappath, 'r').read()
 
685
            except IOError:
 
686
                pass
 
687
            except OSError:
 
688
                pass
 
689
            else:
 
690
                mapid = 'ImageMapOf' + drawing
 
691
                # replace MAPNAME
 
692
                map = map.replace('%MAPNAME%', mapid)
 
693
                # add alt and title tags to areas
 
694
                map = re.sub('href\s*=\s*"((?!%TWIKIDRAW%).+?)"', r'href="\1" alt="\1" title="\1"', map)
 
695
                # add in edit links plus alt and title attributes
 
696
                alt = title = _('Edit drawing %(filename)s (opens in new window)') % {'filename': self.text(fname)}
 
697
                map = map.replace('%TWIKIDRAW%"', '%s" alt="%s" title="%s"' % (drawing_url, alt, title))
 
698
                # unxml, because 4.01 concrete will not validate />
 
699
                map = map.replace('/>', '>')
 
700
                alt = title = _('Clickable drawing: %(filename)s') % {'filename': self.text(fname)}
 
701
                src = AttachFile.getAttachUrl(pagename, filename, self.request, addts=1)
 
702
                return (map + self.image(alt=alt, title=title, src=src, usemap='#'+mapid, css="drawing"))
 
703
        else:
 
704
            alt = title = _('Edit drawing %(filename)s (opens in new window)') % {'filename': self.text(fname)}
 
705
            src = AttachFile.getAttachUrl(pagename, filename, self.request, addts=1)
 
706
            return (self.url(1, drawing_url) +
 
707
                    self.image(alt=alt, title=title, src=src, css="drawing") +
 
708
                    self.url(0))
 
709
 
672
710
 
673
711
    # Text ##############################################################
674
712
 
824
862
}
825
863
function addnumber(did, nstart, nstep) {
826
864
  var c = document.getElementById(did), l = c.firstChild, n = 1;
827
 
  if (!isnumbered(c)) {
 
865
  if (!isnumbered(c))
828
866
    if (typeof nstart == 'undefined') nstart = 1;
829
867
    if (typeof nstep  == 'undefined') nstep = 1;
830
 
    var n = nstart;
 
868
    n = nstart;
831
869
    while (l != null) {
832
870
      if (l.tagName == 'SPAN') {
833
871
        var s = document.createElement('SPAN');
834
 
        var a = document.createElement('A');
835
 
        s.className = 'LineNumber';
836
 
        a.appendChild(document.createTextNode(nformat(n,4,'')));
837
 
        a.href = '#' + did + '_' + n;
838
 
        s.appendChild(a);
839
 
        s.appendChild(document.createTextNode(' '));
 
872
        s.className = 'LineNumber'
 
873
        s.appendChild(document.createTextNode(nformat(n,4,' ')));
840
874
        n += nstep;
841
 
        if (l.childNodes.length) {
842
 
          l.insertBefore(s, l.firstChild);
843
 
        }
844
 
        else {
845
 
          l.appendChild(s);
846
 
        }
 
875
        if (l.childNodes.length)
 
876
          l.insertBefore(s, l.firstChild)
 
877
        else
 
878
          l.appendChild(s)
847
879
      }
848
880
      l = l.nextSibling;
849
881
    }
850
 
  }
851
882
  return false;
852
883
}
853
884
function remnumber(did) {
854
885
  var c = document.getElementById(did), l = c.firstChild;
855
 
  if (isnumbered(c)) {
 
886
  if (isnumbered(c))
856
887
    while (l != null) {
857
888
      if (l.tagName == 'SPAN' && l.firstChild.className == 'LineNumber') l.removeChild(l.firstChild);
858
889
      l = l.nextSibling;
859
890
    }
860
 
  }
861
891
  return false;
862
892
}
863
893
function togglenumber(did, nstart, nstep) {
872
902
</script>
873
903
"""
874
904
 
875
 
    def code_area(self, on, code_id, code_type='code', show=0, start=-1, step=-1, msg=None):
 
905
    def code_area(self, on, code_id, code_type='code', show=0, start=-1, step=-1):
876
906
        """Creates a formatted code region, with line numbering.
877
907
 
878
908
        This region is formatted as a <div> with a <pre> inside it.  The
885
915
 
886
916
        Call once with on=1 to start the region, and a second time
887
917
        with on=0 to end it.
888
 
 
889
 
        the msg string is not escaped
890
918
        """
891
919
        _ = self.request.getText
892
920
        res = []
898
926
            self._in_code_area = 1
899
927
            self._in_code_line = 0
900
928
            # id in here no longer used
901
 
            self._code_area_state = [None, show, start, step, start, ci]
902
 
 
903
 
            if msg:
904
 
                attr = {'class': 'codemsg'}
905
 
                res.append(self._open('div', attr={'class': 'codemsg'}))
906
 
                res.append(msg)
907
 
                res.append(self._close('div'))
 
929
            self._code_area_state = [None, show, start, step, start]
908
930
 
909
931
            # Open the code div - using left to right always!
910
932
            attr = {'class': 'codearea', 'lang': 'en', 'dir': 'ltr'}
949
971
        if on:
950
972
            res += '<span class="line">'
951
973
            if self._code_area_state[1] > 0:
952
 
                res += ('<span class="LineNumber"><a href="#%(fmt)s">%%(num)4d</a> </span><span class="LineAnchor" id="%(fmt)s"></span>' % {'fmt': self._code_id_format, }) % {
953
 
                    'id': self._code_area_state[5],
954
 
                    'num': self._code_area_state[4],
955
 
                    }
 
974
                res += '<span class="LineNumber">%4d </span>' % (self._code_area_state[4], )
956
975
                self._code_area_state[4] += self._code_area_state[3]
957
976
        self._in_code_line = on != 0
958
977
        return res