@@ -113,46 +113,51 @@ def _fragment(tpl: str, msg: Message) -> str:
113
113
114
114
@staticmethod
115
115
def _user_range_to_python_range (
116
- ref : str ,
116
+ ref : str , allow_single : bool = True , strict_range : bool = True
117
117
) -> Tuple [Optional [int ], Optional [int ]]:
118
- c = ref .count (" " )
119
- if c == 0 :
120
- if ref == "." :
118
+ tokens = ref .split ()
119
+ if not tokens :
120
+ raise ValueError ("No indices provided" )
121
+ if len (tokens ) == 1 :
122
+ if tokens [0 ] == "." :
121
123
return (None , None )
122
- start = end = ref
123
- elif c == 1 :
124
- start , end = ref .split ()
124
+ if not allow_single :
125
+ raise ValueError ("Wrong number of indices" )
126
+ start = end = tokens [0 ]
127
+ elif len (tokens ) == 2 :
128
+ start , end = tokens
125
129
else :
126
130
raise ValueError ("Wrong number of indices" )
127
131
128
- if start == "." :
129
- py_start = None
130
- else :
131
- py_start = int (start )
132
- if py_start > 0 :
133
- py_start -= 1 # Python indices are zero-based
134
- if end == "." :
135
- py_end = None
136
- else :
137
- py_end = int (end )
138
- if py_end > 0 :
139
- py_end -= 1 # Python indices are zero-based
140
- py_end += 1 # Python indices are end exclusive
141
- elif py_end == - 1 :
142
- py_end = None
132
+ def _convert (token : str , is_start : bool ) -> Optional [int ]:
133
+ if token == "." :
134
+ return None
135
+ val = int (token )
136
+ if is_start :
137
+ return val - 1 if val > 0 else val
143
138
else :
144
- py_end += 1 # Python indices are end exclusive
139
+ if val > 0 :
140
+ return val
141
+ elif val == - 1 :
142
+ return None
143
+ else :
144
+ return val + 1
145
145
146
- if c == 0 :
147
- # Don't return an empty range
146
+ py_start = _convert (start , True )
147
+ py_end = _convert (end , False )
148
+
149
+ if len (tokens ) == 1 :
148
150
if py_start == - 1 :
149
151
py_end = None
150
152
elif py_start is not None :
151
153
py_end = py_start + 1
152
-
153
- if py_start is not None and py_end is not None and py_start >= py_end :
154
+ if (
155
+ strict_range
156
+ and py_start is not None
157
+ and py_end is not None
158
+ and py_start >= py_end
159
+ ):
154
160
raise ValueError ("Range end is beyond its start" )
155
-
156
161
return py_start , py_end
157
162
158
163
@staticmethod
0 commit comments