Skip to content

Commit 1f34611

Browse files
committed
Sorts strings naturally
1 parent 925d8ed commit 1f34611

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

taskwiki/sort.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from taskwiki import constants
22
from taskwiki import util
3+
import re
4+
35

46
class TaskSorter(object):
57
def __init__(self, cache, tasks, sortstring=None):
@@ -110,16 +112,26 @@ def generic_compare(self, first, second, method):
110112
return True if method == 'gt' else False
111113

112114
# Non-None values should respect reverse flags, use loop_method
113-
if first_value < second_value:
115+
if self.natural_compare(first_value, second_value) == -1:
114116
return True if loop_method == 'lt' else False
115-
elif first_value > second_value:
117+
elif self.natural_compare(first_value, second_value) == 1:
116118
return True if loop_method == 'gt' else False
117119
else:
118120
# Values are equal, move to next distinguisher
119121
continue
120122

121123
return True if method == 'eq' else False
122124

125+
def natural_compare(self, a, b):
126+
if not isinstance(a, str):
127+
return (a > b) - (a < b)
128+
129+
convert = lambda text: int(text) if text.isdigit() else text.lower()
130+
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+).*$', key)]
131+
132+
return (alphanum_key(a) > alphanum_key(b)) - (alphanum_key(a) < alphanum_key(b))
133+
134+
123135
def lt(self, first, second):
124136
return self.generic_compare(first, second, 'lt')
125137

0 commit comments

Comments
 (0)