Пример #1
0
def get_cg_info(race, template, data, target):
    if race in list(template.keys()):
        infolist = template[race]
    else:
        infolist = template['Default']
    leftcolumn = ['Name: %30.30s' % (target.name, )]
    rightcolumn = ['Race: %29.29s' % (data['Race'], )]
    for infoentry in infolist['Left']:
        if infoentry in list(data.keys()):
            w = 36 - len('%s: ' % infoentry)
            try:
                leftline = '%s: %s' % (
                    infoentry, justify(data[infoentry], width=w, align='r'))
            except TypeError as e:
                leftline = e
            leftcolumn.append(leftline)
    for infoentry in infolist['Right']:
        if infoentry in list(data.keys()):
            w = 35 - len('%s: ' % infoentry)
            try:
                rightline = '%s: %s' % (
                    infoentry, justify(data[infoentry], width=w, align='r'))
            except TypeError as e:
                rightline = e
            rightcolumn.append(rightline)
    table = evtable.EvTable(table=[leftcolumn, rightcolumn], border='incols')
    table.reformat(width=78)
    return table
Пример #2
0
    def init_str(self, text):
        """The input is a string"""

        if self._justify:
            # we must break very long lines into multiple ones. Note that this
            # will also remove spurious whitespace.
            justify_kwargs = self._justify_kwargs or {}
            width = self._justify_kwargs.get("width", self.width)
            justify_kwargs["width"] = width
            justify_kwargs["align"] = self._justify_kwargs.get("align", "l")
            justify_kwargs["indent"] = self._justify_kwargs.get("indent", 0)

            lines = []
            for line in text.split("\n"):
                if len(line) > width:
                    lines.extend(justify(line, **justify_kwargs).split("\n"))
                else:
                    lines.append(line)
        else:
            # no justification. Simple division by line
            lines = text.split("\n")

        self._data = [
            "\n".join(lines[i : i + self.height]) for i in range(0, len(lines), self.height)
        ]
        self._npages = len(self._data)
        self._paginator = self.paginator_index
Пример #3
0
def format_available_protfuncs():
    """
    Get all protfuncs in a pretty-formatted form.

    Args:
        clr (str, optional): What coloration tag to use.
    """
    out = []
    for protfunc_name, protfunc in PROT_FUNCS.items():
        out.append("- |c${name}|n - |W{docs}".format(
            name=protfunc_name, docs=protfunc.__doc__.strip().replace("\n", "")))
    return justify("\n".join(out), indent=8)
