A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

77 lines
1.7 KiB

  1. /*
  2. * Copyright © 2018 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package parse
  11. import (
  12. "github.com/writeas/web-core/stringmanip"
  13. "regexp"
  14. "strings"
  15. )
  16. var (
  17. titleElementReg = regexp.MustCompile("</?p>")
  18. urlReg = regexp.MustCompile("https?://")
  19. imgReg = regexp.MustCompile(`!\[([^]]+)\]\([^)]+\)`)
  20. )
  21. // PostLede attempts to extract the first thought of the given post, generally
  22. // contained within the first line or sentence of text.
  23. func PostLede(t string, includePunc bool) string {
  24. // Adjust where we truncate if we want to include punctuation
  25. iAdj := 0
  26. if includePunc {
  27. iAdj = 1
  28. }
  29. // Find lede within first line of text
  30. nl := strings.IndexRune(t, '\n')
  31. if nl > -1 {
  32. t = t[:nl]
  33. }
  34. // Strip certain HTML tags
  35. t = titleElementReg.ReplaceAllString(t, "")
  36. // Strip URL protocols
  37. t = urlReg.ReplaceAllString(t, "")
  38. // Strip image URL, leaving only alt text
  39. t = imgReg.ReplaceAllString(t, " $1 ")
  40. // Find lede within first sentence
  41. punc := strings.Index(t, ". ")
  42. if punc > -1 {
  43. t = t[:punc+iAdj]
  44. }
  45. punc = stringmanip.IndexRune(t, '。')
  46. if punc > -1 {
  47. c := []rune(t)
  48. t = string(c[:punc+iAdj])
  49. }
  50. return t
  51. }
  52. // TruncToWord truncates the given text to the provided limit.
  53. func TruncToWord(s string, l int) (string, bool) {
  54. truncated := false
  55. c := []rune(s)
  56. if len(c) > l {
  57. truncated = true
  58. s = string(c[:l])
  59. spaceIdx := strings.LastIndexByte(s, ' ')
  60. if spaceIdx > -1 {
  61. s = s[:spaceIdx]
  62. }
  63. }
  64. return s, truncated
  65. }