shithub: hell

ref: a8234dc3c631ff8477654661683f852d61575218
dir: /format.go/

View raw version
package main

import (
	"strings"

	"github.com/chzyer/readline"
)

func hyphenate(input string) string {
	width := readline.GetScreenWidth()
	return hyphenateWithWidth(input, width)
}

func hyphenateWithWidth(input string, width int) string {
	var remainder = []rune(input)
	var result []rune

	if width < 2 {
		return input
	}

	for len(remainder) > width {
		if strings.HasPrefix(string(remainder), "\n") {
			result = append(result, '\n')
			remainder = remainder[1:]
			continue
		}

		index := strings.Index(string(remainder), "\n")
		// If a newline is found at or before the wrap position, break there.
		if index != -1 && index <= width-1 {
			result = append(result, remainder[:index]...)
			remainder = remainder[index:]
			continue
		}

		if remainder[width-1] == ' ' {
			result = append(result, remainder[:width-1]...)
			result = append(result, '\n')
			remainder = remainder[width:] // Consume the space
		} else if remainder[width-1] == '-' {
			result = append(result, remainder[:width]...)
			result = append(result, '\n')
			remainder = remainder[width:] // Consume the hyphen
		} else {
			result = append(result, remainder[:width-1]...)
			result = append(result, '-')
			remainder = remainder[width-1:]
		}
	}

	result = append(result, remainder...)
	return string(result)
}

func countEmoji(runes []rune) int {
	count := 0
	for _, r := range runes {
		if isEmoji(r) {
			count++
		}
	}
	return count
}

func isEmoji(r rune) bool {
	return r >= 0x1F600 && r <= 0x1F64F // Emoticons
}