Пример #4
0
    def __init__(self,
                 caller,
                 text,
                 always_page=False,
                 session=None,
                 justify_kwargs=None,
                 **kwargs):
        """
        Initialization of the text handler.

        Args:
            caller (Object or Player): Entity reading the text.
            text (str): The text to put under paging.
            always_page (bool, optional): If `False`, the
                pager will only kick in if `text` is too big
                to fit the screen.
            session (Session, optional): If given, this session will be used
                to determine the screen width and will receive all output.
            justify_kwargs (dict, bool or None, optional): If given, this should
                be valid keyword arguments to the utils.justify() function. If False,
                no justification will be done.
            kwargs (any, optional): These will be passed on
                to the `caller.msg` method.

        """
        self._caller = caller
        self._kwargs = kwargs
        self._pages = []
        self._npages = []
        self._npos = []
        self._exit_msg = "Exited |wmore|n pager."
        if not session:
            # if not supplied, use the first session to
            # determine screen size
            sessions = caller.sessions.get()
            if not sessions:
                return
            session = sessions[0]
        self._session = session

        # set up individual pages for different sessions
        height = max(
            4,
            session.protocol_flags.get("SCREENHEIGHT", {0: _SCREEN_HEIGHT})[0]
            - 4)
        width = session.protocol_flags.get("SCREENWIDTH",
                                           {0: _SCREEN_WIDTH})[0]

        if justify_kwargs is False:
            # no justification. Simple division by line
            lines = text.split("\n")
        else:
            # we must break very long lines into multiple ones
            justify_kwargs = justify_kwargs or {}
            width = justify_kwargs.get("width", width)
            justify_kwargs["width"] = width
            justify_kwargs["align"] = justify_kwargs.get("align", 'l')
            justify_kwargs["indent"] = justify_kwargs.get("indent", 0)

            lines = justify(text, **justify_kwargs).split("\n")

        # always limit number of chars to 10 000 per page
        height = min(10000 // width, height)

        self._pages = [
            "\n".join(lines[i:i + height])
            for i in range(0, len(lines), height)
        ]
        self._npages = len(self._pages)
        self._npos = 0

        if self._npages <= 1 and not always_page:
            # no need for paging; just pass-through.
            caller.msg(text=text, **kwargs)
        else:
            # go into paging mode
            # first pass on the msg kwargs
            caller.ndb._more = self
            caller.cmdset.add(CmdSetMore)

            # goto top of the text
            self.page_top()
Пример #5
0
    def __init__(self, caller, text, always_page=False, session=None,
                 justify_kwargs=None, exit_on_lastpage=False,
                 exit_cmd=None, **kwargs):
        """
        Initialization of the text handler.

        Args:
            caller (Object or Account): Entity reading the text.
            text (str): The text to put under paging.
            always_page (bool, optional): If `False`, the
                pager will only kick in if `text` is too big
                to fit the screen.
            session (Session, optional): If given, this session will be used
                to determine the screen width and will receive all output.
            justify_kwargs (dict, bool or None, optional): If given, this should
                be valid keyword arguments to the utils.justify() function. If False,
                no justification will be done (especially important for handling
                fixed-width text content, like tables!).
            exit_on_lastpage (bool, optional): If reaching the last page without the
                page being completely filled, exit pager immediately. If unset,
                another move forward is required to exit. If set, the pager
                exit message will not be shown.
            exit_cmd (str, optional): If given, this command-string will be executed on
                the caller when the more page exits. Note that this will be using whatever
                cmdset the user had *before* the evmore pager was activated (so none of
                the evmore commands will be available when this is run).
            kwargs (any, optional): These will be passed on
                to the `caller.msg` method.

        """
        self._caller = caller
        self._kwargs = kwargs
        self._pages = []
        self._npages = []
        self._npos = []
        self.exit_on_lastpage = exit_on_lastpage
        self.exit_cmd = exit_cmd
        self._exit_msg = "Exited |wmore|n pager."
        if not session:
            # if not supplied, use the first session to
            # determine screen size
            sessions = caller.sessions.get()
            if not sessions:
                return
            session = sessions[0]
        self._session = session

        # set up individual pages for different sessions
        height = max(4, session.protocol_flags.get("SCREENHEIGHT", {0: _SCREEN_HEIGHT})[0] - 4)
        width = session.protocol_flags.get("SCREENWIDTH", {0: _SCREEN_WIDTH})[0]

        if "\f" in text:
            self._pages = text.split("\f")
            self._npages = len(self._pages)
            self._npos = 0
        else:
            if justify_kwargs is False:
                # no justification. Simple division by line
                lines = text.split("\n")
            else:
                # we must break very long lines into multiple ones
                justify_kwargs = justify_kwargs or {}
                width = justify_kwargs.get("width", width)
                justify_kwargs["width"] = width
                justify_kwargs["align"] = justify_kwargs.get("align", 'l')
                justify_kwargs["indent"] = justify_kwargs.get("indent", 0)

                lines = []
                for line in text.split("\n"):
                    if len(line) > width:
                        lines.extend(justify(line, **justify_kwargs).split("\n"))
                    else:
                        lines.append(line)

            # always limit number of chars to 10 000 per page
            height = min(10000 // max(1, width), height)

            self._pages = ["\n".join(lines[i:i + height]) for i in range(0, len(lines), height)]
            self._npages = len(self._pages)
            self._npos = 0

        if self._npages <= 1 and not always_page:
            # no need for paging; just pass-through.
            caller.msg(text=text, session=self._session, **kwargs)
        else:
            # go into paging mode
            # first pass on the msg kwargs
            caller.ndb._more = self
            caller.cmdset.add(CmdSetMore)

            # goto top of the text
            self.page_top()
Пример #6
0
Файл: say.py Проект: dimaguy/NOW
 def func(self):
     """Run the spoof command"""
     char = self.character
     here = char.location
     opt = self.switches
     args = self.args
     to_self = 'self' in opt or not here
     if not args:
         self.account.execute_cmd('help spoof')
         return
     # Optionally strip any markup /or/ just escape it,
     stripped = ansi.strip_ansi(args)
     spoof = stripped if 'strip' in opt else args.replace('|', '||')
     if 'indent' in opt:
         indent = 20
         if self.rhs:
             args = self.lhs.strip()
             indent = re.sub("[^0123456789]", '', self.rhs) or 20
             indent = int(indent)
         if to_self:
             char.msg(' ' * indent + args.rstrip())
         else:
             here.msg_contents(text=(' ' * indent + escape_braces(args.rstrip()), {'type': 'spoof'}))
     elif 'right' in opt or 'center' in opt or 'news' in opt:
         if self.rhs is not None:  # Equals sign exists.
             parameters = '' if not self.rhs else self.rhs.split()
             args = self.lhs.strip()
             if len(parameters) > 1:
                 if len(parameters) == 2:
                     outside, inside = self.rhs.split()
                 else:
                     outside, inside = [parameters[0], parameters[1]]
                 outside = re.sub("[^0123456789]", '', outside) or 0
                 inside = re.sub("[^0123456789]", '', inside) or 0
                 outside, inside = [int(max(outside, inside)), int(min(outside, inside))]
             else:
                 outside, inside = [72, 20]
         else:
             outside, inside = [72, min(int(self.rhs or 72), 20)]
         block = 'r' if 'right' in opt else 'f'
         block = 'c' if 'center' in opt else block
         for text in justify(args, width=outside, align=block, indent=inside).split('\n'):
             if to_self:
                 char.msg(text.rstrip())
             else:
                 here.msg_contents(text=(escape_braces(text.rstrip()), {'type': 'spoof'}))
     else:
         if 'strip' in opt:  # Optionally strip any markup or escape it,
             if to_self:
                 char.msg(spoof.rstrip(), options={'raw': True})
             else:
                 here.msg_contents(text=(escape_braces(spoof.rstrip()), {'type': 'spoof'}), options={'raw': True})
         elif 'dot' in opt:  # Leave leading spacing intact, remove leading dot.
             spoof = args.lstrip('.')
             if to_self:
                 char.msg(spoof.rstrip(), options={'raw': True})
             else:
                 here.msg_contents(text=(escape_braces(spoof.rstrip()), {'type': 'spoof'}), options={'raw': True})
         else:
             if to_self:
                 char.msg(args.rstrip())
             else:
                 here.msg_contents(text=(escape_braces(spoof.rstrip()), {'type': 'spoof'}))
Пример #7
0
    def __init__(self, caller, text, always_page=False, session=None,
                 justify_kwargs=None, exit_on_lastpage=False,
                 exit_cmd=None, **kwargs):
        """
        Initialization of the text handler.

        Args:
            caller (Object or Account): Entity reading the text.
            text (str): The text to put under paging.
            always_page (bool, optional): If `False`, the
                pager will only kick in if `text` is too big
                to fit the screen.
            session (Session, optional): If given, this session will be used
                to determine the screen width and will receive all output.
            justify_kwargs (dict, bool or None, optional): If given, this should
                be valid keyword arguments to the utils.justify() function. If False,
                no justification will be done.
            exit_on_lastpage (bool, optional): If reaching the last page without the
                page being completely filled, exit pager immediately. If unset,
                another move forward is required to exit. If set, the pager
                exit message will not be shown.
            exit_cmd (str, optional): If given, this command-string will be executed on
                the caller when the more page exits. Note that this will be using whatever
                cmdset the user had *before* the evmore pager was activated (so none of
                the evmore commands will be available when this is run).
            kwargs (any, optional): These will be passed on
                to the `caller.msg` method.

        """
        self._caller = caller
        self._kwargs = kwargs
        self._pages = []
        self._npages = []
        self._npos = []
        self.exit_on_lastpage = exit_on_lastpage
        self.exit_cmd = exit_cmd
        self._exit_msg = "Exited |wmore|n pager."
        if not session:
            # if not supplied, use the first session to
            # determine screen size
            sessions = caller.sessions.get()
            if not sessions:
                return
            session = sessions[0]
        self._session = session

        # set up individual pages for different sessions
        height = max(4, session.protocol_flags.get("SCREENHEIGHT", {0: _SCREEN_HEIGHT})[0] - 4)
        width = session.protocol_flags.get("SCREENWIDTH", {0: _SCREEN_WIDTH})[0]

        if justify_kwargs is False:
            # no justification. Simple division by line
            lines = text.split("\n")
        else:
            # we must break very long lines into multiple ones
            justify_kwargs = justify_kwargs or {}
            width = justify_kwargs.get("width", width)
            justify_kwargs["width"] = width
            justify_kwargs["align"] = justify_kwargs.get("align", 'l')
            justify_kwargs["indent"] = justify_kwargs.get("indent", 0)

            lines = []
            for line in text.split("\n"):
                if len(line) > width:
                    lines.extend(justify(line, **justify_kwargs).split("\n"))
                else:
                    lines.append(line)

        # always limit number of chars to 10 000 per page
        height = min(10000 // max(1, width), height)

        self._pages = ["\n".join(lines[i:i + height]) for i in range(0, len(lines), height)]
        self._npages = len(self._pages)
        self._npos = 0

        if self._npages <= 1 and not always_page:
            # no need for paging; just pass-through.
            caller.msg(text=text, session=self._session, **kwargs)
        else:
            # go into paging mode
            # first pass on the msg kwargs
            caller.ndb._more = self
            caller.cmdset.add(CmdSetMore)

            # goto top of the text
            self.page_top()
Пример #8
0
    def __init__(
        self,
        caller,
        text,
        always_page=False,
        session=None,
        justify=False,
        justify_kwargs=None,
        exit_on_lastpage=False,
        exit_cmd=None,
        **kwargs,
    ):

        """
        Initialization of the text handler.

        Args:
            caller (Object or Account): Entity reading the text.
            text (str, EvTable or iterator): The text or data to put under paging.
                - If a string, paginage normally. If this text contains
                   one or more `\f` format symbol, automatic pagination and justification
                   are force-disabled and page-breaks will only happen after each `\f`.
                - If `EvTable`, the EvTable will be paginated with the same
                   setting on each page if it is too long. The table
                   decorations will be considered in the size of the page.
                - Otherwise `text` is converted to an iterator, where each step is
                   expected to be a line in the final display. Each line
                   will be run through repr() (so one could pass a list of objects).
            always_page (bool, optional): If `False`, the
                pager will only kick in if `text` is too big
                to fit the screen.
            session (Session, optional): If given, this session will be used
                to determine the screen width and will receive all output.
            justify (bool, optional): If set, auto-justify long lines. This must be turned
                off for fixed-width or formatted output, like tables. It's force-disabled
                if `text` is an EvTable.
            justify_kwargs (dict, optional): Keywords for the justifiy function. Used only
                if `justify` is True. If this is not set, default arguments will be used.
            exit_on_lastpage (bool, optional): If reaching the last page without the
                page being completely filled, exit pager immediately. If unset,
                another move forward is required to exit. If set, the pager
                exit message will not be shown.
            exit_cmd (str, optional): If given, this command-string will be executed on
                the caller when the more page exits. Note that this will be using whatever
                cmdset the user had *before* the evmore pager was activated (so none of
                the evmore commands will be available when this is run).
            kwargs (any, optional): These will be passed on to the `caller.msg` method.

        Examples:
            super_long_text = " ... "
            EvMore(caller, super_long_text)

            from django.core.paginator import Paginator
            query = ObjectDB.objects.all()
            pages = Paginator(query, 10)  # 10 objs per page
            EvMore(caller, pages)   # will repr() each object per line, 10 to a page

            multi_page_table = [ [[..],[..]], ...]
            EvMore(caller, multi_page_table, use_evtable=True,
                   evtable_args=("Header1", "Header2"),
                   evtable_kwargs={"align": "r", "border": "tablecols"})

        """
        self._caller = caller
        self._kwargs = kwargs
        self._pages = []
        self._npages = 1
        self._npos = 0
        self.exit_on_lastpage = exit_on_lastpage
        self.exit_cmd = exit_cmd
        self._exit_msg = "Exited |wmore|n pager."

        if not session:
            # if not supplied, use the first session to
            # determine screen size
            sessions = caller.sessions.get()
            if not sessions:
                return
            session = sessions[0]
        self._session = session

        # set up individual pages for different sessions
        height = max(4, session.protocol_flags.get("SCREENHEIGHT", {0: _SCREEN_HEIGHT})[0] - 4)
        width = session.protocol_flags.get("SCREENWIDTH", {0: _SCREEN_WIDTH})[0]

        if hasattr(text, "table") and hasattr(text, "get"):
            # This is an EvTable.

            table = text

            if table.height:
                # enforced height of each paged table, plus space for evmore extras
                height = table.height - 4

            # convert table to string
            text = str(text)
            justify_kwargs = None  # enforce

        if not isinstance(text, str):
            # not a string - pre-set pages of some form
            text = "\n".join(str(repr(element)) for element in make_iter(text))

        if "\f" in text:
            # we use \f to indicate the user wants to enforce their line breaks
            # on their own. If so, we do no automatic line-breaking/justification
            # at all.
            self._pages = text.split("\f")
            self._npages = len(self._pages)
        else:
            if justify:
                # we must break very long lines into multiple ones. Note that this
                # will also remove spurious whitespace.
                justify_kwargs = justify_kwargs or {}
                width = justify_kwargs.get("width", width)
                justify_kwargs["width"] = width
                justify_kwargs["align"] = justify_kwargs.get("align", "l")
                justify_kwargs["indent"] = justify_kwargs.get("indent", 0)

                lines = []
                for line in text.split("\n"):
                    if len(line) > width:
                        lines.extend(justify(line, **justify_kwargs).split("\n"))
                    else:
                        lines.append(line)
            else:
                # no justification. Simple division by line
                lines = text.split("\n")

            # always limit number of chars to 10 000 per page
            height = min(10000 // max(1, width), height)

            # figure out the pagination
            self._pages = ["\n".join(lines[i : i + height]) for i in range(0, len(lines), height)]
            self._npages = len(self._pages)

        if self._npages <= 1 and not always_page:
            # no need for paging; just pass-through.
            caller.msg(text=self._get_page(0), session=self._session, **kwargs)
        else:
            # go into paging mode
            # first pass on the msg kwargs
            caller.ndb._more = self
            caller.cmdset.add(CmdSetMore)

            # goto top of the text
            self.page_top()
Пример #9
0
 def func(self):
     """Run the spoof command"""
     char = self.character
     cmd = self.cmdstring
     here = char.location
     opt = self.switches
     args = self.args
     to_self = 'self' in opt or not here
     if not args:
         self.account.execute_cmd('help spoof', session=self.session)
         return
     # Optionally strip any markup /or/ just escape it,
     stripped = ansi.strip_ansi(args)
     spoof = stripped if 'strip' in opt else args.replace('|', '||')
     if 'indent' in opt:
         indent = 20
         if self.rhs:
             args = self.lhs.strip()
             indent = re.sub("[^0123456789]", '', self.rhs) or 20
             indent = int(indent)
         if to_self:
             char.msg(' ' * indent + args.rstrip())
         else:
             here.msg_contents(text=(' ' * indent + escape_braces(args.rstrip()), {'type': 'spoof'}))
     elif 'right' in opt or 'center' in opt or 'news' in opt:  # Use Justify
         if self.rhs is not None:  # Equals sign exists.
             parameters = '' if not self.rhs else self.rhs.split()
             args = self.lhs.strip()
             if len(parameters) > 1:
                 if len(parameters) == 2:
                     outside, inside = self.rhs.split()
                 else:
                     outside, inside = [parameters[0], parameters[1]]
                 outside = re.sub("[^0123456789]", '', outside) or 0
                 inside = re.sub("[^0123456789]", '', inside) or 0
                 outside, inside = [int(max(outside, inside)), int(min(outside, inside))]
             else:
                 outside, inside = [72, 20]
         else:
             outside, inside = [72, min(int(self.rhs or 72), 20)]
         block = 'l'
         if 'right' in opt:
             block = 'r'
         elif 'center' in opt:
             block = 'c'
         elif 'news' in opt:
             block = 'f'
         for text in justify(args, width=outside, align=block, indent=inside).split('\n'):
             if to_self:
                 char.msg(text.rstrip())
             else:
                 here.msg_contents(text=(escape_braces(text.rstrip()), {'type': 'spoof'}))
     else:
         if 'strip' in opt:  # Optionally strip any markup or escape it,
             if to_self:
                 char.msg(spoof.rstrip(), options={'raw': True})
             else:
                 here.msg_contents(text=(escape_braces(spoof.rstrip()), {'type': 'spoof'}), options={'raw': True})
         elif '.' in cmd:  # Leave leading spacing intact by using self.raw and not stripping left whitespace
             # Adding <pre> and </pre> to all output in case one of the viewers is using webclient
             spoof = self.raw.rstrip()
             if to_self:
                 char.msg(('<code>' + spoof + '</code>', {'type': 'spoof'}), options={'raw': True})
             else:
                 here.msg_contents(text=('<code>' + spoof + '</code>', {'type': 'spoof'}), options={'raw': True})
         else:
             if to_self:
                 char.msg(args.rstrip())
             else:
                 here.msg_contents(text=(escape_braces(spoof.rstrip()), {'type': 'spoof'}))
Пример #10
0
    def __init__(self, caller, text, always_page=False, session=None, justify_kwargs=None, **kwargs):
        """
        Initialization of the text handler.

        Args:
            caller (Object or Player): Entity reading the text.
            text (str): The text to put under paging.
            always_page (bool, optional): If `False`, the
                pager will only kick in if `text` is too big
                to fit the screen.
            session (Session, optional): If given, this session will be used
                to determine the screen width and will receive all output.
            justify_kwargs (dict, bool or None, optional): If given, this should
                be valid keyword arguments to the utils.justify() function. If False,
                no justification will be done.
            kwargs (any, optional): These will be passed on
                to the `caller.msg` method.

        """
        self._caller = caller
        self._kwargs = kwargs
        self._pages = []
        self._npages = []
        self._npos = []
        self._exit_msg = "Exited |wmore|n pager."
        if not session:
            # if not supplied, use the first session to
            # determine screen size
            sessions = caller.sessions.get()
            if not sessions:
                return
            session = sessions[0]
        self._session = session

        # set up individual pages for different sessions
        height = max(4, session.protocol_flags.get("SCREENHEIGHT", {0:_SCREEN_HEIGHT})[0] - 4)
        width = session.protocol_flags.get("SCREENWIDTH", {0:_SCREEN_WIDTH})[0]

        if justify_kwargs is False:
            # no justification. Simple division by line
            lines = text.split("\n")
        else:
            # we must break very long lines into multiple ones
            justify_kwargs = justify_kwargs or {}
            width = justify_kwargs.get("width", width)
            justify_kwargs["width"] = width
            justify_kwargs["align"] = justify_kwargs.get("align", 'l')
            justify_kwargs["indent"] = justify_kwargs.get("indent", 0)

            lines = justify(text, **justify_kwargs).split("\n")

        # always limit number of chars to 10 000 per page
        height = min(10000 // width, height)

        self._pages = ["\n".join(lines[i:i+height]) for i in range(0, len(lines), height)]
        self._npages = len(self._pages)
        self._npos = 0

        if self._npages <= 1 and not always_page:
            # no need for paging; just pass-through.
            caller.msg(text=text, **kwargs)
        else:
            # go into paging mode
            # first pass on the msg kwargs
            caller.ndb._more = self
            caller.cmdset.add(CmdSetMore)

            # goto top of the text
            self.page_top()